dot-react-comment-lib 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,416 @@
1
+ # dot-react-comment-lib
2
+
3
+ > **High-performance, ultra-customizable nested threaded comments library for React and Next.js**, built with Material UI (MUI), `emoji-picker-react`, `react-hook-form`, `@hookform/resolvers`, and `@emotion/styled`.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/dot-react-comment-lib.svg?style=flat-square)](https://www.npmjs.com/package/dot-react-comment-lib)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg?style=flat-square)](https://www.typescriptlang.org/)
8
+ [![React](<https://img.shields.io/badge/React-18%20%2F%2019-61dafb.svg?style=flat-square>)](https://react.dev)
9
+ [![Next.js](<https://img.shields.io/badge/Next.js-App%20Router%20%2F%20Pages-black.svg?style=flat-square>)](https://nextjs.org/)
10
+ [![Bundle Size](<https://img.shields.io/badge/Bundle-~31KB%20Minified-success.svg?style=flat-square>)](https://bundlephobia.com)
11
+
12
+ ---
13
+
14
+ ## ⚡ Key Optimizations
15
+
16
+ - 🚀 **Blazing Fast & Ultra Lightweight**: Only **~31 KB** minified bundle size.
17
+ - 💤 **Lazy-Loaded Emoji Picker**: `emoji-picker-react` (~300 KB) is loaded dynamically **only** when the user opens the emoji popover, ensuring instant initial page loads.
18
+ - 🛡️ **Zero Unnecessary Re-Renders**: Every subcomponent is optimized with `React.memo` and stable callback selectors. Reacting or editing one comment will never re-render the whole thread tree.
19
+ - 🔄 **Universal Database Schema Adapter**: Works directly with **ANY** database entity (`RoomChatEntity`, Prisma, Supabase, MongoDB, REST APIs) — automatically converts flat database rows into nested threads on the fly.
20
+ - 🎭 **Complete Business Rules Freedom**: Easily toggle user avatars on/off, switch between nested vs flat linear comments, limit nesting depth, and customize CSS on every element.
21
+
22
+ ---
23
+
24
+ ## 📊 With vs. Without Customization Overview
25
+
26
+ | Feature | WITHOUT Customization (Default) | WITH Customization |
27
+ | :------------------------------ | :------------------------------------------------------- | :------------------------------------------------------------------- |
28
+ | **Data Schema** | Standard`{ id, parentId, content, createdAt, author }` | Any DB Schema (`uuid`, `message_parent_uuid`, `message`, etc.) |
29
+ | **Comment Threading** | Multi-level nested tree (`enableNesting: true`) | Simple flat linear comments (`enableNesting: false`) |
30
+ | **Nesting Depth** | Unlimited (`maxDepth: Infinity`) | Limited to 1, 2, 3, or N levels |
31
+ | **User Images / Avatars** | Displayed with circle shape & initials fallback | Hidden completely (`showAvatars: false`) or custom shapes |
32
+ | **CSS & Styles** | Modern clean MUI theme | Custom CSS /`styles` / `classes` for every component |
33
+ | **Permissions** | Authors can edit/delete own comments | Custom role functions (Admin, Moderator, Guest read-only) |
34
+ | **Reactions & Emojis** | Quick reactions + full lazy-loaded emoji picker | Toggleable on/off, custom quick emoji list |
35
+ | **Soft Deletions** | `"[This comment has been deleted]"` placeholder | Hard remove (`softDeleteHandling: 'hide'`) |
36
+
37
+ ---
38
+
39
+ ## 📦 Installation
40
+
41
+ ```bash
42
+ npm install dot-react-comment-lib
43
+ ```
44
+
45
+ ### Peer Dependencies
46
+
47
+ ```bash
48
+ npm install @mui/material @mui/icons-material @emotion/react @emotion/styled react-hook-form @hookform/resolvers zod emoji-picker-react
49
+ ```
50
+
51
+ ---
52
+
53
+ ## 🚀 Usage Guide
54
+
55
+ ### 1. Usage WITHOUT Customization (Zero Configuration)
56
+
57
+ If you have standard comment objects, just pass `comments` and `currentUser`. It works instantly out-of-the-box:
58
+
59
+ ```tsx
60
+ 'use client';
61
+
62
+ import { NestedComments } from 'dot-react-comment-lib';
63
+
64
+ const simpleComments = [
65
+ {
66
+ id: '1',
67
+ parentId: null,
68
+ content: 'This is a top-level comment!',
69
+ createdAt: '2025-02-14T08:00:00.000Z',
70
+ author: { id: 'u1', name: 'Aarav Sharma' },
71
+ },
72
+ {
73
+ id: '2',
74
+ parentId: '1',
75
+ content: 'This is an automatic reply to comment #1.',
76
+ createdAt: '2025-02-14T08:30:00.000Z',
77
+ author: { id: 'u2', name: 'Priya Patel' },
78
+ },
79
+ ];
80
+
81
+ export default function BasicComments() {
82
+ return (
83
+ <NestedComments
84
+ comments={simpleComments}
85
+ currentUser={{ id: 'u1', name: 'Aarav Sharma' }}
86
+ onSubmitComment={({ content, parentId }) => {
87
+ console.log('Submitting:', content, 'Reply to:', parentId);
88
+ }}
89
+ />
90
+ );
91
+ }
92
+ ```
93
+
94
+ ---
95
+
96
+ ### 2. Usage WITH Database Schema Mapping
97
+
98
+ #### A. TypeORM `RoomChatEntity` Schema (`schema="room-chat"`)
99
+
100
+ If your backend database matches the `RoomChatEntity` structure (`uuid`, `message_parent_uuid`, `message`, `created_at`, `deleted_at`), pass `schema="room-chat"`:
101
+
102
+ ```tsx
103
+ import { NestedComments } from 'dot-react-comment-lib';
104
+
105
+ export function RoomChatComponent({ dbRows }) {
106
+ return (
107
+ <NestedComments
108
+ comments={dbRows} // Flat rows from RoomChatEntity
109
+ schema="room-chat"
110
+ currentUser={{ id: 'usr-1', name: 'Aarav Sharma', role: 'Admin' }}
111
+ onSubmitComment={async ({ content, parentId }) => {
112
+ // Save to TypeORM / database endpoint
113
+ }}
114
+ />
115
+ );
116
+ }
117
+ ```
118
+
119
+ #### B. Custom Database Schema Adapter (Prisma, MongoDB, REST)
120
+
121
+ Map any database structure in just a few lines:
122
+
123
+ ```tsx
124
+ import { NestedComments, CommentFieldMapping } from 'dot-react-comment-lib';
125
+
126
+ interface PostCommentEntity {
127
+ comment_id: string;
128
+ reply_to_id?: string | null;
129
+ body_text: string;
130
+ timestamp: string;
131
+ user_info: {
132
+ user_id: string;
133
+ display_name: string;
134
+ avatar_link?: string;
135
+ };
136
+ }
137
+
138
+ const customAdapter: CommentFieldMapping<PostCommentEntity> = {
139
+ idKey: 'comment_id',
140
+ parentIdKey: 'reply_to_id',
141
+ contentKey: 'body_text',
142
+ createdAtKey: 'timestamp',
143
+ authorKey: (item) => ({
144
+ id: item.user_info.user_id,
145
+ name: item.user_info.display_name,
146
+ avatarUrl: item.user_info.avatar_link,
147
+ }),
148
+ };
149
+
150
+ export function CustomDatabaseComments({ data }) {
151
+ return (
152
+ <NestedComments
153
+ comments={data}
154
+ schema={customAdapter}
155
+ currentUser={{ id: 'u1', name: 'Alex' }}
156
+ />
157
+ );
158
+ }
159
+ ```
160
+
161
+ ---
162
+
163
+ ### 3. Usage WITH Business Rules
164
+
165
+ #### A. Hide User Images Completely (`showAvatars: false`)
166
+
167
+ When corporate privacy rules dictate that no user photos should be shown:
168
+
169
+ ```tsx
170
+ <NestedComments
171
+ comments={comments}
172
+ config={{
173
+ showAvatars: false, // User photos and avatars are completely hidden
174
+ }}
175
+ />
176
+ ```
177
+
178
+ #### B. Simple One-by-One Linear Comments (`enableNesting: false`)
179
+
180
+ When you want a sequential flat timeline without replies or indentation:
181
+
182
+ ```tsx
183
+ <NestedComments
184
+ comments={comments}
185
+ config={{
186
+ enableNesting: false, // Renders flat sequential comments without nesting
187
+ }}
188
+ />
189
+ ```
190
+
191
+ #### C. Limit Nesting Depth (`maxDepth`)
192
+
193
+ Restrict replies to a specific indentation level (e.g. max 2 levels):
194
+
195
+ ```tsx
196
+ <NestedComments
197
+ comments={comments}
198
+ config={{
199
+ maxDepth: 2, // Only allows 2 levels of reply depth
200
+ }}
201
+ />
202
+ ```
203
+
204
+ #### D. Avatar Shapes & Custom Styling
205
+
206
+ ```tsx
207
+ <NestedComments
208
+ comments={comments}
209
+ config={{
210
+ avatarShape: 'rounded', // 'circle' | 'rounded' | 'square'
211
+ showThreadLines: true, // Draw vertical connector lines
212
+ collapsible: true, // Allow collapsing branches
213
+ enableEmojiPicker: true,// Lazy-loaded emoji picker popover
214
+ }}
215
+ />
216
+ ```
217
+
218
+ ---
219
+
220
+ ### 4. Usage WITH Custom CSS & Granular Styling (`styles` & `classes`)
221
+
222
+ You can customize the styling, colors, borders, and shadows of **every single element** in the UI:
223
+
224
+ ```tsx
225
+ <NestedComments
226
+ comments={comments}
227
+ styles={{
228
+ // Root container
229
+ root: {
230
+ p: 2,
231
+ borderRadius: 4,
232
+ background: 'rgba(255, 255, 255, 0.8)',
233
+ boxShadow: '0 8px 32px rgba(0,0,0,0.06)',
234
+ },
235
+ // Header & counters
236
+ header: { pb: 2, borderBottom: '2px solid #e2e8f0' },
237
+ title: { color: '#1e293b', fontWeight: 800 },
238
+ countBadge: { bgcolor: '#6366f1', color: '#ffffff' },
239
+
240
+ // Main composer & reply box
241
+ composer: { my: 2 },
242
+ composerInput: {
243
+ borderRadius: 3,
244
+ border: '2px solid #6366f1',
245
+ },
246
+ composerSubmitButton: {
247
+ bgcolor: '#6366f1',
248
+ '&:hover': { bgcolor: '#4f46e5' },
249
+ },
250
+
251
+ // Comment row cards
252
+ commentItem: {
253
+ p: 1.5,
254
+ borderRadius: 2.5,
255
+ '&:hover': { bgcolor: 'action.hover' },
256
+ },
257
+ authorName: { color: '#4f46e5', fontWeight: 700 },
258
+ commentBody: { fontSize: '0.95rem', lineHeight: 1.6 },
259
+
260
+ // Emoji reaction chips
261
+ reactionChip: {
262
+ borderRadius: '8px',
263
+ border: '1.5px solid #e2e8f0',
264
+ },
265
+ activeReactionChip: {
266
+ bgcolor: 'rgba(99, 102, 241, 0.15)',
267
+ borderColor: '#6366f1',
268
+ },
269
+
270
+ // Thread lines
271
+ threadLine: { bgcolor: '#6366f1', width: '2px' },
272
+ }}
273
+ classes={{
274
+ root: 'my-custom-wrapper',
275
+ composer: 'my-custom-composer',
276
+ commentItem: 'my-custom-card',
277
+ }}
278
+ />
279
+ ```
280
+
281
+ ---
282
+
283
+ ### 5. Usage WITH Granular Role Permissions
284
+
285
+ ```tsx
286
+ <NestedComments
287
+ comments={comments}
288
+ currentUser={currentUser}
289
+ permissions={{
290
+ // Disable replies for guests
291
+ canReply: (comment, user) => user?.role !== 'Guest',
292
+ // Only Admins or comment authors can edit
293
+ canEdit: (comment, user) => user?.role === 'Admin' || comment.author.id === user?.id,
294
+ // Only Admins or comment authors can delete
295
+ canDelete: (comment, user) => user?.role === 'Admin' || comment.author.id === user?.id,
296
+ // Only Admins and Authors can pin comments
297
+ canPin: (comment, user) => user?.role === 'Admin' || user?.role === 'Author',
298
+ }}
299
+ />
300
+ ```
301
+
302
+ ---
303
+
304
+ ### 6. Headless State Management: `useCommentTree` Hook
305
+
306
+ For optimistic UI updates with custom API calls:
307
+
308
+ ```tsx
309
+ import { useCommentTree, NestedComments } from 'dot-react-comment-lib';
310
+
311
+ export function OptimisticComments({ initialData }) {
312
+ const {
313
+ comments,
314
+ addComment,
315
+ editComment,
316
+ deleteComment,
317
+ reactToComment,
318
+ totalComments,
319
+ } = useCommentTree({
320
+ initialData,
321
+ schema: 'room-chat',
322
+ });
323
+
324
+ return (
325
+ <NestedComments
326
+ comments={comments}
327
+ onSubmitComment={async ({ content, parentId }) => {
328
+ addComment(content, parentId); // Optimistic UI update
329
+ await api.saveComment({ content, parentId });
330
+ }}
331
+ onEditComment={async ({ id, content }) => {
332
+ editComment(id, content);
333
+ await api.updateComment(id, content);
334
+ }}
335
+ onDeleteComment={async ({ id }) => {
336
+ deleteComment(id, true);
337
+ await api.deleteComment(id);
338
+ }}
339
+ onReactComment={async ({ id, emoji }) => {
340
+ reactToComment(id, emoji);
341
+ await api.toggleReaction(id, emoji);
342
+ }}
343
+ />
344
+ );
345
+ }
346
+ ```
347
+
348
+ ---
349
+
350
+ ## 📖 Component Props Reference
351
+
352
+ ### `<NestedComments />`
353
+
354
+ | Prop | Type | Default | Description |
355
+ | :------------------ | :--------------------------------------------------- | :--------------------- | :------------------------------------------------------------------------------ |
356
+ | `comments` | `T[]` | `[]` | Array of raw comment data (flat list or nested tree). |
357
+ | `schema` | `CommentFieldMapping<T> \| 'room-chat' \| 'default'` | `'default'` | Database schema field adapter configuration. |
358
+ | `currentUser` | `CommentAuthor` | `undefined` | The currently logged-in user object. |
359
+ | `config` | `NestedCommentsConfig` | `{}` | Business rules and UI configurations (see table below). |
360
+ | `permissions` | `CommentPermissions<T>` | `{}` | Permission predicates for reply, edit, delete, pin, react, report. |
361
+ | `styles` | `CommentCustomStyles` | `{}` | Granular custom styles/SX props for every UI element. |
362
+ | `classes` | `CommentClassNames` | `{}` | Custom CSS classes for every UI element. |
363
+ | `labels` | `Partial<CommentLabels>` | `{}` | Internationalization & custom text labels. |
364
+ | `renderers` | `CommentCustomRenderers<T>` | `{}` | Custom slot overrides for avatar, header, body, actions, composer, empty state. |
365
+ | `onSubmitComment` | `(data) => Promise<void> \| void` | `undefined` | Handler for submitting new comments / replies. |
366
+ | `onEditComment` | `(data) => Promise<void> \| void` | `undefined` | Handler for editing a comment. |
367
+ | `onDeleteComment` | `(data) => Promise<void> \| void` | `undefined` | Handler for deleting a comment. |
368
+ | `onReactComment` | `(data) => Promise<void> \| void` | `undefined` | Handler for adding/removing an emoji reaction. |
369
+ | `onPinComment` | `(data) => Promise<void> \| void` | `undefined` | Handler for pinning/unpinning comments. |
370
+ | `onReportComment` | `(data) => Promise<void> \| void` | `undefined` | Handler for reporting a comment. |
371
+ | `formatDate` | `(date) => string` | `formatRelativeTime` | Custom timestamp formatter function (e.g.,`"2h ago"`). |
372
+ | `sx` | `SxProps<Theme>` | `undefined` | Root container MUI`sx` styling props. |
373
+
374
+ ---
375
+
376
+ ### `config` Options (`NestedCommentsConfig`)
377
+
378
+ | Option | Type | Default | Description |
379
+ | :--------------------- | :------------------------------------------------------ | :------------------------------------ | :------------------------------------------------------------------- |
380
+ | `enableNesting` | `boolean` | `true` | When`false`, renders as simple one-by-one linear comments. |
381
+ | `maxDepth` | `number` | `Infinity` | Maximum nesting depth level. |
382
+ | `showAvatars` | `boolean` | `true` | Set to`false` to hide user images and photos. |
383
+ | `avatarShape` | `'circle' \| 'rounded' \| 'square'` | `'circle'` | Shape of user avatars. |
384
+ | `showThreadLines` | `boolean` | `true` | Whether to draw vertical connecting thread lines for nested replies. |
385
+ | `collapsible` | `boolean` | `true` | Allow collapsing/expanding nested reply branches. |
386
+ | `defaultExpanded` | `boolean` | `true` | Whether reply branches start expanded by default. |
387
+ | `enableReactions` | `boolean` | `true` | Enable reaction pills and counts. |
388
+ | `quickReactions` | `string[]` | `['👍','❤️','🔥','🎉','🚀','👀']` | List of quick emoji buttons. |
389
+ | `enableEmojiPicker` | `boolean` | `true` | Enable popup emoji picker from`emoji-picker-react`. |
390
+ | `composerPosition` | `'top' \| 'bottom' \| 'both' \| 'none'` | `'top'` | Placement of the main comment input box. |
391
+ | `softDeleteHandling` | `'placeholder' \| 'hide'` | `'placeholder'` | Keep deleted comments as placeholder or remove completely. |
392
+ | `showSortControl` | `boolean` | `true` | Show sorting dropdown. |
393
+ | `sortBy` | `'newest' \| 'oldest' \| 'mostUpvoted' \| 'mostReplies'` | `'newest'` | Initial or controlled sort order. |
394
+ | `minContentLength` | `number` | `1` | Minimum characters for validation. |
395
+ | `maxContentLength` | `number` | `5000` | Maximum characters for validation. |
396
+
397
+ ---
398
+
399
+ ## 🏗️ Publishing to NPM
400
+
401
+ ```bash
402
+ # 1. Build the lightweight minified bundle (creates ESM, CJS, and .d.ts in dist/)
403
+ npm run build:lib
404
+
405
+ # 2. Lotgin to npm
406
+ npm login
407
+
408
+ # 3. Publish to npm registry
409
+ npm publish
410
+ ```
411
+
412
+ ---
413
+
414
+ ## 📄 License
415
+
416
+ MIT © dot