π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat(preview): inline comments, replies, resolve and anonymous commenting
Gilad Resisi6fae13c7bc71
diff --git a/.env.example b/.env.exampleindex cd8c85c7c..4b55c0586 100644--- a/.env.example+++ b/.env.example@@ -166,6 +166,10 @@ POSTIZ_OAUTH_CLIENT_SECRET=""# LINK_DRIP_API_ENDPOINT="https://api.linkdrip.com/v1/" # Your self-hosted LinkDrip API endpoint# LINK_DRIP_SHORT_LINK_DOMAIN="dripl.ink" # Your self-hosted LinkDrip domain+# reCAPTCHA Settings (invisible v2 on anonymous preview comments, optional; unset = no captcha)+# RECAPTCHA_SITE_KEY="" # Your reCAPTCHA v2 invisible site key+# RECAPTCHA_SECRET_KEY="" # Your reCAPTCHA v2 invisible secret key+# Provider visibility / migration# HIDDEN_PROVIDERS="tiktok" # comma-separated identifiers hidden from the add-channel screen# MIGRATE_PROVIDERS="tiktok:tiktok-business" # comma-separated "old:new" pairs, a reconnect of "old" goes through "new" and the channel is migrated in placediff --git a/apps/backend/src/api/routes/posts.controller.ts b/apps/backend/src/api/routes/posts.controller.tsindex 91c1b44e1..230d2cef3 100644--- a/apps/backend/src/api/routes/posts.controller.ts+++ b/apps/backend/src/api/routes/posts.controller.ts@@ -29,6 +29,11 @@ import {Sections,} from '@gitroom/backend/services/auth/permissions/permission.exception.class';import { PostValidationException } from '@gitroom/backend/api/routes/posts.validation.exception';+import {+ CreatePublicCommentDto,+ ResolveCommentDto,+} from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';+import { RealIP } from 'nestjs-real-ip';@ApiTags('Posts')@Controller('/posts')@@ -71,12 +76,21 @@ export class PostsController {@Post('/:id/comments')async createComment(- @GetOrgFromRequest() org: Organization,@GetUserFromRequest() user: User,@Param('id') id: string,- @Body() body: { comment: string }+ @Body() body: CreatePublicCommentDto,+ @RealIP() ip: string) {- return this._postsService.createComment(org.id, user.id, id, body.comment);+ return this._postsService.createPublicComment(id, body, user.id, ip);+ }++ @Put('/comments/:commentId/resolve')+ async resolveComment(+ @GetOrgFromRequest() org: Organization,+ @Param('commentId') commentId: string,+ @Body() body: ResolveCommentDto+ ) {+ return this._postsService.resolveComment(org.id, commentId, body.resolved);}@Get('/tags')@@ -159,7 +173,10 @@ export class PostsController {}@Get('/group/:group')- getPostsByGroup(@GetOrgFromRequest() org: Organization, @Param('group') group: string) {+ getPostsByGroup(+ @GetOrgFromRequest() org: Organization,+ @Param('group') group: string+ ) {return this._postsService.getPostsByGroup(org.id, group);}diff --git a/apps/backend/src/api/routes/public.controller.ts b/apps/backend/src/api/routes/public.controller.tsindex fc2069593..40cf3542c 100644--- a/apps/backend/src/api/routes/public.controller.ts+++ b/apps/backend/src/api/routes/public.controller.ts@@ -27,6 +27,7 @@ import { promisify } from 'util';import { OnlyURL } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';+import { CreatePublicCommentDto } from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';const pump = promisify(pipeline);@@ -76,6 +77,15 @@ export class PublicController {return { comments: await this._postsService.getComments(postId) };}+ @Post(`/posts/:id/comments`)+ async createComment(+ @Param('id') postId: string,+ @Body() body: CreatePublicCommentDto,+ @RealIP() ip: string+ ) {+ return this._postsService.createPublicComment(postId, body, null, ip);+ }+@Post('/t')async trackEvent(@Res() res: Response,@@ -154,7 +164,6 @@ export class PublicController {}}-@Get('/stream')async streamFile(@Query() query: OnlyURL,diff --git a/apps/frontend/src/app/(app)/(preview)/p/[id]/layout.tsx b/apps/frontend/src/app/(app)/(preview)/p/[id]/layout.tsxindex aed33f16a..8c6e48dcd 100644--- a/apps/frontend/src/app/(app)/(preview)/p/[id]/layout.tsx+++ b/apps/frontend/src/app/(app)/(preview)/p/[id]/layout.tsx@@ -3,7 +3,7 @@ import { PreviewWrapper } from '@gitroom/frontend/components/preview/preview.wraexport default async function AppLayout({ children }: { children: ReactNode }) {return (- <div className="bg-[#000000] min-h-screen">+ <div className="bg-newBgColor min-h-screen text-newTextColor"><PreviewWrapper>{children}</PreviewWrapper></div>);diff --git a/apps/frontend/src/app/(app)/(preview)/p/[id]/page.tsx b/apps/frontend/src/app/(app)/(preview)/p/[id]/page.tsxindex f5dc7b463..2b90644a9 100644--- a/apps/frontend/src/app/(app)/(preview)/p/[id]/page.tsx+++ b/apps/frontend/src/app/(app)/(preview)/p/[id]/page.tsx@@ -6,6 +6,8 @@ import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.siimport SafeImage from '@gitroom/react/helpers/safe.image';import Link from 'next/link';import { CommentsComponents } from '@gitroom/frontend/components/preview/comments.components';+import { PreviewCommentsProvider } from '@gitroom/frontend/components/preview/preview.comments.context';+import { PostContentClient } from '@gitroom/frontend/components/preview/post.content.client';import dayjs from 'dayjs';import utc from 'dayjs/plugin/utc';import { VideoOrImage } from '@gitroom/react/helpers/video.or.image';@@ -40,107 +42,102 @@ export default async function Auth(const t = await getT();if (!post.length) {return (- <div className="text-white fixed start-0 top-0 w-full h-full flex justify-center items-center text-[20px]">+ <div className="text-newTextColor fixed start-0 top-0 w-full h-full flex justify-center items-center text-[20px]">{t('post_not_found', 'Post not found')}</div>);}return (- <div>- <div className="mx-auto w-full max-w-[1346px] py-3 text-white">- <div className="flex items-center justify-between">- <div className="flex items-center space-x-4">- <div className="flex items-center space-x-2">- <div className="min-w-[55px]">- <Link- href="/"- className="text-2xl flex items-center justify-center gap-[10px] text-textColor order-1"- >- <div className="max-w-[55px]">- <SafeImage- src={'/postiz.svg'}- width={55}- height={55}- alt="Logo"- />- </div>- <div>- <svg- width="80"- height="75"- viewBox="0 0 366 167"- fill="none"- xmlns="http://www.w3.org/2000/svg"- >- <path- d="M24.9659 30.4263V43.3825C26.9237 41.3095 29.3998 39.582 32.3941 38.2C35.3885 36.7028 39.0162 35.9543 43.2774 35.9543C47.1931 35.9543 50.8784 36.7028 54.3334 38.2C57.9036 39.6972 61.0131 42.1157 63.6619 45.4555C66.4259 48.6802 68.6141 52.9989 70.2264 58.4118C71.8387 63.8246 72.6449 70.3891 72.6449 78.1053C72.6449 83.6333 72.1266 89.1613 71.0902 94.6893C70.1688 100.217 68.4989 105.169 66.0804 109.546C63.6619 113.922 60.3796 117.492 56.2336 120.256C52.2028 122.905 47.1355 124.23 41.0316 124.23C36.6553 124.23 33.2003 123.654 30.6666 122.502C28.1329 121.235 26.2327 119.796 24.9659 118.183V160.162L0.0898438 166.381V30.4263H24.9659ZM32.7396 109.2C35.734 109.2 38.2676 108.221 40.3406 106.264C42.4136 104.191 44.026 101.542 45.1776 98.3171C46.4445 95.0924 47.3082 91.5222 47.7689 87.6066C48.3447 83.5757 48.6326 79.6025 48.6326 75.6868C48.6326 69.3526 48.0568 64.3429 46.9051 60.6575C45.8686 56.9722 44.6018 54.2658 43.1046 52.5383C41.6075 50.6956 40.1103 49.5439 38.6131 49.0833C37.2311 48.6226 36.137 48.3923 35.3309 48.3923C33.2579 48.3923 31.2425 49.1409 29.2846 50.638C27.3268 52.02 25.8872 54.1506 24.9659 57.0298V105.227C25.5417 106.148 26.463 107.07 27.7299 107.991C28.9967 108.797 30.6666 109.2 32.7396 109.2Z"- fill="currentColor"- />- <path- d="M188.176 31.4627C191.055 42.5188 193.588 51.5593 195.777 58.5845C197.965 65.4945 199.807 71.3105 201.305 76.0323C202.917 80.7541 204.126 84.9001 204.932 88.4703C205.854 92.0405 206.314 96.0137 206.314 100.39C208.272 99.1232 210.172 97.7988 212.015 96.4168C213.858 94.9196 215.413 93.5376 216.679 92.2708H223.935C220.825 96.9926 217.543 100.908 214.088 104.018C210.633 107.012 207.293 109.661 204.069 111.964C201.996 116.456 198.829 119.623 194.567 121.466C190.306 123.308 185.872 124.23 181.266 124.23C176.083 124.23 171.649 123.539 167.964 122.157C164.279 120.659 161.227 118.702 158.808 116.283C156.505 113.749 154.777 110.87 153.626 107.646C152.474 104.421 151.898 101.023 151.898 97.4533C151.898 93.5376 152.819 90.4857 154.662 88.2975C156.62 85.9942 158.866 84.8426 161.399 84.8426C168.424 84.8426 171.937 87.6641 171.937 93.3073C171.937 95.15 171.304 96.7047 170.037 97.9716C168.77 99.2384 167.158 99.8718 165.2 99.8718C164.278 99.8718 163.3 99.7566 162.263 99.5263C161.342 99.1808 160.593 98.5474 160.017 97.6261C160.939 101.657 162.436 104.824 164.509 107.127C166.697 109.431 169.461 110.582 172.801 110.582C175.68 110.582 177.811 109.891 179.193 108.509C180.575 107.012 181.266 104.478 181.266 100.908C181.266 97.1078 180.92 93.7104 180.229 90.7161C179.653 87.6066 178.732 84.2091 177.465 80.5238C176.198 76.8385 174.644 72.4621 172.801 67.3948C170.958 62.2123 168.885 55.5326 166.582 47.3558C160.823 59.6786 153.222 67.5675 143.779 71.0225C143.779 71.9439 143.779 72.8652 143.779 73.7865C143.894 74.5927 143.952 75.4565 143.952 76.3778C143.952 83.0575 143.376 89.334 142.224 95.2076C141.072 100.966 139.115 106.033 136.351 110.41C133.702 114.671 130.247 118.068 125.986 120.602C121.724 123.02 116.484 124.23 110.265 124.23C106.004 124.23 101.916 123.596 98 122.329C94.1995 120.947 90.8021 118.759 87.8078 115.765C84.8134 112.655 82.3949 108.624 80.5523 103.672C78.8248 98.605 77.961 92.4436 77.961 85.188C77.961 80.2359 78.4793 74.9382 79.5158 69.295C80.5523 63.5367 82.4525 58.1814 85.2165 53.2293C87.9805 48.2771 91.7234 44.1887 96.4453 40.964C101.282 37.6242 107.444 35.9543 114.93 35.9543C122.646 35.9543 128.807 38.0273 133.414 42.1733C138.136 46.3193 141.303 52.9989 142.915 62.2123C146.946 61.2909 150.574 58.5269 153.798 53.9203C157.138 49.1984 160.305 42.8643 163.3 34.9177L188.176 31.4627ZM115.102 107.991C117.521 107.991 119.594 107.185 121.321 105.573C123.164 103.845 124.661 101.542 125.813 98.6626C126.964 95.6682 127.771 92.1556 128.231 88.1248C128.807 84.094 129.095 79.7176 129.095 74.9958V72.75C124.488 71.7135 122.185 68.3161 122.185 62.5578C122.185 58.8724 123.682 56.4539 126.677 55.3023C125.41 51.6169 123.855 49.1984 122.012 48.0468C120.285 46.8951 118.788 46.3193 117.521 46.3193C114.987 46.3193 112.799 47.5285 110.956 49.947C109.229 52.2504 107.789 55.2447 106.638 58.93C105.486 62.5002 104.622 66.4734 104.046 70.8498C103.586 75.2261 103.355 79.4297 103.355 83.4605C103.355 88.6431 103.701 92.8466 104.392 96.0713C105.198 99.296 106.177 101.772 107.329 103.5C108.48 105.227 109.747 106.436 111.129 107.127C112.511 107.703 113.835 107.991 115.102 107.991Z"- fill="currentColor"- />- <path- d="M239.554 9.52348V36.818H250.092V43.728H239.554V95.5531C239.554 100.39 240.187 103.615 241.454 105.227C242.836 106.724 245.197 107.473 248.537 107.473C251.877 107.473 254.641 106.033 256.829 103.154C259.132 100.275 260.457 96.6471 260.802 92.2708H268.058C267.136 99.296 265.524 104.939 263.221 109.2C260.917 113.346 258.326 116.571 255.447 118.874C252.568 121.062 249.631 122.502 246.637 123.193C243.642 123.884 240.993 124.23 238.69 124.23C229.822 124.23 223.603 121.811 220.033 116.974C216.463 112.022 214.678 105.515 214.678 97.4533V43.728H209.15V36.818H214.678V12.9785L239.554 9.52348Z"- fill="currentColor"- />- <path- d="M258.833 13.8422C258.833 10.0417 260.158 6.81706 262.806 4.16823C265.455 1.40422 268.68 0.0222168 272.48 0.0222168C276.281 0.0222168 279.506 1.40422 282.154 4.16823C284.918 6.81706 286.3 10.0417 286.3 13.8422C286.3 17.6427 284.918 20.8674 282.154 23.5162C279.506 26.1651 276.281 27.4895 272.48 27.4895C268.68 27.4895 265.455 26.1651 262.806 23.5162C260.158 20.8674 258.833 17.6427 258.833 13.8422ZM285.609 36.818V95.5531C285.609 100.39 286.243 103.615 287.51 105.227C288.892 106.724 291.253 107.473 294.592 107.473C296.09 107.473 297.184 107.358 297.875 107.127C298.681 106.897 299.372 106.667 299.948 106.436C300.063 107.012 300.12 107.588 300.12 108.164C300.12 108.74 300.12 109.315 300.12 109.891C300.12 112.77 299.602 115.131 298.566 116.974C297.644 118.817 296.377 120.314 294.765 121.466C293.268 122.502 291.598 123.193 289.755 123.539C288.028 123.999 286.358 124.23 284.746 124.23C275.878 124.23 269.659 121.811 266.089 116.974C262.518 112.022 260.733 105.515 260.733 97.4533V36.818H285.609ZM351.773 107.473C350.391 107.358 349.354 106.897 348.663 106.091C347.972 105.169 347.627 104.133 347.627 102.981C347.627 101.484 348.26 100.045 349.527 98.6626C350.794 97.1654 352.867 96.4168 355.746 96.4168C358.971 96.4168 361.389 97.5109 363.001 99.6991C364.614 101.772 365.42 104.248 365.42 107.127C365.42 108.97 365.074 110.87 364.383 112.828C363.692 114.671 362.598 116.398 361.101 118.011C359.604 119.508 357.761 120.775 355.573 121.811C353.385 122.732 350.851 123.193 347.972 123.193H300.293L334.152 46.1465H321.369C318.835 46.1465 316.704 46.3193 314.977 46.6648C313.365 46.8951 312.558 47.5285 312.558 48.565C312.558 49.0257 312.674 49.256 312.904 49.256C313.249 49.256 313.595 49.3712 313.94 49.6015C314.401 49.8318 314.747 50.2925 314.977 50.9835C315.322 51.6745 315.495 52.8838 315.495 54.6113C315.495 57.1449 314.689 58.9876 313.077 60.1393C311.579 61.2909 309.852 61.8668 307.894 61.8668C305.591 61.8668 303.345 61.1182 301.157 59.621C299.084 58.0087 298.047 55.5902 298.047 52.3655C298.047 50.638 298.393 48.9105 299.084 47.183C299.775 45.3403 300.811 43.6704 302.193 42.1733C303.575 40.5609 305.303 39.2941 307.376 38.3728C309.449 37.3363 311.867 36.818 314.631 36.818H362.138L329.142 109.891C329.833 109.891 330.812 109.949 332.079 110.064C333.346 110.179 334.67 110.294 336.052 110.41C337.55 110.525 338.989 110.64 340.371 110.755C341.868 110.87 343.193 110.928 344.344 110.928C346.417 110.928 348.145 110.697 349.527 110.237C351.024 109.776 351.773 108.855 351.773 107.473Z"- fill="currentColor"- />- </svg>- </div>- </Link>- </div>+ <PreviewCommentsProvider+ previewId={id}+ postIds={post.map((p: any) => p.id)}+ organizationId={post[0].organizationId}+ >+ <div className="mx-auto w-full max-w-[1346px] p-[12px] flex flex-col gap-[8px] text-newTextColor">+ <div className="flex bg-newBgColorInner rounded-[12px] min-h-[80px] px-[20px] py-[12px] items-center gap-[20px] flex-wrap">+ <Link+ href="/"+ className="flex items-center gap-[10px] text-textColor"+ >+ <div className="w-[44px]">+ <SafeImage src={'/postiz.svg'} width={44} height={44} alt="Logo" />+ </div>+ <div>+ <svg+ width="64"+ height="60"+ viewBox="0 0 366 167"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M24.9659 30.4263V43.3825C26.9237 41.3095 29.3998 39.582 32.3941 38.2C35.3885 36.7028 39.0162 35.9543 43.2774 35.9543C47.1931 35.9543 50.8784 36.7028 54.3334 38.2C57.9036 39.6972 61.0131 42.1157 63.6619 45.4555C66.4259 48.6802 68.6141 52.9989 70.2264 58.4118C71.8387 63.8246 72.6449 70.3891 72.6449 78.1053C72.6449 83.6333 72.1266 89.1613 71.0902 94.6893C70.1688 100.217 68.4989 105.169 66.0804 109.546C63.6619 113.922 60.3796 117.492 56.2336 120.256C52.2028 122.905 47.1355 124.23 41.0316 124.23C36.6553 124.23 33.2003 123.654 30.6666 122.502C28.1329 121.235 26.2327 119.796 24.9659 118.183V160.162L0.0898438 166.381V30.4263H24.9659ZM32.7396 109.2C35.734 109.2 38.2676 108.221 40.3406 106.264C42.4136 104.191 44.026 101.542 45.1776 98.3171C46.4445 95.0924 47.3082 91.5222 47.7689 87.6066C48.3447 83.5757 48.6326 79.6025 48.6326 75.6868C48.6326 69.3526 48.0568 64.3429 46.9051 60.6575C45.8686 56.9722 44.6018 54.2658 43.1046 52.5383C41.6075 50.6956 40.1103 49.5439 38.6131 49.0833C37.2311 48.6226 36.137 48.3923 35.3309 48.3923C33.2579 48.3923 31.2425 49.1409 29.2846 50.638C27.3268 52.02 25.8872 54.1506 24.9659 57.0298V105.227C25.5417 106.148 26.463 107.07 27.7299 107.991C28.9967 108.797 30.6666 109.2 32.7396 109.2Z"+ fill="currentColor"+ />+ <path+ d="M188.176 31.4627C191.055 42.5188 193.588 51.5593 195.777 58.5845C197.965 65.4945 199.807 71.3105 201.305 76.0323C202.917 80.7541 204.126 84.9001 204.932 88.4703C205.854 92.0405 206.314 96.0137 206.314 100.39C208.272 99.1232 210.172 97.7988 212.015 96.4168C213.858 94.9196 215.413 93.5376 216.679 92.2708H223.935C220.825 96.9926 217.543 100.908 214.088 104.018C210.633 107.012 207.293 109.661 204.069 111.964C201.996 116.456 198.829 119.623 194.567 121.466C190.306 123.308 185.872 124.23 181.266 124.23C176.083 124.23 171.649 123.539 167.964 122.157C164.279 120.659 161.227 118.702 158.808 116.283C156.505 113.749 154.777 110.87 153.626 107.646C152.474 104.421 151.898 101.023 151.898 97.4533C151.898 93.5376 152.819 90.4857 154.662 88.2975C156.62 85.9942 158.866 84.8426 161.399 84.8426C168.424 84.8426 171.937 87.6641 171.937 93.3073C171.937 95.15 171.304 96.7047 170.037 97.9716C168.77 99.2384 167.158 99.8718 165.2 99.8718C164.278 99.8718 163.3 99.7566 162.263 99.5263C161.342 99.1808 160.593 98.5474 160.017 97.6261C160.939 101.657 162.436 104.824 164.509 107.127C166.697 109.431 169.461 110.582 172.801 110.582C175.68 110.582 177.811 109.891 179.193 108.509C180.575 107.012 181.266 104.478 181.266 100.908C181.266 97.1078 180.92 93.7104 180.229 90.7161C179.653 87.6066 178.732 84.2091 177.465 80.5238C176.198 76.8385 174.644 72.4621 172.801 67.3948C170.958 62.2123 168.885 55.5326 166.582 47.3558C160.823 59.6786 153.222 67.5675 143.779 71.0225C143.779 71.9439 143.779 72.8652 143.779 73.7865C143.894 74.5927 143.952 75.4565 143.952 76.3778C143.952 83.0575 143.376 89.334 142.224 95.2076C141.072 100.966 139.115 106.033 136.351 110.41C133.702 114.671 130.247 118.068 125.986 120.602C121.724 123.02 116.484 124.23 110.265 124.23C106.004 124.23 101.916 123.596 98 122.329C94.1995 120.947 90.8021 118.759 87.8078 115.765C84.8134 112.655 82.3949 108.624 80.5523 103.672C78.8248 98.605 77.961 92.4436 77.961 85.188C77.961 80.2359 78.4793 74.9382 79.5158 69.295C80.5523 63.5367 82.4525 58.1814 85.2165 53.2293C87.9805 48.2771 91.7234 44.1887 96.4453 40.964C101.282 37.6242 107.444 35.9543 114.93 35.9543C122.646 35.9543 128.807 38.0273 133.414 42.1733C138.136 46.3193 141.303 52.9989 142.915 62.2123C146.946 61.2909 150.574 58.5269 153.798 53.9203C157.138 49.1984 160.305 42.8643 163.3 34.9177L188.176 31.4627ZM115.102 107.991C117.521 107.991 119.594 107.185 121.321 105.573C123.164 103.845 124.661 101.542 125.813 98.6626C126.964 95.6682 127.771 92.1556 128.231 88.1248C128.807 84.094 129.095 79.7176 129.095 74.9958V72.75C124.488 71.7135 122.185 68.3161 122.185 62.5578C122.185 58.8724 123.682 56.4539 126.677 55.3023C125.41 51.6169 123.855 49.1984 122.012 48.0468C120.285 46.8951 118.788 46.3193 117.521 46.3193C114.987 46.3193 112.799 47.5285 110.956 49.947C109.229 52.2504 107.789 55.2447 106.638 58.93C105.486 62.5002 104.622 66.4734 104.046 70.8498C103.586 75.2261 103.355 79.4297 103.355 83.4605C103.355 88.6431 103.701 92.8466 104.392 96.0713C105.198 99.296 106.177 101.772 107.329 103.5C108.48 105.227 109.747 106.436 111.129 107.127C112.511 107.703 113.835 107.991 115.102 107.991Z"+ fill="currentColor"+ />+ <path+ d="M239.554 9.52348V36.818H250.092V43.728H239.554V95.5531C239.554 100.39 240.187 103.615 241.454 105.227C242.836 106.724 245.197 107.473 248.537 107.473C251.877 107.473 254.641 106.033 256.829 103.154C259.132 100.275 260.457 96.6471 260.802 92.2708H268.058C267.136 99.296 265.524 104.939 263.221 109.2C260.917 113.346 258.326 116.571 255.447 118.874C252.568 121.062 249.631 122.502 246.637 123.193C243.642 123.884 240.993 124.23 238.69 124.23C229.822 124.23 223.603 121.811 220.033 116.974C216.463 112.022 214.678 105.515 214.678 97.4533V43.728H209.15V36.818H214.678V12.9785L239.554 9.52348Z"+ fill="currentColor"+ />+ <path+ d="M258.833 13.8422C258.833 10.0417 260.158 6.81706 262.806 4.16823C265.455 1.40422 268.68 0.0222168 272.48 0.0222168C276.281 0.0222168 279.506 1.40422 282.154 4.16823C284.918 6.81706 286.3 10.0417 286.3 13.8422C286.3 17.6427 284.918 20.8674 282.154 23.5162C279.506 26.1651 276.281 27.4895 272.48 27.4895C268.68 27.4895 265.455 26.1651 262.806 23.5162C260.158 20.8674 258.833 17.6427 258.833 13.8422ZM285.609 36.818V95.5531C285.609 100.39 286.243 103.615 287.51 105.227C288.892 106.724 291.253 107.473 294.592 107.473C296.09 107.473 297.184 107.358 297.875 107.127C298.681 106.897 299.372 106.667 299.948 106.436C300.063 107.012 300.12 107.588 300.12 108.164C300.12 108.74 300.12 109.315 300.12 109.891C300.12 112.77 299.602 115.131 298.566 116.974C297.644 118.817 296.377 120.314 294.765 121.466C293.268 122.502 291.598 123.193 289.755 123.539C288.028 123.999 286.358 124.23 284.746 124.23C275.878 124.23 269.659 121.811 266.089 116.974C262.518 112.022 260.733 105.515 260.733 97.4533V36.818H285.609ZM351.773 107.473C350.391 107.358 349.354 106.897 348.663 106.091C347.972 105.169 347.627 104.133 347.627 102.981C347.627 101.484 348.26 100.045 349.527 98.6626C350.794 97.1654 352.867 96.4168 355.746 96.4168C358.971 96.4168 361.389 97.5109 363.001 99.6991C364.614 101.772 365.42 104.248 365.42 107.127C365.42 108.97 365.074 110.87 364.383 112.828C363.692 114.671 362.598 116.398 361.101 118.011C359.604 119.508 357.761 120.775 355.573 121.811C353.385 122.732 350.851 123.193 347.972 123.193H300.293L334.152 46.1465H321.369C318.835 46.1465 316.704 46.3193 314.977 46.6648C313.365 46.8951 312.558 47.5285 312.558 48.565C312.558 49.0257 312.674 49.256 312.904 49.256C313.249 49.256 313.595 49.3712 313.94 49.6015C314.401 49.8318 314.747 50.2925 314.977 50.9835C315.322 51.6745 315.495 52.8838 315.495 54.6113C315.495 57.1449 314.689 58.9876 313.077 60.1393C311.579 61.2909 309.852 61.8668 307.894 61.8668C305.591 61.8668 303.345 61.1182 301.157 59.621C299.084 58.0087 298.047 55.5902 298.047 52.3655C298.047 50.638 298.393 48.9105 299.084 47.183C299.775 45.3403 300.811 43.6704 302.193 42.1733C303.575 40.5609 305.303 39.2941 307.376 38.3728C309.449 37.3363 311.867 36.818 314.631 36.818H362.138L329.142 109.891C329.833 109.891 330.812 109.949 332.079 110.064C333.346 110.179 334.67 110.294 336.052 110.41C337.55 110.525 338.989 110.64 340.371 110.755C341.868 110.87 343.193 110.928 344.344 110.928C346.417 110.928 348.145 110.697 349.527 110.237C351.024 109.776 351.773 108.855 351.773 107.473Z"+ fill="currentColor"+ />+ </svg>+ </div>+ </Link>+ <div className="flex-1" />+ <div className="flex items-center gap-[20px] text-[14px] text-textItemBlur">+ <div>+ {t('publication_date', 'Publication Date:')}{' '}+ <span className="text-newTextColor">+ <RenderPreviewDateClient date={post[0].publishDate} />+ </span></div>- </div>- <div className="text-sm text-gray-400 flex items-center gap-[20px]">{!!searchParams?.share && (- <div>+ <>+ <div className="w-[1px] h-[20px] bg-blockSeparator" /><CopyClient />- </div>+ </>)}- <div className="flex-1">- {t('publication_date', 'Publication Date:')}{' '}- <RenderPreviewDateClient date={post[0].publishDate} />- </div></div></div>- </div>- <div className="flex flex-col lg:flex-row text-white w-full max-w-[1346px] mx-auto">- <div className="flex-1">- <div className="gap-[20px] flex flex-col">+ <div className="flex flex-col lg:flex-row gap-[8px]">+ <div className="flex-1 flex flex-col gap-[8px]">{post.map((p: any, index: number) => (<divkey={String(p.id)}- className="relative px-4 py-4 bg-third border border-tableBorder"+ className="bg-newBgColorInner border border-newTableBorder rounded-[12px] p-[20px]">- <div className="flex space-x-3">+ <div className="flex gap-[12px]"><div>- <div className="flex shrink-0 rounded-full h-30 w-30 relative">+ <div className="flex shrink-0 rounded-full relative"><div className="w-[50px] h-[50px] z-[20]"><img- className="w-full h-full relative z-[20] bg-black aspect-square rounded-full border-tableBorder"+ className="w-full h-full relative z-[20] bg-newBgColor aspect-square rounded-full"alt={post[0].integration.name}src={post[0].integration.picture}/></div>- <div className="absolute -end-[5px] -bottom-[5px] w-[30px] h-[30px] z-[20]">+ <div className="absolute -end-[5px] -bottom-[5px] w-[24px] h-[24px] z-[20]"><img- className="w-full h-full bg-black aspect-square rounded-full border-tableBorder"+ className="w-full h-full bg-newBgColor aspect-square rounded-full"alt={post[0].integration.providerIdentifier}src={`/icons/platforms/${post[0].integration.providerIdentifier}.png`}/></div></div></div>- <div className="flex-1 space-y-1">- <div className="flex items-center space-x-2">- <h2 className="text-sm font-semibold">+ <div className="flex-1 flex flex-col gap-[8px] min-w-0">+ <div className="flex items-center gap-[8px]">+ <h2 className="text-[14px] font-[600]">{post[0].integration.name}</h2>- <span className="text-sm text-gray-500">+ <span className="text-[14px] text-textItemBlur">@{post[0].integration.profile}</span>{index === 0 && (@@ -150,40 +147,40 @@ export default async function Auth(/>)}</div>- <div className="flex flex-col gap-[20px]">- <div- className="text-sm whitespace-pre-wrap"- dangerouslySetInnerHTML={{- __html: sanitizePostContent(p.content),- }}+ <div className="flex flex-col gap-[16px]">+ <PostContentClient+ postId={p.id}+ html={sanitizePostContent(p.content)}/>- <div className="flex w-full gap-[10px]">- {JSON.parse(p?.image || '[]').map((p: any) => (- <div- key={p.name}- className="flex-1 rounded-[10px] max-h-[500px] overflow-hidden"- >- <VideoOrImage- isContain={true}- src={p.path}- autoplay={true}- />- </div>- ))}- </div>+ {!!JSON.parse(p?.image || '[]').length && (+ <div className="flex w-full gap-[10px]">+ {JSON.parse(p?.image || '[]').map((p: any) => (+ <div+ key={p.name}+ className="flex-1 rounded-[10px] max-h-[500px] overflow-hidden"+ >+ <VideoOrImage+ isContain={true}+ src={p.path}+ autoplay={true}+ />+ </div>+ ))}+ </div>+ )}</div></div></div></div>))}</div>- </div>- <div className="w-full lg:w-96 lg:flex-shrink-0">- <div className="p-4 pt-0">- <CommentsComponents postId={id} />+ <div className="w-full lg:w-[380px] lg:flex-shrink-0">+ <div className="bg-newBgColorInner border border-newTableBorder rounded-[12px] p-[20px] lg:sticky lg:top-[12px]">+ <CommentsComponents previewId={id} />+ </div></div></div></div>- </div>+ </PreviewCommentsProvider>);}diff --git a/apps/frontend/src/app/(app)/layout.tsx b/apps/frontend/src/app/(app)/layout.tsxindex ae83325be..27eea4bf3 100644--- a/apps/frontend/src/app/(app)/layout.tsx+++ b/apps/frontend/src/app/(app)/layout.tsx@@ -87,6 +87,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {googleAdsId={process.env.NEXT_PUBLIC_GTM_ID}googleAdsTrialTracking={process.env.NEXT_PUBLIC_TRACKING_TRIAL}language={language}+ recaptchaSiteKey={process.env.RECAPTCHA_SITE_KEY || ''}transloadit={process.env.TRANSLOADIT_AUTH && process.env.TRANSLOADIT_TEMPLATE? [diff --git a/apps/frontend/src/components/preview/comments.components.tsx b/apps/frontend/src/components/preview/comments.components.tsxindex e4b658b6f..630ad20b2 100644--- a/apps/frontend/src/components/preview/comments.components.tsx+++ b/apps/frontend/src/components/preview/comments.components.tsx@@ -2,127 +2,524 @@import { useUser } from '@gitroom/frontend/components/layout/user.context';import { Button } from '@gitroom/react/form/button';-import { FC, useCallback, useMemo, useState } from 'react';+import { Input } from '@gitroom/react/form/input';+import { Textarea } from '@gitroom/react/form/textarea';+import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useFetch } from '@gitroom/helpers/utils/custom.fetch';-import useSWR from 'swr';-import { FieldValues, SubmitHandler, useForm } from 'react-hook-form';+import { FormProvider, useForm } from 'react-hook-form';import { useT } from '@gitroom/react/translation/get.transation.service.client';-export const RenderComponents: FC<{- postId: string;-}> = (props) => {- const { postId } = props;- const fetch = useFetch();- const comments = useCallback(async () => {- return (await fetch(`/public/posts/${postId}/comments`)).json();- }, [postId]);- const { data, mutate, isLoading } = useSWR('comments', comments);- const mapUsers = useMemo(() => {- return (data?.comments || []).reduce(- (all: any, current: any) => {- all.users[current.userId] = all.users[current.userId] || all.counter++;- return all;- },- {- users: {},- counter: 1,+import { useModals } from '@gitroom/frontend/components/layout/new-modal';+import { useVariables } from '@gitroom/react/helpers/variable.context';+import { useToaster } from '@gitroom/react/toaster/toaster';+import clsx from 'clsx';+import dayjs from 'dayjs';+import {+ PreviewComment,+ usePreviewComments,+} from '@gitroom/frontend/components/preview/preview.comments.context';++const REVIEWER_NAME_KEY = 'preview-reviewer-name';++// Invisible reCAPTCHA v2: one widget for the page. Google only shows a puzzle+// when it considers the visitor risky; otherwise the token comes back at once.+// Google does not report a dismissed puzzle, so an attempt stays pending until+// it gets a token, expires, errors, or the reviewer clicks Post again (which+// abandons the previous attempt with null).+let recaptchaWidget: {+ id: number;+ resolve?: (token: string | null) => void;+} | null = null;++const loadRecaptchaToken = async (siteKey: string) => {+ if (!(window as any).grecaptcha?.render) {+ await new Promise<void>((resolve, reject) => {+ (window as any).onPreviewRecaptchaLoad = () => resolve();+ const script = document.createElement('script');+ script.src =+ 'https://www.google.com/recaptcha/api.js?onload=onPreviewRecaptchaLoad&render=explicit';+ script.async = true;+ script.onerror = () => reject(new Error('recaptcha failed to load'));+ document.head.appendChild(script);+ });+ }+ const grecaptcha = (window as any).grecaptcha;+ if (!recaptchaWidget) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const widget: NonNullable<typeof recaptchaWidget> = { id: 0 };+ const settle = (token: string | null) => {+ const resolve = widget.resolve;+ widget.resolve = undefined;+ resolve?.(token);+ };+ widget.id = grecaptcha.render(container, {+ sitekey: siteKey,+ size: 'invisible',+ callback: (token: string) => settle(token),+ 'expired-callback': () => settle(null),+ 'error-callback': () => settle(null),+ });+ recaptchaWidget = widget;+ }+ const widget = recaptchaWidget;+ widget.resolve?.(null);+ grecaptcha.reset(widget.id);+ return new Promise<string | null>((resolve) => {+ widget.resolve = resolve;+ grecaptcha.execute(widget.id);+ });+};++const ReviewerNameForm: FC<{ onConfirm: (name: string) => void }> = ({+ onConfirm,+}) => {+ const t = useT();+ const form = useForm({+ values: {+ name:+ (typeof window !== 'undefined' &&+ localStorage.getItem(REVIEWER_NAME_KEY)) ||+ '',+ },+ mode: 'onChange',+ });+ const submit = useCallback(+ (values: { name: string }) => {+ const name = values.name.trim();+ if (!name) {+ return;}- ).users;- }, [data]);- const { handleSubmit, register, setValue } = useForm();- const submit: SubmitHandler<FieldValues> = useCallback(- async (e) => {- setValue('comment', '');- await fetch(`/posts/${postId}/comments`, {- method: 'POST',- body: JSON.stringify(e),- });- mutate();+ localStorage.setItem(REVIEWER_NAME_KEY, name);+ onConfirm(name);},- [postId, mutate]+ [onConfirm]);+ return (+ <FormProvider {...form}>+ <form onSubmit={form.handleSubmit(submit)}>+ <div className="relative flex gap-[10px] flex-col flex-1">+ <div className="text-[14px] text-textItemBlur">+ {t(+ 'preview_comment_name_required',+ 'We can only post your comment if you provide your name.'+ )}+ </div>+ <Input+ label={t('preview_comment_your_name', 'Your name')}+ placeholder={t('preview_comment_your_name', 'Your name')}+ name="name"+ maxLength={80}+ autoFocus={true}+ />+ <Button type="submit">{t('continue', 'Continue')}</Button>+ </div>+ </form>+ </FormProvider>+ );+};++const CommentComposer: FC<{+ parentId?: string;+ onDone?: () => void;+}> = ({ parentId, onDone }) => {const t = useT();+ const user = useUser();+ const fetch = useFetch();+ const toast = useToaster();+ const modals = useModals();+ const { recaptchaSiteKey } = useVariables();+ const { previewId, pending, setPending, mutate } = usePreviewComments();+ const [loading, setLoading] = useState(false);+ const form = useForm({ values: { content: '' } });+ const anchor = parentId ? null : pending;++ const askForName = useCallback(+ () =>+ new Promise<string | null>((resolve) => {+ modals.openModal({+ classNames: {+ modal: 'bg-transparent text-textColor',+ },+ title: t('preview_comment_your_name', 'Your name'),+ withCloseButton: true,+ onClose: () => resolve(null),+ children: (close) => (+ <ReviewerNameForm+ onConfirm={(name) => {+ resolve(name);+ close();+ }}+ />+ ),+ });+ }),+ [t]+ );++ const submit = useCallback(+ async (values: { content: string }) => {+ const content = values.content.trim();+ if (!content) {+ return;+ }++ let displayName: string | undefined;+ let recaptchaToken: string | undefined;+ if (!user?.id) {+ const name = await askForName();+ if (!name) {+ return;+ }+ displayName = name;++ if (recaptchaSiteKey) {+ const token = await loadRecaptchaToken(recaptchaSiteKey).catch(() => {+ toast.show(+ t('preview_comment_failed', 'Could not post the comment'),+ 'warning'+ );+ return null;+ });+ if (!token) {+ return;+ }+ recaptchaToken = token;+ }+ }++ setLoading(true);+ try {+ const response = await fetch(+ user?.id+ ? `/posts/${previewId}/comments`+ : `/public/posts/${previewId}/comments`,+ {+ method: 'POST',+ body: JSON.stringify({+ content,+ ...(parentId ? { parentId } : {}),+ ...(anchor+ ? {+ postId: anchor.postId,+ anchorStart: anchor.start,+ anchorEnd: anchor.end,+ anchorQuote: anchor.quote,+ }+ : {}),+ ...(displayName ? { displayName } : {}),+ ...(recaptchaToken ? { recaptchaToken } : {}),+ }),+ }+ );++ if (!response.ok) {+ const body = await response.json().catch(() => ({}));+ toast.show(+ body?.message ||+ t('preview_comment_failed', 'Could not post the comment'),+ 'warning'+ );+ return;+ }++ form.reset({ content: '' });+ if (anchor) {+ setPending(null);+ }+ await mutate();+ onDone?.();+ } finally {+ setLoading(false);+ }+ },+ [user?.id, recaptchaSiteKey, previewId, parentId, anchor, askForName]+ );- if (isLoading) {- return <></>;- }return (- <>- <div className="mb-6 flex space-x-3">- <form className="flex-1 space-y-2" onSubmit={handleSubmit(submit)}>- <textarea- {...register('comment', {- required: true,- })}- className="flex w-full px-3 py-2 h-[98px] text-sm ring-offset-background placeholder:text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 min-h-[80px] resize-none text-white bg-third border border-tableBorder placeholder-gray-500 focus:ring-0"- placeholder="Add a comment..."- defaultValue={''}- />- <div className="flex justify-end">- <Button type="submit">- <svg- xmlns="http://www.w3.org/2000/svg"- width={24}- height={24}- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth={2}- strokeLinecap="round"- strokeLinejoin="round"- className="lucide lucide-send me-2 h-4 w-4"- >- <path d="m22 2-7 20-4-9-9-4Z" />- <path d="M22 2 11 13" />- </svg>- {t('post', 'Post')}- </Button>+ <FormProvider {...form}>+ <form+ className="flex flex-col gap-[8px]"+ onSubmit={form.handleSubmit(submit)}+ >+ {!!anchor && (+ <div className="flex items-start gap-[8px] border-s-[3px] border-btnPrimary ps-[8px] text-[12px] text-textItemBlur">+ <div className="flex-1 italic truncate">{anchor.quote}</div>+ <button+ type="button"+ className="hover:text-newTextColor"+ onClick={() => setPending(null)}+ aria-label={t('cancel', 'Cancel')}+ >+ β+ </button></div>- </form>- </div>- <div className="space-y-4">- {!!data.comments.length && (- <h3 className="text-lg font-semibold">{t('comments', 'Comments')}</h3>)}- {data.comments.map((comment: any) => (- <div- key={comment.id}- className="flex space-x-3 border-t border-tableBorder py-3"+ <Textarea+ label={+ parentId ? t('reply', 'Reply') : t('add_a_comment', 'Add a comment')+ }+ name="content"+ className="!min-h-[90px] resize-none"+ placeholder={+ parentId+ ? t('write_a_reply', 'Write a reply...')+ : t('add_a_comment_placeholder', 'Add a comment...')+ }+ maxLength={2000}+ />+ <div className="flex items-center justify-end gap-[10px] -mt-[14px]">+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width={16}+ height={16}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ className="text-textItemBlur cursor-help"+ data-tooltip-id="tooltip"+ data-tooltip-content={t(+ 'preview_comment_detach_hint',+ 'Comments on selected text lose their highlight if the text is edited later.'+ )}>- <div className="flex-1 space-y-1">- <div className="flex items-center space-x-2">- <h3 className="text-sm font-semibold">- {t('user', 'User')}- {mapUsers[comment.userId]}- </h3>- </div>- <p className="text-sm text-gray-300">{comment.content}</p>- </div>- </div>- ))}+ <circle cx="12" cy="12" r="10" />+ <path d="M12 16v-4" />+ <path d="M12 8h.01" />+ </svg>+ {!!onDone && (+ <Button type="button" secondary={true} onClick={onDone}>+ {t('cancel', 'Cancel')}+ </Button>+ )}+ <Button type="submit" loading={loading}>+ {parentId ? t('reply', 'Reply') : t('post', 'Post')}+ </Button>+ </div>+ </form>+ </FormProvider>+ );+};++const CommentBody: FC<{ comment: PreviewComment }> = ({ comment }) => {+ const t = useT();+ return (+ <div className="flex flex-col gap-[4px]">+ <div className="text-[14px] whitespace-pre-wrap break-words">+ {comment.content}+ </div>+ <div className="text-[12px] text-textItemBlur">+ {comment.name || t('reviewer', 'Reviewer')} Β·{' '}+ {dayjs(comment.createdAt).format('MMM D, YYYY HH:mm')}</div>- </>+ </div>);};-export const CommentsComponents: FC<{- postId: string;-}> = (props) => {- const user = useUser();++const ThreadCard: FC<{+ comment: PreviewComment;+ replies: PreviewComment[];+ canResolve: boolean;+}> = ({ comment, replies, canResolve }) => {const t = useT();+ const fetch = useFetch();+ const toast = useToaster();+ const ref = useRef<HTMLDivElement>(null);+ const [replying, setReplying] = useState(false);+ const [expanded, setExpanded] = useState(false);+ const [flash, setFlash] = useState(false);+ const {+ mutate,+ activeThread,+ setActiveThread,+ hoveredThread,+ setHoveredThread,+ } = usePreviewComments();+ const resolved = !!comment.resolvedAt;+ const anchored = comment.anchorStart !== null && comment.anchorEnd !== null;++ useEffect(() => {+ if (activeThread?.id !== comment.id || activeThread.source !== 'mark') {+ return;+ }+ ref.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ setFlash(true);+ const timer = setTimeout(() => setFlash(false), 1500);+ return () => clearTimeout(timer);+ }, [activeThread, comment.id]);++ const toggleResolved = useCallback(async () => {+ const response = await fetch(`/posts/comments/${comment.id}/resolve`, {+ method: 'PUT',+ body: JSON.stringify({ resolved: !resolved }),+ });+ if (!response.ok) {+ toast.show(+ t('preview_comment_failed', 'Could not post the comment'),+ 'warning'+ );+ return;+ }+ mutate();+ }, [comment.id, resolved]);- const { postId } = props;- const goToComments = useCallback(() => {- window.location.href = `/auth?returnUrl=${window.location.href}`;- }, []);- if (!user?.id) {- return (- <Button onClick={goToComments}>- {t(- 'login_register_to_add_comments',- 'Login / Register to add comments'+ return (+ <div+ ref={ref}+ onMouseEnter={() => !resolved && setHoveredThread(comment.id)}+ onMouseLeave={() => setHoveredThread(null)}+ className={clsx(+ 'flex flex-col gap-[8px] rounded-[8px] border p-[12px] transition-colors',+ resolved && 'opacity-50',+ flash || hoveredThread === comment.id || activeThread?.id === comment.id+ ? 'border-btnPrimary'+ : 'border-newTableBorder'+ )}+ >+ <div className="flex items-center gap-[6px] flex-wrap">+ {resolved && (+ <div className="text-[11px] rounded-[4px] px-[6px] py-[2px] bg-btnSimple">+ {t('resolved', 'Resolved')}+ </div>)}- </Button>- );- }- return <RenderComponents postId={postId} />;+ {!!comment.anchorQuote && !anchored && !resolved && (+ <div className="text-[11px] rounded-[4px] px-[6px] py-[2px] bg-btnSimple">+ {t('preview_comment_text_changed', 'Text changed')}+ </div>+ )}+ </div>+ {!!comment.anchorQuote && (+ <div+ className={clsx(+ 'border-s-[3px] border-btnPrimary ps-[8px] text-[12px] italic text-textItemBlur truncate',+ anchored && !resolved && 'cursor-pointer hover:text-newTextColor'+ )}+ onClick={() =>+ anchored &&+ !resolved &&+ setActiveThread({ id: comment.id, source: 'card' })+ }+ >+ {comment.anchorQuote}+ </div>+ )}+ {resolved && !expanded ? (+ <div+ className="text-[14px] truncate cursor-pointer"+ onClick={() => setExpanded(true)}+ >+ {comment.content}+ </div>+ ) : (+ <CommentBody comment={comment} />+ )}+ {(!resolved || expanded) && !!replies.length && (+ <div className="flex flex-col gap-[8px] ps-[12px] border-s border-newTableBorder">+ {replies.map((reply) => (+ <CommentBody key={reply.id} comment={reply} />+ ))}+ </div>+ )}+ {(!resolved || expanded) && (+ <div className="flex gap-[12px] text-[12px]">+ {!resolved && (+ <button+ type="button"+ className="text-textItemBlur hover:text-newTextColor"+ onClick={() => setReplying(!replying)}+ >+ {t('reply', 'Reply')}+ </button>+ )}+ {canResolve && (+ <button+ type="button"+ className="text-textItemBlur hover:text-newTextColor"+ onClick={toggleResolved}+ >+ {resolved ? t('reopen', 'Reopen') : t('resolve', 'Resolve')}+ </button>+ )}+ {resolved && (+ <button+ type="button"+ className="text-textItemBlur hover:text-newTextColor"+ onClick={() => setExpanded(false)}+ >+ {t('collapse', 'Collapse')}+ </button>+ )}+ </div>+ )}+ {replying && !resolved && (+ <CommentComposer+ parentId={comment.id}+ onDone={() => setReplying(false)}+ />+ )}+ </div>+ );+};++export const CommentsComponents: FC<{ previewId: string }> = () => {+ const t = useT();+ const user = useUser();+ const { comments, isLoading, postIds, organizationId } = usePreviewComments();+ const canResolve = !!user?.id && user?.orgId === organizationId;++ const threads = useMemo(() => {+ const replies = comments.reduce((all, current) => {+ if (current.parentId) {+ all[current.parentId] = [...(all[current.parentId] || []), current];+ }+ return all;+ }, {} as Record<string, PreviewComment[]>);++ const rank = (c: PreviewComment) => {+ if (c.resolvedAt) {+ return [2, 0, dayjs(c.createdAt).valueOf()];+ }+ if (c.anchorStart !== null && c.anchorEnd !== null) {+ return [0, postIds.indexOf(c.postId), c.anchorStart];+ }+ return [1, 0, dayjs(c.createdAt).valueOf()];+ };++ return comments+ .filter((c) => !c.parentId)+ .sort((a, b) => {+ const ra = rank(a);+ const rb = rank(b);+ return ra[0] - rb[0] || ra[1] - rb[1] || ra[2] - rb[2];+ })+ .map((comment) => ({ comment, replies: replies[comment.id] || [] }));+ }, [comments, postIds]);++ return (+ <div className="flex flex-col gap-[16px]">+ <div className="text-[18px] font-[600]">{t('comments', 'Comments')}</div>+ <CommentComposer />+ {!isLoading && !threads.length && (+ <div className="text-[13px] text-textItemBlur">+ {t(+ 'preview_no_comments_yet',+ 'No comments yet. Select some text in the post to comment on it, or add a general comment.'+ )}+ </div>+ )}+ <div className="flex flex-col gap-[10px]">+ {threads.map(({ comment, replies }) => (+ <ThreadCard+ key={comment.id}+ comment={comment}+ replies={replies}+ canResolve={canResolve}+ />+ ))}+ </div>+ </div>+ );};diff --git a/apps/frontend/src/components/preview/post.content.client.tsx b/apps/frontend/src/components/preview/post.content.client.tsxnew file mode 100644index 000000000..680ab431a--- /dev/null+++ b/apps/frontend/src/components/preview/post.content.client.tsx@@ -0,0 +1,324 @@+'use client';++import {+ FC,+ MouseEvent,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import clsx from 'clsx';+import { useT } from '@gitroom/react/translation/get.transation.service.client';+import {+ PendingAnchor,+ usePreviewComments,+} from '@gitroom/frontend/components/preview/preview.comments.context';++interface HighlightRange {+ id: string;+ start: number;+ end: number;+}++// The btnPrimary token has no alpha channel, so the tints are mixed in CSS.+const MARK_CLASS = [+ 'bg-[color-mix(in_srgb,var(--new-btn-primary)_25%,transparent)]',+ 'bg-[color-mix(in_srgb,var(--new-btn-primary)_45%,transparent)]',+ 'bg-[color-mix(in_srgb,var(--new-btn-primary)_65%,transparent)]',+];++const markClassName = (count: number, pending: boolean) =>+ clsx(+ 'text-inherit rounded-[2px]',+ pending+ ? 'bg-[color-mix(in_srgb,var(--new-btn-primary)_40%,transparent)] underline decoration-btnPrimary decoration-2'+ : [MARK_CLASS[Math.min(count, MARK_CLASS.length) - 1], 'cursor-pointer']+ );++// Offsets are into the plain text of the rendered item, so a range from the+// start of the container to (node, offset) measures exactly that.+const textOffset = (root: HTMLElement, node: Node, offset: number) => {+ const range = document.createRange();+ range.setStart(root, 0);+ range.setEnd(node, offset);+ return range.toString().length;+};++const clearHighlights = (root: HTMLElement) => {+ root.querySelectorAll('mark[data-preview-mark]').forEach((mark) => {+ const parent = mark.parentNode!;+ while (mark.firstChild) {+ parent.insertBefore(mark.firstChild, mark);+ }+ parent.removeChild(mark);+ });+ root.normalize();+};++// Split the text nodes at every range boundary, then wrap each piece once+// with a mark that lists every thread covering it.+const applyHighlights = (+ root: HTMLElement,+ ranges: HighlightRange[],+ pending: PendingAnchor | null+) => {+ clearHighlights(root);++ const all = [+ ...ranges,+ ...(pending ? [{ id: '', start: pending.start, end: pending.end }] : []),+ ];+ if (!all.length) {+ return;+ }++ const boundaries = Array.from(+ new Set(all.flatMap((r) => [r.start, r.end]))+ ).sort((a, b) => a - b);++ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const textNodes: Text[] = [];+ let next: Node | null;+ while ((next = walker.nextNode())) {+ textNodes.push(next as Text);+ }++ const segments: { node: Text; start: number; end: number }[] = [];+ let offset = 0;+ for (const node of textNodes) {+ const length = node.length;+ let current = node;+ let currentStart = offset;+ for (const boundary of boundaries) {+ if (boundary <= currentStart || boundary >= offset + length) {+ continue;+ }+ const rest = current.splitText(boundary - currentStart);+ segments.push({ node: current, start: currentStart, end: boundary });+ current = rest;+ currentStart = boundary;+ }+ segments.push({ node: current, start: currentStart, end: offset + length });+ offset += length;+ }++ for (const segment of segments) {+ if (segment.end <= segment.start) {+ continue;+ }+ const covering = all.filter(+ (r) => r.start <= segment.start && r.end >= segment.end+ );+ if (!covering.length) {+ continue;+ }+ const ids = covering.map((c) => c.id).filter(Boolean);+ const isPending = covering.some((c) => !c.id);+ const mark = document.createElement('mark');+ mark.setAttribute('data-preview-mark', '');+ if (ids.length) {+ mark.setAttribute('data-thread-ids', ids.join(','));+ }+ mark.className = markClassName(ids.length, isPending && !ids.length);+ segment.node.parentNode!.insertBefore(mark, segment.node);+ mark.appendChild(segment.node);+ }+};++const marksOf = (root: HTMLElement, id: string) =>+ Array.from(+ root.querySelectorAll<HTMLElement>('mark[data-thread-ids]')+ ).filter((mark) => mark.dataset.threadIds!.split(',').includes(id));++export const PostContentClient: FC<{ postId: string; html: string }> = ({+ postId,+ html,+}) => {+ const t = useT();+ const {+ comments,+ pending,+ setPending,+ activeThread,+ setActiveThread,+ hoveredThread,+ setHoveredThread,+ } = usePreviewComments();+ const ref = useRef<HTMLDivElement>(null);+ const [selection, setSelection] = useState<+ (PendingAnchor & { top: number; left: number }) | null+ >(null);++ const ranges = useMemo<HighlightRange[]>(+ () =>+ comments+ .filter(+ (c) =>+ c.postId === postId &&+ !c.parentId &&+ !c.resolvedAt &&+ c.anchorStart !== null &&+ c.anchorEnd !== null+ )+ .map((c) => ({ id: c.id, start: c.anchorStart!, end: c.anchorEnd! })),+ [comments, postId]+ );++ const ownPending = pending?.postId === postId ? pending : null;++ useEffect(() => {+ if (ref.current) {+ applyHighlights(ref.current, ranges, ownPending);+ }+ }, [ranges, ownPending, html]);++ useEffect(() => {+ ref.current+ ?.querySelectorAll<HTMLElement>('mark[data-thread-ids]')+ .forEach((mark) => {+ const ids = mark.dataset.threadIds!.split(',');+ mark.classList.toggle(+ 'ring-1',+ ids.includes(hoveredThread!) || ids.includes(activeThread?.id!)+ );+ mark.classList.toggle(+ 'ring-btnPrimary',+ ids.includes(hoveredThread!) || ids.includes(activeThread?.id!)+ );+ });+ }, [hoveredThread, activeThread, ranges, ownPending]);++ useEffect(() => {+ if (!ref.current || activeThread?.source !== 'card') {+ return;+ }+ const [mark] = marksOf(ref.current, activeThread.id);+ if (!mark) {+ return;+ }+ mark.scrollIntoView({ behavior: 'smooth', block: 'center' });+ mark.classList.add('animate-pulse');+ const timer = setTimeout(+ () => mark.classList.remove('animate-pulse'),+ 1500+ );+ return () => clearTimeout(timer);+ }, [activeThread]);++ useEffect(() => {+ const onSelectionChange = () => {+ const current = window.getSelection();+ if (!current || current.isCollapsed) {+ setSelection(null);+ }+ };+ document.addEventListener('selectionchange', onSelectionChange);+ return () =>+ document.removeEventListener('selectionchange', onSelectionChange);+ }, []);++ const onMouseUp = useCallback(() => {+ const root = ref.current;+ const current = window.getSelection();+ if (!root || !current || current.isCollapsed || !current.rangeCount) {+ setSelection(null);+ return;+ }+ const selected = current.getRangeAt(0);+ if (!selected.intersectsNode(root)) {+ setSelection(null);+ return;+ }+ // A triple-click ends the selection just past the item; clamp to the item,+ // but only when nothing visible lies outside it.+ const range = selected.cloneRange();+ if (!root.contains(range.startContainer)) {+ range.setStart(root, 0);+ }+ if (!root.contains(range.endContainer)) {+ range.setEnd(root, root.childNodes.length);+ }+ if (selected.toString().trim() !== range.toString().trim()) {+ setSelection(null);+ return;+ }+ const start = textOffset(root, range.startContainer, range.startOffset);+ const end = textOffset(root, range.endContainer, range.endOffset);+ const quote = (root.textContent || '').slice(start, end);+ if (end <= start || !quote.trim() || quote.length > 500) {+ setSelection(null);+ return;+ }+ const rect = range.getBoundingClientRect();+ const rootRect = root.getBoundingClientRect();+ setSelection({+ postId,+ start,+ end,+ quote,+ top: rect.bottom - rootRect.top + 6,+ left: Math.max(0, rect.right - rootRect.left - 90),+ });+ }, [postId]);++ const startComment = useCallback(() => {+ if (!selection) {+ return;+ }+ const { top, left, ...anchor } = selection;+ setPending(anchor);+ setSelection(null);+ window.getSelection()?.removeAllRanges();+ setActiveThread(null);+ }, [selection, setPending, setActiveThread]);++ const threadOf = (e: MouseEvent<HTMLDivElement>) =>+ (e.target as HTMLElement)+ .closest<HTMLElement>('mark[data-thread-ids]')+ ?.dataset.threadIds?.split(',')[0] || null;++ return (+ <div className="relative">+ <div+ ref={ref}+ className="text-[14px] whitespace-pre-wrap leading-[22px]"+ onMouseUp={onMouseUp}+ onMouseOver={(e) => setHoveredThread(threadOf(e))}+ onMouseOut={() => setHoveredThread(null)}+ onClick={(e) => {+ const id = threadOf(e);+ if (id) {+ setActiveThread({ id, source: 'mark' });+ }+ }}+ dangerouslySetInnerHTML={{ __html: html }}+ />+ {!!selection && (+ <button+ type="button"+ onMouseDown={(e) => e.preventDefault()}+ onClick={startComment}+ style={{ top: selection.top, left: selection.left }}+ className="absolute z-[10] bg-btnPrimary text-white text-[12px] font-[500] rounded-[6px] px-[10px] h-[28px] flex items-center gap-[6px] shadow-lg"+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width={14}+ height={14}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />+ </svg>+ {t('comment', 'Comment')}+ </button>+ )}+ </div>+ );+};diff --git a/apps/frontend/src/components/preview/preview.comments.context.tsx b/apps/frontend/src/components/preview/preview.comments.context.tsxnew file mode 100644index 000000000..25d9eb7fd--- /dev/null+++ b/apps/frontend/src/components/preview/preview.comments.context.tsx@@ -0,0 +1,105 @@+'use client';++import {+ createContext,+ FC,+ ReactNode,+ useCallback,+ useContext,+ useState,+} from 'react';+import useSWR from 'swr';+import { useFetch } from '@gitroom/helpers/utils/custom.fetch';++export interface PreviewComment {+ id: string;+ postId: string;+ parentId: string | null;+ content: string;+ anchorStart: number | null;+ anchorEnd: number | null;+ anchorQuote: string | null;+ resolvedAt: string | null;+ createdAt: string;+ name: string | null;+}++export interface PendingAnchor {+ postId: string;+ start: number;+ end: number;+ quote: string;+}++// Which side asked for the focus decides which side scrolls: a click on a+// highlight scrolls the card into view, a click on a card quote scrolls the+// highlight into view.+export interface ActiveThread {+ id: string;+ source: 'mark' | 'card';+}++const useComments = (previewId: string) => {+ const fetch = useFetch();+ const load = useCallback(async () => {+ return (await fetch(`/public/posts/${previewId}/comments`)).json();+ }, [previewId]);+ return useSWR<{ comments: PreviewComment[] }>(+ `/public/posts/${previewId}/comments`,+ load+ );+};++interface PreviewCommentsContextInterface {+ previewId: string;+ postIds: string[];+ organizationId: string;+ comments: PreviewComment[];+ isLoading: boolean;+ mutate: () => Promise<any>;+ pending: PendingAnchor | null;+ setPending: (pending: PendingAnchor | null) => void;+ activeThread: ActiveThread | null;+ setActiveThread: (thread: ActiveThread | null) => void;+ hoveredThread: string | null;+ setHoveredThread: (id: string | null) => void;+}++const PreviewCommentsContext = createContext<PreviewCommentsContextInterface>(+ {} as PreviewCommentsContextInterface+);++export const PreviewCommentsProvider: FC<{+ previewId: string;+ postIds: string[];+ organizationId: string;+ children: ReactNode;+}> = ({ previewId, postIds, organizationId, children }) => {+ const { data, mutate, isLoading } = useComments(previewId);+ const [pending, setPending] = useState<PendingAnchor | null>(null);+ const [activeThread, setActiveThread] = useState<ActiveThread | null>(null);+ const [hoveredThread, setHoveredThread] = useState<string | null>(null);++ return (+ <PreviewCommentsContext.Provider+ value={{+ previewId,+ postIds,+ organizationId,+ comments: data?.comments || [],+ isLoading,+ mutate,+ pending,+ setPending,+ activeThread,+ setActiveThread,+ hoveredThread,+ setHoveredThread,+ }}+ >+ {children}+ </PreviewCommentsContext.Provider>+ );+};++export const usePreviewComments = () => useContext(PreviewCommentsContext);diff --git a/libraries/helpers/src/utils/sanitize.post.content.ts b/libraries/helpers/src/utils/sanitize.post.content.tsindex 9f2d98618..204fee139 100644--- a/libraries/helpers/src/utils/sanitize.post.content.ts+++ b/libraries/helpers/src/utils/sanitize.post.content.ts@@ -1,4 +1,5 @@import DOMPurify from 'isomorphic-dompurify';+import { parseFragment } from 'parse5';const ALLOWED_TAGS = ['p',@@ -34,3 +35,17 @@ export const sanitizePostContent = (value: unknown): string => {ALLOWED_URI_REGEXP: /^(?:https?:|mailto:|\/|#)/i,});};++// The plain text a reviewer sees for a post item: the text nodes of the+// sanitised HTML, in order, entities decoded. This is what anchor offsets+// index into on both the frontend (element.textContent) and the backend.+export const postContentPlainText = (value: unknown): string => {+ const walk = (nodes: any[]): string =>+ nodes+ .map((node) =>+ node.nodeName === '#text' ? node.value : walk(node.childNodes || [])+ )+ .join('');++ return walk(parseFragment(sanitizePostContent(value)).childNodes as any[]);+};diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.tsindex 4d6e240f6..c1515a2be 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts@@ -814,10 +814,21 @@ export class PostsRepository {);}- async getComments(postId: string) {+ getCommentsForPosts(postIds: string[]) {return this._comments.model.comments.findMany({where: {- postId,+ postId: {+ in: postIds,+ },+ deletedAt: null,+ },+ include: {+ user: {+ select: {+ name: true,+ lastName: true,+ },+ },},orderBy: {createdAt: 'asc',@@ -825,6 +836,61 @@ export class PostsRepository {});}+ getCommentById(id: string) {+ return this._comments.model.comments.findFirst({+ where: {+ id,+ deletedAt: null,+ },+ include: {+ post: {+ select: {+ id: true,+ organizationId: true,+ },+ },+ },+ });+ }++ setCommentResolved(id: string, resolvedAt: Date | null) {+ return this._comments.model.comments.update({+ where: {+ id,+ },+ data: {+ resolvedAt,+ },+ });+ }++ getAnchoredCommentsForPost(postId: string) {+ return this._comments.model.comments.findMany({+ where: {+ postId,+ deletedAt: null,+ anchorStart: {+ not: null,+ },+ },+ });+ }++ detachAnchorsForPost(postId: string, ids: string[]) {+ return this._comments.model.comments.updateMany({+ where: {+ postId,+ id: {+ in: ids,+ },+ },+ data: {+ anchorStart: null,+ anchorEnd: null,+ },+ });+ }+async getTags(orgId: string) {return this._tags.model.tags.findMany({where: {@@ -870,9 +936,16 @@ export class PostsRepository {createComment(orgId: string,- userId: string,+ userId: string | null,postId: string,- content: string+ content: string,+ extra: {+ displayName?: string;+ parentId?: string;+ anchorStart?: number;+ anchorEnd?: number;+ anchorQuote?: string;+ } = {}) {return this._comments.model.comments.create({data: {@@ -880,6 +953,11 @@ export class PostsRepository {userId,postId,content,+ displayName: extra.displayName ?? null,+ parentId: extra.parentId ?? null,+ anchorStart: extra.anchorStart ?? null,+ anchorEnd: extra.anchorEnd ?? null,+ anchorQuote: extra.anchorQuote ?? null,},});}diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.tsindex 13e684f81..b46a1ccd3 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts@@ -53,6 +53,8 @@ import { stripLinks } from '@gitroom/helpers/utils/strip.links';import { validate } from 'class-validator';import { plainToInstance } from 'class-transformer';import { stripHtmlValidation } from '@gitroom/helpers/utils/strip.html.validation';+import { postContentPlainText } from '@gitroom/helpers/utils/sanitize.post.content';+import { CreatePublicCommentDto } from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';import { weightedLength } from '@gitroom/helpers/utils/count.length';type PostWithConditionals = Post & {@@ -826,7 +828,10 @@ export class PostsService {errors = err?.message || 'Invalid media';}- const maximumCharacters = provider.maxLength(additionalSettings, settings);+ const maximumCharacters = provider.maxLength(+ additionalSettings,+ settings+ );const isX = integration.providerIdentifier === 'x';const emptyContent = (post.value || []).some((a) => {@@ -878,7 +883,11 @@ export class PostsService {// the platform: require the explicit `republish` opt-in instead. The message// doubles as the confirmation dialog for API/MCP automation.private guardAgainstRepublish(- post: { state: State; publishDate: Date; integration?: { providerIdentifier: string } } | null,+ post: {+ state: State;+ publishDate: Date;+ integration?: { providerIdentifier: string };+ } | null,source: 'createPost' | 'changeDate') {if (post?.state !== 'PUBLISHED') {@@ -891,7 +900,9 @@ export class PostsService {throw new BadRequestException(`This post was already published on ${dayjs.utc(post.publishDate)- .format('YYYY-MM-DD HH:mm')} UTC. Saving it this way would publish it again to ${+ .format(+ 'YYYY-MM-DD HH:mm'+ )} UTC. Saving it this way would publish it again to ${post.integration?.providerIdentifier || 'the channel'}. To edit without republishing, ${howToUpdate}. To intentionally publish again, pass republish: true.`);@@ -950,6 +961,11 @@ export class PostsService {return [] as any[];}+ const existingIds = (post.value || []).map((p) => p.id).filter(Boolean);+ await this.detachStaleAnchors(+ posts.filter((p) => existingIds.includes(p.id))+ );+if (body.type !== 'update') {this.startWorkflow(post.settings.__type.split('-')[0].toLowerCase(),@@ -1331,8 +1347,170 @@ export class PostsService {return date.clone().add(num, 'minutes').format('YYYY-MM-DDTHH:mm:00');}- getComments(postId: string) {- return this._postRepository.getComments(postId);+ async getComments(previewId: string) {+ const posts = await this.getPostsRecursively(previewId, false);+ const comments = await this._postRepository.getCommentsForPosts(+ posts.map((p) => p.id)+ );++ return comments.map((comment) => ({+ id: comment.id,+ postId: comment.postId,+ parentId: comment.parentId,+ content: comment.content,+ anchorStart: comment.anchorStart,+ anchorEnd: comment.anchorEnd,+ anchorQuote: comment.anchorQuote,+ resolvedAt: comment.resolvedAt,+ createdAt: comment.createdAt,+ name: comment.userId+ ? [comment.user?.name, comment.user?.lastName]+ .filter(Boolean)+ .join(' ')+ .trim() || null+ : comment.displayName,+ }));+ }++ async createPublicComment(+ previewId: string,+ body: CreatePublicCommentDto,+ userId: string | null,+ ip: string+ ) {+ const posts = await this.getPostsRecursively(previewId, false);+ if (!posts.length) {+ throw new NotFoundException('Post not found');+ }++ let post = body.postId ? posts.find((p) => p.id === body.postId) : posts[0];+ if (!post) {+ throw new BadRequestException('Post does not belong to this preview');+ }++ if (!userId) {+ if (!body.displayName?.trim()) {+ throw new BadRequestException('Name is required');+ }+ await this.verifyRecaptcha(body.recaptchaToken, ip);+ }++ const hasStart = typeof body.anchorStart === 'number';+ const hasEnd = typeof body.anchorEnd === 'number';+ if (hasStart !== hasEnd) {+ throw new BadRequestException('Both anchor offsets are required');+ }++ if (body.parentId) {+ const parent = await this._postRepository.getCommentById(body.parentId);+ if (!parent || !posts.some((p) => p.id === parent.postId)) {+ throw new BadRequestException('Parent comment not found');+ }+ if (parent.parentId) {+ throw new BadRequestException(+ 'Replies can only be added to a root comment'+ );+ }+ if (hasStart || body.anchorQuote) {+ throw new BadRequestException('Replies cannot be anchored');+ }+ post = posts.find((p) => p.id === parent.postId)!;+ }++ if (hasStart) {+ const plainText = postContentPlainText(post.content);+ if (+ body.anchorStart! < 0 ||+ body.anchorStart! >= body.anchorEnd! ||+ body.anchorEnd! > plainText.length+ ) {+ throw new BadRequestException('Anchor is out of range');+ }+ if (+ body.anchorQuote !== plainText.slice(body.anchorStart!, body.anchorEnd!)+ ) {+ throw new BadRequestException('Anchor does not match the post text');+ }+ }++ return this._postRepository.createComment(+ post.organizationId,+ userId,+ post.id,+ body.content,+ {+ displayName: userId ? undefined : body.displayName!.trim(),+ parentId: body.parentId,+ anchorStart: hasStart ? body.anchorStart : undefined,+ anchorEnd: hasStart ? body.anchorEnd : undefined,+ anchorQuote: hasStart ? body.anchorQuote : undefined,+ }+ );+ }++ private async verifyRecaptcha(token: string | undefined, ip: string) {+ if (!process.env.RECAPTCHA_SECRET_KEY) {+ return;+ }++ if (!token) {+ throw new BadRequestException('Captcha verification failed');+ }++ const result = await (+ await fetch('https://www.google.com/recaptcha/api/siteverify', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ secret: process.env.RECAPTCHA_SECRET_KEY,+ response: token,+ remoteip: ip,+ }),+ })+ ).json();++ if (!result?.success) {+ throw new BadRequestException('Captcha verification failed');+ }+ }++ async resolveComment(orgId: string, commentId: string, resolved: boolean) {+ const comment = await this._postRepository.getCommentById(commentId);+ if (!comment || comment.post.organizationId !== orgId) {+ throw new NotFoundException('Comment not found');+ }+ if (comment.parentId) {+ throw new BadRequestException('Only root comments can be resolved');+ }++ return this._postRepository.setCommentResolved(+ commentId,+ resolved ? new Date() : null+ );+ }++ // A comment anchored to a span of text keeps its quote but loses the+ // highlight once the span no longer reads the same on the new content.+ async detachStaleAnchors(posts: { id: string; content: string }[]) {+ for (const post of posts) {+ const anchored = await this._postRepository.getAnchoredCommentsForPost(+ post.id+ );+ if (!anchored.length) {+ continue;+ }++ const plainText = postContentPlainText(post.content);+ const stale = anchored+ .filter(+ (c) => c.anchorQuote !== plainText.slice(c.anchorStart!, c.anchorEnd!)+ )+ .map((c) => c.id);++ if (stale.length) {+ await this._postRepository.detachAnchorsForPost(post.id, stale);+ }+ }}getTags(orgId: string) {@@ -1350,13 +1528,4 @@ export class PostsService {deleteTag(id: string, orgId: string) {return this._postRepository.deleteTag(id, orgId);}-- createComment(- orgId: string,- userId: string,- postId: string,- comment: string- ) {- return this._postRepository.createComment(orgId, userId, postId, comment);- }}diff --git a/libraries/nestjs-libraries/src/database/prisma/schema.prisma b/libraries/nestjs-libraries/src/database/prisma/schema.prismaindex 623bc0c68..20e853e19 100644--- a/libraries/nestjs-libraries/src/database/prisma/schema.prisma+++ b/libraries/nestjs-libraries/src/database/prisma/schema.prisma@@ -380,18 +380,28 @@ model Comments {content StringorganizationId StringpostId String- userId String+ userId String?+ displayName String?+ parentId String?+ anchorStart Int?+ anchorEnd Int?+ anchorQuote String?+ resolvedAt DateTime?createdAt DateTime @default(now())updatedAt DateTime @updatedAtdeletedAt DateTime?organization Organization @relation(fields: [organizationId], references: [id])post Post @relation(fields: [postId], references: [id])- user User @relation(fields: [userId], references: [id])+ user User? @relation(fields: [userId], references: [id])+ parent Comments? @relation("CommentReplies", fields: [parentId], references: [id])+ replies Comments[] @relation("CommentReplies")@@index([createdAt])@@index([organizationId])@@index([userId])@@index([postId])+ @@index([parentId])+ @@index([resolvedAt])@@index([deletedAt])}diff --git a/libraries/nestjs-libraries/src/dtos/comments/add.comment.dto.ts b/libraries/nestjs-libraries/src/dtos/comments/add.comment.dto.tsindex df7114cbf..0e23ca654 100644--- a/libraries/nestjs-libraries/src/dtos/comments/add.comment.dto.ts+++ b/libraries/nestjs-libraries/src/dtos/comments/add.comment.dto.ts@@ -1,4 +1,56 @@+import {+ IsBoolean,+ IsInt,+ IsOptional,+ IsString,+ MaxLength,+ Min,+ MinLength,+} from 'class-validator';+export class AddCommentDto {+ @IsString()+ @MinLength(1)+ @MaxLength(2000)content: string;- date: string;+}++export class CreatePublicCommentDto extends AddCommentDto {+ @IsOptional()+ @IsString()+ postId?: string;++ @IsOptional()+ @IsInt()+ @Min(0)+ anchorStart?: number;++ @IsOptional()+ @IsInt()+ @Min(0)+ anchorEnd?: number;++ @IsOptional()+ @IsString()+ @MaxLength(500)+ anchorQuote?: string;++ @IsOptional()+ @IsString()+ parentId?: string;++ @IsOptional()+ @IsString()+ @MinLength(1)+ @MaxLength(80)+ displayName?: string;++ @IsOptional()+ @IsString()+ recaptchaToken?: string;+}++export class ResolveCommentDto {+ @IsBoolean()+ resolved: boolean;}diff --git a/libraries/nestjs-libraries/src/throttler/throttler.provider.ts b/libraries/nestjs-libraries/src/throttler/throttler.provider.tsindex 72b218d55..89aab0012 100644--- a/libraries/nestjs-libraries/src/throttler/throttler.provider.ts+++ b/libraries/nestjs-libraries/src/throttler/throttler.provider.ts@@ -2,13 +2,19 @@ import { ThrottlerGuard } from '@nestjs/throttler';import { ExecutionContext, Injectable } from '@nestjs/common';import { Request } from 'express';+const isPublicComment = (method: string, url: string) =>+ method === 'POST' && /^\/public\/posts\/[^/]+\/comments/.test(url);+@Injectable()export class ThrottlerBehindProxyGuard extends ThrottlerGuard {public override async canActivate(context: ExecutionContext): Promise<boolean> {const { url, method } = context.switchToHttp().getRequest<Request>();- if (method === 'POST' && url.includes('/public/v1/posts')) {+ if (+ (method === 'POST' && url.includes('/public/v1/posts')) ||+ isPublicComment(method, url)+ ) {return super.canActivate(context);}@@ -18,6 +24,13 @@ export class ThrottlerBehindProxyGuard extends ThrottlerGuard {protected override async getTracker(req: Record<string, any>): Promise<string> {+ if (!req.org) {+ const forwarded = String(req.headers?.['x-forwarded-for'] || '')+ .split(',')[0]+ .trim();+ return 'ip_' + (forwarded || req.ip || 'unknown');+ }+return (req.org.id + '_' + (req.url.indexOf('/posts') > -1 ? 'posts' : 'other'));diff --git a/libraries/react-shared-libraries/src/helpers/variable.context.tsx b/libraries/react-shared-libraries/src/helpers/variable.context.tsxindex 67e3b4007..2521658f9 100644--- a/libraries/react-shared-libraries/src/helpers/variable.context.tsx+++ b/libraries/react-shared-libraries/src/helpers/variable.context.tsx@@ -33,6 +33,7 @@ interface VariableContextInterface {extensionId: string;googleAdsId?: string;googleAdsTrialTracking?: string;+ recaptchaSiteKey?: string;}const VariableContext = createContext({stripeClient: '',@@ -65,6 +66,7 @@ const VariableContext = createContext({transloadit: [],sentryDsn: '',extensionId: '',+ recaptchaSiteKey: '',} as VariableContextInterface);export const VariableContextComponent: FC<VariableContextInterface & {