@bitsocial/bitsocial-react-hooks 0.1.52 → 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/README.md CHANGED
@@ -1,1544 +1,89 @@
1
- [![CI](https://github.com/bitsocialnet/bitsocial-react-hooks/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/bitsocialnet/bitsocial-react-hooks/actions/workflows/CI.yml)
2
- [![Coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/bitsocialnet/bitsocial-react-hooks/master/badges/coverage.json)](https://github.com/bitsocialnet/bitsocial-react-hooks/blob/master/scripts/write-coverage-badge.mjs)
3
- [![License](https://img.shields.io/badge/license-GPL--3.0--or--later-red.svg)](https://github.com/bitsocialnet/bitsocial-react-hooks/blob/master/LICENSE)
4
- [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](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
- React hooks for the Bitsocial protocol. Build decentralized, serverless social apps with React using a familiar hooks API — fetch feeds, comments, author profiles, manage accounts, publish content, and more, all without a central server.
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
- await expandTimeWindow(60 * 60 * 24 * 7)
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
- ```jsx
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
- <Virtuoso
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
+ [![The Bitsocial React Hooks playground: editable React code beside a social feed with author portraits, post images, and reply counts.](docs/assets/readme/playground.jpg)](https://hooks.bitsocial.net/#playground)
949
14
 
950
- Comments automatically drop out of this feed once they are no longer returned by the pending-approval mod-queue pages.
15
+ *Edit a component and see the result. The playground uses simulated content and publishes nothing.*
951
16
 
952
- #### Approve a pending approval comment
17
+ Supports **React 16.8+**. Used by [5chan](https://github.com/bitsocialnet/5chan).
953
18
 
954
- ```jsx
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
- #### Edit an account
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
- // comments published in a pseudonymous community (comment.pseudonymityMode is set) keep their community-assigned author instead, because the account identity was never published.
1069
- // note: accountComment.index can change after deletions; prefer commentCid for stable identifiers
1070
-
1071
- // all my own votes
1072
- const { accountVotes } = useAccountVotes();
1073
-
1074
- // my own comments in memes.eth
1075
- const communityAddress = "memes.eth";
1076
- const myCommentsInMemesEth = useAccountComments({ communityAddress });
1077
-
1078
- // my own posts in memes.eth
1079
- const filter = useCallback(
1080
- (comment) => comment.communityAddress === communityAddress && !comment.parentCid,
1081
- [communityAddress],
1082
- );
1083
- const myPostsInMemesEth = useAccountComments({ filter });
1084
-
1085
- // my own replies in a post with cid 'Qm...'
1086
- const postCid = "Qm...";
1087
- const filter = useCallback((comment) => comment.postCid === postCid, [postCid]);
1088
- const myCommentsInSomePost = useAccountComments({ filter });
1089
-
1090
- // my own replies to a comment with cid 'Qm...'
1091
- const parentCommentCid = "Qm...";
1092
- const myRepliesToSomeComment = useAccountComments({ parentCid: parentCommentCid });
1093
-
1094
- // recent own comments in memes.eth, newest first, one page at a time
1095
- const recentMyCommentsInMemesEth = useAccountComments({
1096
- communityAddress,
1097
- newerThan: 60 * 60 * 24 * 30,
1098
- sortType: "new",
1099
- page: 0,
1100
- pageSize: 20,
1101
- });
1102
-
1103
- // get one own comment directly by cid
1104
- const accountComment = useAccountComment({ commentCid: "Qm..." });
1105
-
1106
- // get a specific set of own comments by account comment index
1107
- const replacementReplies = useAccountComments({ commentIndices: [5, 7, 9] });
1108
-
1109
- // voted profile tab helpers
1110
- const recentUpvotes = useAccountVotes({
1111
- vote: 1,
1112
- newerThan: 60 * 60 * 24 * 30,
1113
- sortType: "new",
1114
- page: 0,
1115
- pageSize: 20,
1116
- });
1117
-
1118
- // know if you upvoted a comment already with cid 'Qm...'
1119
- const { vote } = useAccountVote({ commentCid: "Qm..." });
1120
- console.log(vote); // 1, -1 or 0
1121
-
1122
- // my own pending posts in a feed
1123
- const { feed } = useFeed({
1124
- communities: [{ name: communityAddress }],
1125
- accountComments: { newerThan: Infinity, append: false },
1126
- });
1127
-
1128
- // my own pending replies in a replies feed
1129
- const { replies } = useReplies({
1130
- comment: post,
1131
- accountComments: { newerThan: Infinity, append: false },
1132
- });
1133
-
1134
- // pending local account comments are reconciled with their approved network version
1135
- // so the same post or reply is not shown twice after moderation approval
1136
- // published account replies stay visible and are deduplicated by cid while
1137
- // canonical replies propagate; explicitly purged replies are hidden after an
1138
- // exhausted canonical feed refreshes past their timestamp
1139
- ```
1140
-
1141
- #### Determine if a comment is your own
1142
-
1143
- ```jsx
1144
- const account = useAccount();
1145
- const comment = useComment({ commentCid });
1146
- const isMyOwnComment = account?.author.address === comment?.author.address;
1147
- ```
1148
-
1149
- #### Get account notifications
1150
-
1151
- ```jsx
1152
- const { notifications, markAsRead } = useNotifications();
1153
- for (const notification of notifications) {
1154
- console.log(notification);
1155
- }
1156
- await markAsRead();
1157
-
1158
- const johnsNotifications = useNotifications({ accountName: "John" });
1159
- for (const notification of johnsNotifications.notifications) {
1160
- console.log(notification);
1161
- }
1162
- await johnsNotifications.markAsRead();
1163
-
1164
- // get the unread notification counts for all accounts
1165
- const { accounts } = useAccounts();
1166
- const accountsUnreadNotificationsCounts = accounts?.map(
1167
- (account) => account.unreadNotificationCount,
1168
- );
1169
- ```
1170
-
1171
- #### Block an address (author, community or multisub)
1172
-
1173
- ```jsx
1174
- const address: 'community-address.eth' // or 'author-address.eth' or '12D3KooW...'
1175
- const {blocked, unblock, block} = useBlock({address})
21
+ Add the package to an existing React app:
1176
22
 
1177
- if (blocked) {
1178
- console.log(`'${address}' is blocked`)
1179
- }
1180
- else {
1181
- console.log(`'${address}' is not blocked`)
1182
- }
1183
-
1184
- // to block
1185
- block()
1186
-
1187
- // to unblock
1188
- unblock()
1189
- ```
1190
-
1191
- #### Block a cid (hide a comment)
1192
-
1193
- ```jsx
1194
- const { blocked, unblock, block } = useBlock({ cid: "Qm..." });
1195
-
1196
- if (blocked) {
1197
- console.log(`'${cid}' is blocked`);
1198
- } else {
1199
- console.log(`'${cid}' is not blocked`);
1200
- }
1201
-
1202
- // to block
1203
- block();
1204
-
1205
- // to unblock
1206
- unblock();
1207
- ```
1208
-
1209
- #### Save a comment
1210
-
1211
- Saved comments are kept in the account's `savedComments` list and are included when the account is exported.
1212
-
1213
- ```jsx
1214
- const { saved, saveComment, unsaveComment } = useSaveComment({ commentCid: "Qm..." });
1215
-
1216
- if (saved) {
1217
- await unsaveComment();
1218
- } else {
1219
- await saveComment();
1220
- }
1221
- ```
1222
-
1223
- #### (Desktop only) Create a community
1224
-
1225
- ```jsx
1226
- const createCommunityOptions = { title: "My community title" };
1227
- const { createdCommunity, createCommunity } = useCreateCommunity(createCommunityOptions);
1228
- await createCommunity();
1229
-
1230
- // it is recommended to redirect to `p/${createdCommunity.address}` after creation
1231
- if (createdCommunity?.address) {
1232
- console.log("created community with title", createdCommunity.title);
1233
- history.push(`/p/${createdCommunity.address}`);
1234
- }
1235
-
1236
- // after the community is created, fetch it using
1237
- const { accountCommunities } = useAccountCommunities();
1238
- const accountCommunityAddresses = Object.keys(accountCommunities);
1239
- const communities = useCommunities({
1240
- communities: accountCommunityAddresses.map((communityAddress) => ({ name: communityAddress })),
1241
- });
1242
- // or
1243
- const _community = useCommunity({ community: { name: createdCommunity.address } });
1244
- ```
1245
-
1246
- #### (Desktop only) Export communities
1247
-
1248
- ```jsx
1249
- // Export one community.
1250
- const { communityExports, exportCommunity, state, error } = useExportCommunity({
1251
- communityAddress: "your-community-address.eth",
1252
- });
1253
- await exportCommunity();
1254
-
1255
- // Export several communities at the same time.
1256
- const exportMany = useExportCommunity({
1257
- communityAddresses: ["community-1.eth", "community-2.eth"],
1258
- });
1259
- await exportMany.exportCommunity();
1260
-
1261
- // Export every community listed by the active account's pkc client.
1262
- const exportAll = useExportCommunity();
1263
- await exportAll.exportCommunity();
1264
-
1265
- if (state === "succeeded") {
1266
- console.log("started exports", communityExports);
1267
- }
1268
- if (state === "failed") {
1269
- console.log("failed to start export", error.message);
1270
- }
23
+ ```bash
24
+ yarn add @bitsocial/bitsocial-react-hooks
1271
25
  ```
1272
26
 
1273
- #### (Desktop only) List the communities you created
27
+ Render this component in the browser with an existing community name:
1274
28
 
1275
29
  ```jsx
1276
- const { accountCommunities } = useAccountCommunities();
1277
- const ownerCommunityAddresses = Object.keys(accountCommunities).filter(
1278
- (communityAddress) => accountCommunities[communityAddress].role?.role === "owner",
1279
- );
1280
- const communities = useCommunities({
1281
- communities: ownerCommunityAddresses.map((communityAddress) => ({ name: communityAddress })),
1282
- });
1283
- ```
1284
-
1285
- #### (Desktop only) Edit your community settings
30
+ import { useCommunity } from "@bitsocial/bitsocial-react-hooks";
1286
31
 
1287
- If the account's pkc client hosts the community (it is listed in `pkc.communities`), the edit is applied locally. Otherwise it is published as a `CommunityEdit` over pubsub, even when the account is the owner, and the hosting node accepts it from the owner or an admin (only the owner can change `address` or `roles`).
32
+ export default function CommunityCard({ name }) {
33
+ const community = useCommunity({ community: { name } });
1288
34
 
1289
- ```jsx
1290
- const onChallenge = async (challenges: Challenge[], communityEdit: CommunityEdit) => {
1291
- let challengeAnswers: string[]
1292
- try {
1293
- challengeAnswers = await getChallengeAnswersFromUser(challenges)
1294
- }
1295
- catch (e) {}
1296
- if (challengeAnswers) {
1297
- await communityEdit.publishChallengeAnswers(challengeAnswers)
35
+ if (!community.hasCachedData) {
36
+ return (
37
+ <p role="status">
38
+ {community.error?.message || "Loading community…"}
39
+ </p>
40
+ );
1298
41
  }
1299
- }
1300
-
1301
- const onChallengeVerification = (challengeVerification, communityEdit) => {
1302
- console.log('challenge verified', challengeVerification)
1303
- }
1304
-
1305
- const onError = (error, communityEdit) => console.error(error)
1306
-
1307
- // add ENS to your community
1308
- const editCommunityOptions = {
1309
- communityAddress: '12D3KooWANwdyPERMQaCgiMnTT1t3Lr4XLFbK1z4ptFVhW2ozg1z', // the previous address before changing it
1310
- address: 'your-community-address.eth', // the new address to change to
1311
- onChallenge,
1312
- onChallengeVerification,
1313
- onError
1314
- }
1315
-
1316
- await publishCommunityEdit()
1317
-
1318
- // edit other community settings
1319
- const editCommunityOptions = {
1320
- communityAddress: 'your-community-address.eth', // the address of the community to change
1321
- title: 'Your title',
1322
- description: 'Your description',
1323
- onChallenge,
1324
- onChallengeVerification,
1325
- onError
1326
- }
1327
- const {publishCommunityEdit} = usePublishCommunityEdit(editCommunityOptions)
1328
- await publishCommunityEdit()
1329
-
1330
- // verify if ENS was set correctly, use {cache: false} or it won't update
1331
- const {resolvedAddress} = useResolvedCommunityAddress({communityAddress: 'your-community-address.eth', cache: false})
1332
-
1333
- // result
1334
- if (state === 'succeeded') {
1335
- console.log('Succeeded resolving address', resolvedAddress)
1336
- console.log('ENS set correctly', resolvedAddress === community.signer.address)
1337
- }
1338
- if (state === 'failed') {
1339
- console.log('Failed resolving address', error.message)
1340
- }
1341
-
1342
- // pending
1343
- if (state === 'resolving') {
1344
- console.log('Resolving address from chain provider URL', chainProvider.urls)
1345
- }
1346
- ```
1347
-
1348
- #### Export and import account
1349
-
1350
- ```jsx
1351
- import {
1352
- exportAccount,
1353
- importAccount,
1354
- setActiveAccount,
1355
- setAccountsOrder,
1356
- } from "@bitsocial/bitsocial-react-hooks";
1357
-
1358
- // New accounts default to `Account {author short address}`, while custom and legacy names are preserved.
1359
- const activeAccount = useAccount();
1360
- const activeAccountName = activeAccount.name;
1361
-
1362
- // export active account, tell user to copy or download this json
1363
- const activeAccountJson = await exportAccount();
1364
-
1365
- // import account
1366
- await importAccount(activeAccountJson);
1367
-
1368
- // Importing the same identity again uses the next available numeric suffix.
1369
- const importedAccountName = `${activeAccountName} 2`;
1370
- const importedAccount = useAccount(importedAccountName);
1371
-
1372
- // make imported account active account
1373
- await setActiveAccount(importedAccountName);
1374
-
1375
- // reorder the accounts list
1376
- await setAccountsOrder([importedAccountName, activeAccountName]);
1377
- ```
1378
-
1379
- #### View the status of a comment edit
1380
-
1381
- ```jsx
1382
- let comment = useComment({ commentCid });
1383
- const { state: editedCommentState, editedComment } = useEditedComment({ comment });
1384
-
1385
- // if the comment has a succeeded, failed or pending edit, use the edited comment
1386
- if (editedComment) {
1387
- comment = editedComment;
1388
- }
1389
-
1390
- let editLabel;
1391
- if (editedCommentState === "succeeded") {
1392
- editLabel = { text: "EDITED", color: "green" };
1393
- }
1394
- if (editedCommentState === "pending") {
1395
- editLabel = { text: "PENDING EDIT", color: "orange" };
1396
- }
1397
- if (editedCommentState === "failed") {
1398
- editLabel = { text: "FAILED EDIT", color: "red" };
1399
- }
1400
- ```
1401
-
1402
- #### View the status of a specific comment edit property
1403
-
1404
- ```jsx
1405
- const comment = useComment({ commentCid });
1406
- const editedComment = useEditedComment({ comment });
1407
- if (editedComment.failedEdits.removed !== undefined) {
1408
- console.log("failed editing comment.removed property");
1409
- }
1410
- if (editedComment.succeededEdits.removed !== undefined) {
1411
- console.log("succeeded editing comment.removed property");
1412
- }
1413
- if (editedCommentResult.pendingEdits.removed !== undefined) {
1414
- console.log("pending editing comment.removed property");
1415
- }
1416
42
 
1417
- // view the full comment with all edited properties (both succeeded and pending)
1418
- console.log(editedComment.editedComment);
1419
- console.log(editedComment.editedComment.commentModeration?.removed);
1420
-
1421
- // view the state of all edits of the comment
1422
- console.log(editedComment.state); // 'unedited' | 'succeeded' | 'pending' | 'failed'
1423
- ```
1424
-
1425
- Moderation fields are mirrored on both the top-level keys like `comment.removed` and the nested `comment.commentModeration.removed` shape.
1426
-
1427
- #### List all comment and community edits the account has performed
1428
-
1429
- ```jsx
1430
- const { accountEdits } = useAccountEdits();
1431
- for (const accountEdit of accountEdits) {
1432
- console.log(accountEdit);
43
+ return (
44
+ <article>
45
+ <h1>{community.title || name}</h1>
46
+ <p>{community.description}</p>
47
+ </article>
48
+ );
1433
49
  }
1434
- console.log(`there's ${accountEdits.length} account edits`);
1435
-
1436
- // get only the account edits of a specific comment
1437
- const commentCid = "Qm...";
1438
- const filter = useCallback((edit) => edit.commentCid === commentCid, [commentCid]); // important to use useMemo or the same function or will cause rerenders
1439
- const { accountEdits } = useAccountEdits({ filter });
1440
-
1441
- // only get account edits in a specific community
1442
- const communityAddress = "news.eth";
1443
- const filter = useCallback(
1444
- (edit) => edit.communityAddress === communityAddress,
1445
- [communityAddress],
1446
- );
1447
- const { accountEdits } = useAccountEdits({ filter });
1448
50
  ```
1449
51
 
1450
- #### Get replies to a post (nested or flat)
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.
1451
53
 
1452
- ```jsx
1453
- import { useReplies, useComment, useAccountComment } from "@bitsocial/bitsocial-react-hooks";
54
+ ## Explore the docs
1454
55
 
1455
- // NOTE: recommended to use the same replies options for all depths, or will load slower
1456
- const useRepliesOptions = {
1457
- sortType: "best",
1458
- flat: false,
1459
- repliesPerPage: 20,
1460
- onlyIfCached: false,
1461
- accountComments: { newerThan: Infinity, append: false },
1462
- };
56
+ Read the guides at [hooks.bitsocial.net](https://hooks.bitsocial.net/), or browse their source here:
1463
57
 
1464
- // accountComments keeps pending and published local replies visible while
1465
- // canonical replies propagate and deduplicates them by cid; explicitly purged
1466
- // replies are hidden after an exhausted feed refreshes past their timestamp
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.
1467
63
 
1468
- const Reply = ({ reply, updatedReply }) => {
1469
- const { replies, updatedReplies, bufferedReplies, hasMore, loadMore } = useReplies({
1470
- ...useRepliesOptions,
1471
- comment: reply,
1472
- });
64
+ ### Run the website locally
1473
65
 
1474
- // updatedReply updates values in real time, reply does not
1475
- 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:
1476
67
 
1477
- // bufferedReplies updates in real time, can show new replies count in real time
1478
- const moreReplies =
1479
- hasMore && bufferedReplies?.length !== 0 ? `(${bufferedReplies.length} more replies)` : "";
1480
-
1481
- // publishing states exist only on account comment
1482
- const accountReply = useAccountComment({ commentIndex: reply.index });
1483
- const state = accountReply?.state;
1484
- const publishingStateString = useStateString(accountReply);
1485
-
1486
- return (
1487
- <div>
1488
- <div>
1489
- {score} {reply.author.address} {reply.timestamp} {moreReplies}
1490
- </div>
1491
- {state === "pending" && <div>PENDING ({publishingStateString})</div>}
1492
- {state === "failed" && <div>FAILED</div>}
1493
- <div>{reply.content}</div>
1494
- <div style={{ marginLeft: 4 }}>
1495
- {replies.map((reply, index) => (
1496
- <Reply
1497
- key={reply?.index || reply?.cid}
1498
- reply={reply}
1499
- updatedReply={updatedReplies[index]}
1500
- />
1501
- ))}
1502
- </div>
1503
- </div>
1504
- );
1505
- };
1506
-
1507
- const comment = useComment({ commentCid });
1508
- const { replies, updatedReplies, hasMore, loadMore } = useReplies({
1509
- ...useRepliesOptions,
1510
- comment,
1511
- });
1512
- const repliesComponents = replies.map((reply, index) => (
1513
- <Reply key={reply?.index || reply?.cid} reply={reply} updatedReply={updatedReplies[index]} />
1514
- ));
68
+ ```bash
69
+ cd website
70
+ corepack yarn install --immutable
71
+ corepack yarn start
1515
72
  ```
1516
73
 
1517
- #### Format short CIDs and addresses
74
+ ## Contribute
1518
75
 
1519
- ```jsx
1520
- import { useShortAddress, useShortCid } from "@bitsocial/bitsocial-react-hooks";
76
+ Use Node 22 and the repository's pinned Yarn 4 release:
1521
77
 
1522
- const shortParentCid = useShortCid(comment.parentCid);
1523
- const shortAddress = useShortAddress(address);
78
+ ```bash
79
+ nvm install
80
+ nvm use
81
+ corepack yarn install
82
+ corepack yarn build
1524
83
  ```
1525
84
 
1526
- #### useBufferedFeeds with concurrency
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`.
1527
86
 
1528
- ```jsx
1529
- const useBufferedFeedsWithConcurrency = ({feedOptions}) => {
1530
-
1531
- const communities = useCommunities()
1532
-
1533
- return useBufferedFeeds({feedsOptions})
1534
- }
1535
-
1536
- const feedOptions = [
1537
- {communities: [{name: 'news.eth'}, {name: 'crypto.eth'}], sortType: 'new'},
1538
- {communities: [{name: 'memes.eth'}], sortType: 'topWeek'},
1539
- {communities: [{publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}, {publicKey: '12D3KooW...'}], sortType: 'hot'},
1540
- ...
1541
- ]
87
+ ## License
1542
88
 
1543
- useBufferedFeedsWithConcurrency({feedOptions})
1544
- ```
89
+ [GPL-3.0-or-later](LICENSE).