Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

Mention teammates and react to post notes, on the web, the API and MCP (#490)

Paulo Castellano0ce4bc740a93
diff --git a/.ai/rules/jobs.md b/.ai/rules/jobs.md
index 32a92fc54..db4db9ee1 100644
--- a/.ai/rules/jobs.md
+++ b/.ai/rules/jobs.md
@@ -11,4 +11,4 @@ paths:
ReconcileGoogleBusinessPost must not rethrow GoogleBusinessPublishException. Permanent categories (NOT_FOUND, PERMISSION_DENIED, INVALID_ARGUMENT, Unknown) reject the target immediately and call FinalizePostPublication. Only ServerError, RateLimit, and ConnectionException defer until REVIEW_CEILING_HOURS. Throwing leaves last_reconciled_at stale, the 5-minute sweep re-dispatches, RecoverStuckPosts treats PendingReview as still-active, and the post sticks forever. failed() is the safety net if the worker dies mid-review — it must deferOrGiveUp (respect the 24h ceiling), never giveUp immediately. Job $timeout must exceed HasSocialHttpClient's 120s HTTP timeout. RecoverStuckPosts may only fail PendingReview after the same 24h ceiling timed from submitted_at — never created_at (a scheduled draft can be days old before it enters review) and never the 1h publishing timeout. Reconcile must refresh-and-retry on TokenExpiredException the same way PublishToSocialPlatform does; if verify() itself dies, mark the social account token-expired before deferring. If Business Information verify succeeds and Local Posts still 401s, defer without markAsTokenExpired — the token is still valid for the house verify. A 401 must not sit in review for 24h while a refresh would have settled it. JPEG derivatives stay on disk while LocalPostState is Processing/Scheduled so Google can fetch sourceUrl; settle(), RecoverStuckPosts' 1h publishing timeout and the expired-review path prune them. Reconcile must giveUp immediately when socialAccount is null (disconnect nulls the FK and would TypeError in fetchRemote). When RecoverStuckPosts settles a post's publication, call FinalizePostPublication so the owner is notified — do not mark the post Failed/Published by hand. Never compare raw PROCESSING/SCHEDULED/LIVE strings — use App\Enums\GoogleBusiness\LocalPostState.
## Notifications are email only
-There is no in-app notification system: the `notifications` table, bell, broadcast event, presence heartbeat and WorkspaceUserChannel were removed in September 2026. SendNotification(user, type, mailable) only sends the Mailable, gated by User::wantsEmailFor(). User uses RoutesNotifications, not Notifiable (no database channel). A new post note (not an edit, delete or reaction) emails every workspace member except its author (NotifyPostNoteAdded → PostNoteAdded, Type::PostNoteAdded); there are no @mentions in notes. Do not reintroduce an in-app channel.
+There is no in-app notification system: the `notifications` table, bell, broadcast event, presence heartbeat and WorkspaceUserChannel were removed in September 2026. SendNotification(user, type, mailable) only sends the Mailable, gated by User::wantsEmailFor(). User uses RoutesNotifications, not Notifiable (no database channel). Note emails go through NotifyPostNoteRecipients, among the members who see the post (ListPostNoteAudience) and never to the author: the members a note mentions (everyone for `@[everyone]`) get PostNoteMentioned, a new note's other participants (the post's author, the approval requester, earlier note authors) get PostNoteAdded, and an edit emails only the people it newly mentions; reactions and deletes email nobody. Both are Type::PostNoteAdded. SendNotification and the note emails are dropped when their models are gone (#[DeleteWhenMissingModels]): a note deleted before its email goes out is not a failed job. Do not reintroduce an in-app channel.
diff --git a/AGENTS.md b/AGENTS.md
index 30aa3a501..81a3a96f5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -884,7 +884,8 @@ view turns a forgotten variable into a runtime-only failure.
- **Exception — the per-post table on the channel insights page** (owner decision 2026-10-05): it is page-based with numbered pages, 10 posts per page (`ListChannelPublicationPerformance::INSIGHTS_PAGE_SIZE`, through `insightsPage()`), and keeps `?page=` in the URL; a sort, period or filter change goes back to page 1. The API endpoint and the MCP tool for the same list keep the config page size through `handle()`.
- **Exception — the ideas board columns** (owner decision 2026-10-06): each stage column (and Unassigned) is its own scroll prop, `columns.<stage id|unassigned>`, with its own page name, and loads 10 ideas per page (`ListIdeas::BOARD_PAGE_SIZE`) as the column scrolls. A label filter change resets every column to page 1. Column counts come from the database (`stages.*.ideas_count`, `unassigned_count`), never from the loaded cards. The web board moves a card with `after_idea_id` (`MoveIdea::after()`), since a partly loaded column cannot send the full order; the API and MCP keep the full `idea_ids` contract. The gallery keeps the config page size.
- **Exception — the "What's New" modal** (owner decision 2026-10-14): it loads 5 entries per page, enough to fill the modal (capped at 640px) and the next one loads only when the user scrolls (`ListChangelogEntries::PAGE_SIZE`) under the page name `changelog_page`, as the shared optional scroll prop `changelogEntries` (built with the `changelog` card prop by `BuildChangelogProps`, which `HandleInertiaRequests` only spreads), requested by a partial reload when the modal opens.
- - **Exception — the invoices tab on the billing page** (October 2026): invoices live in Stripe, which only pages by cursor, so `BillingController@index` sends `Inertia::scroll()` over Cashier's `cursorPaginateInvoices()` (paid invoices only, config page size). It is the one cursor paginator in the app; database lists keep `paginate()`.
+ - **Exception — the invoices tab on the billing page** (October 2026): invoices live in Stripe, which only pages by cursor, so `BillingController@index` sends `Inertia::scroll()` over Cashier's `cursorPaginateInvoices()` (paid invoices only, config page size). Database lists keep `paginate()`, except the notes thread below.
+ - **Exception — the notes thread on the publish page** (owner decision 2026-11-12): `BuildPostNotesProps` sends `Inertia::scroll()` over `ListPostNotes::thread()`, a `cursorPaginate()` (cursor name `notes_cursor`, config page size, newest first with the id as tiebreaker) with `meta.total` added. Notes are created and deleted while a thread is open (by the user and, live, by teammates), and an offset page would then skip or repeat a note. The API and MCP note lists keep `paginate()` and their `page` / `meta.total` contract.
- **This includes the public REST API** (`app/Http/Controllers/Api`). It used to pin its own page size of 15 as a stable contract; that exception is gone, so a list endpoint reads the same config as everything else. Changing `app.pagination.default` therefore changes the API's page size too — deliberate, and the reason a list response always carries `meta.per_page` for clients to read rather than assume.
## Changelog ("What's New")
diff --git a/app/Actions/Post/BuildPublishPageProps.php b/app/Actions/Post/BuildPublishPageProps.php
index bd6aba380..38b789edf 100644
--- a/app/Actions/Post/BuildPublishPageProps.php
+++ b/app/Actions/Post/BuildPublishPageProps.php
@@ -6,6 +6,7 @@ namespace App\Actions\Post;
use App\Actions\Analytics\ReadPublicationAnalytics;
use App\Actions\Post\Queue\BuildQueueTimeline;
+use App\Actions\PostNote\BuildPostNotesProps;
use App\Actions\SocialAccount\CountPostsScheduledThisWeek;
use App\Actions\SocialAccount\CountPostsSentThisWeek;
use App\Enums\Post\ScheduleMode;
@@ -84,8 +85,8 @@ class BuildPublishPageProps
$basePosts = $workspace->posts()->onChannels($scopedChannelIds);
- $openPostNotesId = self::uuidQuery($request, 'notes');
- $openPostDetailsId = self::uuidQuery($request, 'post');
+ $openPostNotesId = RequestIds::uuid($request->query('notes'));
+ $openPostDetailsId = RequestIds::uuid($request->query('post'));
$focusedPostId = $openPostNotesId ?? $openPostDetailsId;
$resolveTab = fn (mixed $requested, ?string $focusedId): string => self::tab($requested, $focusedId ? (clone $basePosts)->whereKey($focusedId)->visiblePendingApprovalsFor($requester)->value('status') : null);
@@ -143,9 +144,8 @@ class BuildPublishPageProps
...$props,
'openComposer' => $editPost !== null,
'openComposerAssistant' => $request->boolean('assistant'),
- 'openPostNotesId' => $openPostNotesId,
+ ...BuildPostNotesProps::handle($request, $workspace),
'openPostDetailsId' => $openPostDetailsId,
- 'highlightNoteId' => is_string($request->query('note')) ? $request->query('note') : null,
'authUserId' => $user->id,
'editPost' => $editPost,
];
@@ -228,13 +228,6 @@ class BuildPublishPageProps
return $resolveTab(data_get($query, 'tab'), $focusedId) === $tab;
}
- private static function uuidQuery(Request $request, string $key): ?string
- {
- $value = $request->query($key);
-
- return is_string($value) && Str::isUuid($value) ? $value : null;
- }
-
private static function tab(mixed $requested, ?PostStatus $focusedPostStatus): string
{
if (blank($requested) && $focusedPostStatus !== null) {
diff --git a/app/Actions/PostNote/AddPostNoteReaction.php b/app/Actions/PostNote/AddPostNoteReaction.php
new file mode 100644
index 000000000..5c47b3cc8
--- /dev/null
+++ b/app/Actions/PostNote/AddPostNoteReaction.php
@@ -0,0 +1,26 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\PostNote;
+
+use App\Events\PostNoteChanged;
+use App\Models\Post;
+use App\Models\PostNote;
+use App\Models\User;
+
+final class AddPostNoteReaction
+{
+ /**
+ * React to a note with an emoji. Reacting again with the same emoji
+ * changes nothing.
+ */
+ public static function execute(Post $post, PostNote $note, User $user, string $emoji): PostNote
+ {
+ $reaction = $note->reactions()->createOrFirst(['user_id' => $user->id, 'emoji' => $emoji]);
+
+ PostNoteChanged::dispatchIf($reaction->wasRecentlyCreated, $post->id, $post->workspace_id, 'updated', $note->id);
+
+ return $note->load(PostNote::DISPLAY_RELATIONS);
+ }
+}
diff --git a/app/Actions/PostNote/BuildPostNotesProps.php b/app/Actions/PostNote/BuildPostNotesProps.php
new file mode 100644
index 000000000..c5af7c918
--- /dev/null
+++ b/app/Actions/PostNote/BuildPostNotesProps.php
@@ -0,0 +1,51 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\PostNote;
+
+use App\Http\Resources\App\PostNoteResource;
+use App\Models\Post;
+use App\Models\Workspace;
+use App\Support\RequestIds;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Gate;
+use Inertia\Inertia;
+use Inertia\ScrollProp;
+
+/**
+ * The notes thread the publish page shows: the post whose notes are
+ * open (`?notes=`), the note a link points at (`?note=`, only while it is
+ * still on that post, so a stale link never makes the app load every page
+ * looking for it) and the notes
+ * themselves, newest first and a page at a time by cursor for
+ * `<InfiniteScroll reverse>`, with their `meta.total`.
+ * Opening, closing and every change to the thread reload only these props.
+ */
+final class BuildPostNotesProps
+{
+ public const CURSOR_NAME = 'notes_cursor';
+
+ /**
+ * @return array{openPostNotesId: string|null, highlightNoteId: string|null, postNotes: ScrollProp|null}
+ */
+ public static function handle(Request $request, Workspace $workspace): array
+ {
+ $postId = RequestIds::uuid($request->query('notes'));
+ $post = transform($postId, fn (string $id): ?Post => $workspace->posts()->find($id));
+ $canRead = filled($post)
+ && Gate::forUser($request->user())->allows('view', $post)
+ && Gate::forUser($request->user())->allows('createPost', $workspace);
+
+ $noteId = RequestIds::uuid($request->query('note'));
+
+ return [
+ 'openPostNotesId' => $canRead ? $postId : null,
+ 'highlightNoteId' => $canRead && filled($noteId) && $post->notes()->whereKey($noteId)->exists() ? $noteId : null,
+ 'postNotes' => $canRead
+ ? Inertia::scroll(fn () => PostNoteResource::collection(ListPostNotes::thread($post, self::CURSOR_NAME))
+ ->additional(['meta' => ['total' => $post->notes()->count()]]))
+ : null,
+ ];
+ }
+}
diff --git a/app/Actions/PostNote/CreatePostNote.php b/app/Actions/PostNote/CreatePostNote.php
index dbe7ef667..f4aafb9d5 100644
--- a/app/Actions/PostNote/CreatePostNote.php
+++ b/app/Actions/PostNote/CreatePostNote.php
@@ -8,6 +8,8 @@ use App\Events\PostNoteChanged;
use App\Models\Post;
use App\Models\PostNote;
use App\Models\User;
+use App\Support\PostNoteMentions;
+use Illuminate\Support\Facades\DB;
final class CreatePostNote
{
@@ -16,15 +18,23 @@ final class CreatePostNote
*/
public static function execute(Post $post, User $author, array $data): PostNote
{
- $note = $post->notes()->create([
- 'user_id' => $author->id,
- 'body' => data_get($data, 'body'),
- ]);
+ $audience = ListPostNoteAudience::execute($post);
- $note->load('user.avatarMedia');
+ $note = DB::transaction(function () use ($post, $author, $data, $audience): PostNote {
+ $note = $post->notes()->create([
+ 'user_id' => $author->id,
+ 'body' => PostNoteMentions::withoutMentionsOutside((string) data_get($data, 'body'), $audience),
+ ]);
- NotifyPostNoteAdded::execute($note);
- PostNoteChanged::dispatch($post->id, $post->workspace_id, 'created');
+ $note->mentions()->sync(PostNoteMentions::extract($note->body));
+
+ return $note;
+ });
+
+ $note->load(PostNote::DISPLAY_RELATIONS);
+
+ NotifyPostNoteRecipients::created($note, $author, $audience);
+ PostNoteChanged::dispatch($post->id, $post->workspace_id, 'created', $note->id);
return $note;
}
diff --git a/app/Actions/PostNote/DeletePostNote.php b/app/Actions/PostNote/DeletePostNote.php
index 77dea6546..99c79f057 100644
--- a/app/Actions/PostNote/DeletePostNote.php
+++ b/app/Actions/PostNote/DeletePostNote.php
@@ -14,6 +14,6 @@ final class DeletePostNote
{
$note->delete();
- PostNoteChanged::dispatch($post->id, $post->workspace_id, 'deleted');
+ PostNoteChanged::dispatch($post->id, $post->workspace_id, 'deleted', $note->id);
}
}
diff --git a/app/Actions/PostNote/ListPostNoteAudience.php b/app/Actions/PostNote/ListPostNoteAudience.php
new file mode 100644
index 000000000..3ca2f362b
--- /dev/null
+++ b/app/Actions/PostNote/ListPostNoteAudience.php
@@ -0,0 +1,41 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\PostNote;
+
+use App\Enums\Post\Status;
+use App\Models\Post;
+use App\Models\User;
+use Illuminate\Database\Eloquent\Collection;
+use Illuminate\Support\Str;
+
+final class ListPostNoteAudience
+{
+ /**
+ * The members who see the post's notes: every member of its workspace,
+ * and on a pending request only the approvers and the member who asked.
+ * They are the people a note may mention and email, and the mention card
+ * reads them, so the viewer is in the list too. Sorted by name in PHP,
+ * ignoring case and accents (a name `Str::ascii` empties, like 山田, by its
+ * own text, then by id), so PostgreSQL and MySQL give the same order.
+ *
+ * @return Collection<int, User>
+ */
+ public static function execute(Post $post): Collection
+ {
+ $workspace = $post->workspace;
+
+ $isPending = $post->status === Status::PendingApproval;
+ $requesterId = $isPending ? $post->approvalRequester()?->id : null;
+
+ return $workspace->members()
+ ->with(['account', 'avatarMedia'])
+ ->get()
+ ->sortBy(fn (User $member): array => [Str::lower(Str::ascii($member->name)), Str::lower($member->name), $member->id])
+ ->when($isPending, fn (Collection $members): Collection => $members->filter(
+ fn (User $member): bool => $member->id === $requesterId || $member->publishesDirectlyThrough($workspace, $member->pivot),
+ ))
+ ->values();
+ }
+}
diff --git a/app/Actions/PostNote/ListPostNotes.php b/app/Actions/PostNote/ListPostNotes.php
index ed2e42a04..f18613194 100644
--- a/app/Actions/PostNote/ListPostNotes.php
+++ b/app/Actions/PostNote/ListPostNotes.php
@@ -6,6 +6,7 @@ namespace App\Actions\PostNote;
use App\Models\Post;
use App\Models\PostNote;
+use Illuminate\Pagination\CursorPaginator;
use Illuminate\Pagination\LengthAwarePaginator;
final class ListPostNotes
@@ -16,8 +17,26 @@ final class ListPostNotes
public static function execute(Post $post, ?int $page = null): LengthAwarePaginator
{
return $post->notes()
- ->with('user.avatarMedia')
+ ->with(PostNote::DISPLAY_RELATIONS)
->latest()
+ ->latest('id')
->paginate((int) config('app.pagination.default'), page: $page);
}
+
+ /**
+ * The thread the publish page shows, newest first, a page at a time by
+ * cursor: each older page starts after the last note loaded, so notes added
+ * or deleted while the thread is open never shift it (see AGENTS.md,
+ * "Pagination").
+ *
+ * @return CursorPaginator<int, PostNote>
+ */
+ public static function thread(Post $post, string $cursorName): CursorPaginator
+ {
+ return $post->notes()
+ ->with(PostNote::DISPLAY_RELATIONS)
+ ->latest()
+ ->latest('id')
+ ->cursorPaginate((int) config('app.pagination.default'), cursorName: $cursorName);
+ }
}
diff --git a/app/Actions/PostNote/NotifyPostNoteAdded.php b/app/Actions/PostNote/NotifyPostNoteAdded.php
deleted file mode 100644
index 1f7c7fdb0..000000000
--- a/app/Actions/PostNote/NotifyPostNoteAdded.php
+++ /dev/null
@@ -1,50 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Actions\PostNote;
-
-use App\Enums\Notification\Type;
-use App\Enums\Post\Status;
-use App\Jobs\SendNotification;
-use App\Mail\PostNoteAdded;
-use App\Models\PostNote;
-use App\Models\User;
-use Illuminate\Database\Eloquent\Collection;
-
-final class NotifyPostNoteAdded
-{
- /**
- * Email every member of the post's workspace, except the note's author.
- * A note on a pending request reaches only those who can see it: the
- * approvers and the member who asked.
- */
- public static function execute(PostNote $note): void
- {
- $author = $note->user;
- $post = $note->post;
- $workspace = $post?->workspace;
-
- if (! $author instanceof User || ! $workspace) {
- return;
- }
-
- $requesterId = $post->status === Status::PendingApproval ? $post->approvalRequester()?->id : null;
-
- $workspace->members()
- ->with('account')
- ->where('users.id', '!=', $author->id)
- ->get()
- ->when(
- $post->status === Status::PendingApproval,
- fn (Collection $members): Collection => $members->filter(
- fn (User $member): bool => $member->id === $requesterId || $member->publishesDirectlyThrough($workspace, $member->pivot),
- ),
- )
- ->each(fn (User $member) => SendNotification::dispatch(
- user: $member,
- type: Type::PostNoteAdded,
- mailable: new PostNoteAdded(note: $note, author: $author),
- ));
- }
-}
diff --git a/app/Actions/PostNote/NotifyPostNoteRecipients.php b/app/Actions/PostNote/NotifyPostNoteRecipients.php
new file mode 100644
index 000000000..df78da2a6
--- /dev/null
+++ b/app/Actions/PostNote/NotifyPostNoteRecipients.php
@@ -0,0 +1,89 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\PostNote;
+
+use App\Enums\Notification\Type;
+use App\Jobs\SendNotification;
+use App\Mail\PostNoteAdded;
+use App\Mail\PostNoteMentioned;
+use App\Models\PostNote;
+use App\Models\User;
+use App\Support\PostNoteMentions;
+use Closure;
+use Illuminate\Database\Eloquent\Collection;
+use Illuminate\Mail\Mailable;
+
+/**
+ * Who hears about a note, among the members who see it (`$audience`, from
+ * ListPostNoteAudience), never its author: the people it mentions (everyone with `@all`) get a
+ * mention email, and on a new note the post's other participants (its author,
+ * the member who asked for approval and everyone who wrote a note on it) get
+ * the note email.
+ */
+final class NotifyPostNoteRecipients
+{
+ /**
+ * @param Collection<int, User> $audience
+ */
+ public static function created(PostNote $note, User $author, Collection $audience): void
+ {
+ $post = $note->post;
+ $recipients = $audience->reject(fn (User $member): bool => $member->is($author));
+ $mentioned = self::mentionedIn($note->body, $recipients);
+
+ $participantIds = $post->notes()
+ ->whereNotNull('user_id')
+ ->distinct()
+ ->pluck('user_id')
+ ->push($post->user_id, $post->approvalRequester()?->id);
+
+ self::email($mentioned, fn (): Mailable => new PostNoteMentioned(note: $note, author: $author));
+ self::email(
+ $recipients->diff($mentioned)->filter(fn (User $member): bool => $participantIds->contains($member->id)),
+ fn (): Mailable => new PostNoteAdded(note: $note, author: $author),
+ );
+ }
+
+ /**
+ * An edit only emails the people it adds as mentions.
+ *
+ * @param Collection<int, User> $audience
+ */
+ public static function edited(PostNote $note, User $author, string $previousBody, Collection $audience): void
+ {
+ $recipients = $audience->reject(fn (User $member): bool => $member->is($author));
+ $newlyMentioned = self::mentionedIn($note->body, $recipients)->diff(self::mentionedIn($previousBody, $recipients));
+
+ self::email($newlyMentioned, fn (): Mailable => new PostNoteMentioned(note: $note, author: $author));
+ }
+
+ /**
+ * @param Collection<int, User> $audience
+ * @return Collection<int, User>
+ */
+ private static function mentionedIn(string $body, Collection $audience): Collection
+ {
+ if (PostNoteMentions::mentionsEveryone($body)) {
+ return $audience;
+ }
+
+ $ids = PostNoteMentions::extract($body);
+
+ return $audience->filter(fn (User $member): bool => $ids->contains($member->id));
+ }
+
+ /**
+ * @param Collection<int, User> $members
+ * @param Closure(): Mailable $mailable
+ */
+ private static function email(Collection $members, Closure $mailable): void
+ {
+ $members->each(fn (User $member) => SendNotification::dispatch(
+ user: $member,
+ type: Type::PostNoteAdded,
+ mailable: $mailable(),
+ ));
+ }
+}
diff --git a/app/Actions/PostNote/RemovePostNoteReaction.php b/app/Actions/PostNote/RemovePostNoteReaction.php
new file mode 100644
index 000000000..1ab1f8161
--- /dev/null
+++ b/app/Actions/PostNote/RemovePostNoteReaction.php
@@ -0,0 +1,25 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\PostNote;
+
+use App\Events\PostNoteChanged;
+use App\Models\Post;
+use App\Models\PostNote;
+use App\Models\User;
+
+final class RemovePostNoteReaction
+{
+ /**
+ * Take back the user's reaction with that emoji, if they had one.
+ */
+ public static function execute(Post $post, PostNote $note, User $user, string $emoji): PostNote
+ {
+ $removed = $note->reactions()->where('user_id', $user->id)->where('emoji', $emoji)->delete();
+
+ PostNoteChanged::dispatchIf($removed > 0, $post->id, $post->workspace_id, 'updated', $note->id);
+
+ return $note->load(PostNote::DISPLAY_RELATIONS);
+ }
+}
diff --git a/app/Actions/PostNote/SummarizePostNoteReactions.php b/app/Actions/PostNote/SummarizePostNoteReactions.php
new file mode 100644
index 000000000..4badd6b5e
--- /dev/null
+++ b/app/Actions/PostNote/SummarizePostNoteReactions.php
@@ -0,0 +1,34 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\PostNote;
+
+use App\Models\PostNote;
+use App\Models\PostNoteReaction;
+use Illuminate\Support\Collection;
+
+final class SummarizePostNoteReactions
+{
+ /**
+ * The note's reactions grouped by emoji, in the order each emoji was
+ * first used, with who reacted. Load `reactions.user` first.
+ *
+ * @return list<array{emoji: string, count: int, users: list<array{id: string, name: string}>}>
+ */
+ public static function execute(PostNote $note): array
+ {
+ return $note->reactions
+ ->groupBy('emoji')
+ ->map(fn (Collection $reactions, string $emoji): array => [
+ 'emoji' => $emoji,
+ 'count' => $reactions->count(),
+ 'users' => $reactions->map(fn (PostNoteReaction $reaction): array => [
+ 'id' => $reaction->user_id,
+ 'name' => $reaction->user->name,
+ ])->values()->all(),
+ ])
+ ->values()
+ ->all();
+ }
+}
diff --git a/app/Actions/PostNote/UpdatePostNote.php b/app/Actions/PostNote/UpdatePostNote.php
index c1362e23a..5c72d1e70 100644
--- a/app/Actions/PostNote/UpdatePostNote.php
+++ b/app/Actions/PostNote/UpdatePostNote.php
@@ -7,18 +7,29 @@ namespace App\Actions\PostNote;
use App\Events\PostNoteChanged;
use App\Models\Post;
use App\Models\PostNote;
+use App\Models\User;
+use App\Support\PostNoteMentions;
+use Illuminate\Support\Facades\DB;
final class UpdatePostNote
{
/**
* @param array{body?: string} $data
*/
- public static function execute(Post $post, PostNote $note, array $data): PostNote
+ public static function execute(Post $post, PostNote $note, User $author, array $data): PostNote
{
- $note->update(['body' => data_get($data, 'body')]);
+ $previousBody = $note->body;
+ $audience = ListPostNoteAudience::execute($post);
- PostNoteChanged::dispatch($post->id, $post->workspace_id, 'updated');
+ DB::transaction(function () use ($note, $data, $audience): void {
+ $note->update(['body' => PostNoteMentions::withoutMentionsOutside((string) data_get($data, 'body'), $audience)]);
+ $note->mentions()->sync(PostNoteMentions::extract($note->body));
+ });
- return $note->load('user.avatarMedia');
+ NotifyPostNoteRecipients::edited($note, $author, $previousBody, $audience);
+
+ PostNoteChanged::dispatch($post->id, $post->workspace_id, 'updated', $note->id);
+
+ return $note->load(PostNote::DISPLAY_RELATIONS);
}
}
diff --git a/app/Events/PostNoteChanged.php b/app/Events/PostNoteChanged.php
index 657ccad9d..c5f6099f0 100644
--- a/app/Events/PostNoteChanged.php
+++ b/app/Events/PostNoteChanged.php
@@ -9,6 +9,10 @@ use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
+/**
+ * A note of the post was created, updated (its text or its reactions) or
+ * deleted. It names the note, so an open thread updates that note alone.
+ */
class PostNoteChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets;
@@ -17,6 +21,7 @@ class PostNoteChanged implements ShouldBroadcast
public string $postId,
public string $workspaceId,
public string $change,
+ public ?string $noteId = null,
) {}
public function broadcastAs(): string
@@ -32,10 +37,10 @@ class PostNoteChanged implements ShouldBroadcast
];
}
- /** @return array{post_id: string, change: string} */
+ /** @return array{post_id: string, note_id: string|null, change: string} */
public function broadcastWith(): array
{
- return ['post_id' => $this->postId, 'change' => $this->change];
+ return ['post_id' => $this->postId, 'note_id' => $this->noteId, 'change' => $this->change];
}
public function broadcastQueue(): string
diff --git a/app/Http/Controllers/Api/PostNoteController.php b/app/Http/Controllers/Api/PostNoteController.php
index 866d83dc8..6312cb3fb 100644
--- a/app/Http/Controllers/Api/PostNoteController.php
+++ b/app/Http/Controllers/Api/PostNoteController.php
@@ -35,9 +35,18 @@ class PostNoteController extends Controller
->setStatusCode(Response::HTTP_CREATED);
}
+ public function show(Post $post, PostNote $note): PostNoteResource
+ {
+ abort_unless($note->post_id === $post->id, Response::HTTP_NOT_FOUND);
+
+ $this->authorizeNotes($post);
+
+ return PostNoteResource::make($note->load(PostNote::DISPLAY_RELATIONS));
+ }
+
public function update(UpdatePostNoteRequest $request, Post $post, PostNote $note): PostNoteResource
{
- return new PostNoteResource(UpdatePostNote::execute($post, $note, $request->validated()));
+ return new PostNoteResource(UpdatePostNote::execute($post, $note, $request->user(), $request->validated()));
}
public function destroy(Post $post, PostNote $note): JsonResponse
diff --git a/app/Http/Controllers/Api/PostNoteMentionableController.php b/app/Http/Controllers/Api/PostNoteMentionableController.php
new file mode 100644
index 000000000..c5c79f3c4
--- /dev/null
+++ b/app/Http/Controllers/Api/PostNoteMentionableController.php
@@ -0,0 +1,21 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Controllers\Api;
+
+use App\Actions\PostNote\ListPostNoteAudience;
+use App\Http\Resources\Api\PostNoteMentionableResource;
+use App\Models\Post;
+use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
+
+class PostNoteMentionableController extends Controller
+{
+ public function index(Post $post): AnonymousResourceCollection
+ {
+ $this->authorize('view', $post);
+ $this->authorize('createPost', $post->workspace);
+
+ return PostNoteMentionableResource::collection(ListPostNoteAudience::execute($post));
+ }
+}
diff --git a/app/Http/Controllers/Api/PostNoteReactionController.php b/app/Http/Controllers/Api/PostNoteReactionController.php
new file mode 100644
index 000000000..3f8bb3f00
--- /dev/null
+++ b/app/Http/Controllers/Api/PostNoteReactionController.php
@@ -0,0 +1,26 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Controllers\Api;
+
+use App\Actions\PostNote\AddPostNoteReaction;
+use App\Actions\PostNote\RemovePostNoteReaction;
+use App\Http\Requests\Api\PostNoteReaction\DestroyPostNoteReactionRequest;
+use App\Http\Requests\Api\PostNoteReaction\UpdatePostNoteReactionRequest;
+use App\Http\Resources\Api\PostNoteResource;
+use App\Models\Post;
+use App\Models\PostNote;
+
+class PostNoteReactionController extends Controller
+{
+ public function update(UpdatePostNoteReactionRequest $request, Post $post, PostNote $note): PostNoteResource
+ {
+ return new PostNoteResource(AddPostNoteReaction::execute($post, $note, $request->user(), $request->validated('emoji')));
+ }
+
+ public function destroy(DestroyPostNoteReactionRequest $request, Post $post, PostNote $note): PostNoteResource
+ {
+ return new PostNoteResource(RemovePostNoteReaction::execute($post, $note, $request->user(), $request->validated('emoji')));
+ }
+}
diff --git a/app/Http/Controllers/App/PostNoteController.php b/app/Http/Controllers/App/PostNoteController.php
index fdf46934e..64ea51d30 100644
--- a/app/Http/Controllers/App/PostNoteController.php
+++ b/app/Http/Controllers/App/PostNoteController.php
@@ -6,7 +6,6 @@ namespace App\Http\Controllers\App;
use App\Actions\PostNote\CreatePostNote;
use App\Actions\PostNote\DeletePostNote;
-use App\Actions\PostNote\ListPostNotes;
use App\Actions\PostNote\UpdatePostNote;
use App\Http\Requests\App\PostNote\StorePostNoteRequest;
use App\Http\Requests\App\PostNote\UpdatePostNoteRequest;
@@ -14,25 +13,26 @@ use App\Http\Resources\App\PostNoteResource;
use App\Models\Post;
use App\Models\PostNote;
use Illuminate\Http\JsonResponse;
-use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Symfony\Component\HttpFoundation\Response;
class PostNoteController extends Controller
{
- public function index(Post $post): AnonymousResourceCollection
+ public function store(StorePostNoteRequest $request, Post $post): JsonResponse
{
$this->authorizeNotes($post);
- return PostNoteResource::collection(ListPostNotes::execute($post));
+ $note = CreatePostNote::execute($post, $request->user(), $request->validated());
+
+ return PostNoteResource::make($note)->response()->setStatusCode(Response::HTTP_CREATED);
}
- public function store(StorePostNoteRequest $request, Post $post): JsonResponse
+ public function show(Post $post, PostNote $note): PostNoteResource
{
- $this->authorizeNotes($post);
+ abort_unless($note->post_id === $post->id, Response::HTTP_NOT_FOUND);
- $note = CreatePostNote::execute($post, $request->user(), $request->validated());
+ $this->authorizeNotes($post);
- return PostNoteResource::make($note)->response()->setStatusCode(Response::HTTP_CREATED);
+ return PostNoteResource::make($note->load(PostNote::DISPLAY_RELATIONS));
}
public function update(UpdatePostNoteRequest $request, Post $post, PostNote $note): PostNoteResource
@@ -42,7 +42,7 @@ class PostNoteController extends Controller
$this->authorizeNotes($post);
$this->authorize('update', $note);
- return PostNoteResource::make(UpdatePostNote::execute($post, $note, $request->validated()));
+ return PostNoteResource::make(UpdatePostNote::execute($post, $note, $request->user(), $request->validated()));
}
public function destroy(Post $post, PostNote $note): JsonResponse
diff --git a/app/Http/Controllers/App/PostNoteMentionableController.php b/app/Http/Controllers/App/PostNoteMentionableController.php
new file mode 100644
index 000000000..c7f8d1f42
--- /dev/null
+++ b/app/Http/Controllers/App/PostNoteMentionableController.php
@@ -0,0 +1,21 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Controllers\App;
+
+use App\Actions\PostNote\ListPostNoteAudience;
+use App\Http\Resources\App\PostNoteMentionableResource;
+use App\Models\Post;
+use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
+
+class PostNoteMentionableController extends Controller
+{
+ public function index(Post $post): AnonymousResourceCollection
+ {
+ $this->authorize('view', $post);
+ $this->authorize('createPost', $post->workspace);
+
+ return PostNoteMentionableResource::collection(ListPostNoteAudience::execute($post));
+ }
+}
diff --git a/app/Http/Controllers/App/PostNoteReactionController.php b/app/Http/Controllers/App/PostNoteReactionController.php
new file mode 100644
index 000000000..4f95bce04
--- /dev/null
+++ b/app/Http/Controllers/App/PostNoteReactionController.php
@@ -0,0 +1,39 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Controllers\App;
+
+use App\Actions\PostNote\AddPostNoteReaction;
+use App\Actions\PostNote\RemovePostNoteReaction;
+use App\Http\Requests\App\PostNoteReaction\DestroyPostNoteReactionRequest;
+use App\Http\Requests\App\PostNoteReaction\UpdatePostNoteReactionRequest;
+use App\Http\Resources\App\PostNoteResource;
+use App\Models\Post;
+use App\Models\PostNote;
+use Symfony\Component\HttpFoundation\Response;
+
+class PostNoteReactionController extends Controller
+{
+ public function update(UpdatePostNoteReactionRequest $request, Post $post, PostNote $note): PostNoteResource
+ {
+ $this->authorizeReactions($post, $note);
+
+ return PostNoteResource::make(AddPostNoteReaction::execute($post, $note, $request->user(), $request->validated('emoji')));
+ }
+
+ public function destroy(DestroyPostNoteReactionRequest $request, Post $post, PostNote $note): PostNoteResource
+ {
+ $this->authorizeReactions($post, $note);
+
+ return PostNoteResource::make(RemovePostNoteReaction::execute($post, $note, $request->user(), $request->validated('emoji')));
+ }
+
+ private function authorizeReactions(Post $post, PostNote $note): void
+ {
+ abort_unless($note->post_id === $post->id, Response::HTTP_NOT_FOUND);
+
+ $this->authorize('view', $post);
+ $this->authorize('createPost', $post->workspace);
+ }
+}
diff --git a/app/Http/Requests/Api/PostNoteReaction/DestroyPostNoteReactionRequest.php b/app/Http/Requests/Api/PostNoteReaction/DestroyPostNoteReactionRequest.php
new file mode 100644
index 000000000..f4ccec904
--- /dev/null
+++ b/app/Http/Requests/Api/PostNoteReaction/DestroyPostNoteReactionRequest.php
@@ -0,0 +1,35 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Requests\Api\PostNoteReaction;
+
+use App\Rules\SingleEmoji;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Support\Facades\Gate;
+use Symfony\Component\HttpFoundation\Response;
+
+class DestroyPostNoteReactionRequest extends FormRequest
+{
+ public function authorize(): bool
+ {
+ abort_unless($this->route('note')->post_id === $this->route('post')->id, Response::HTTP_NOT_FOUND);
+
+ $gate = Gate::forUser($this->user());
+
+ $gate->authorize('view', $this->route('post'));
+ $gate->authorize('createPost', $this->route('post')->workspace);
+
+ return true;
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ public function rules(): array
+ {
+ return [
+ 'emoji' => ['required', 'string', new SingleEmoji],
+ ];
+ }
+}
diff --git a/app/Http/Requests/Api/PostNoteReaction/UpdatePostNoteReactionRequest.php b/app/Http/Requests/Api/PostNoteReaction/UpdatePostNoteReactionRequest.php
new file mode 100644
index 000000000..be10f26db
--- /dev/null
+++ b/app/Http/Requests/Api/PostNoteReaction/UpdatePostNoteReactionRequest.php
@@ -0,0 +1,35 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Requests\Api\PostNoteReaction;
+
+use App\Rules\SingleEmoji;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Support\Facades\Gate;
+use Symfony\Component\HttpFoundation\Response;
+
+class UpdatePostNoteReactionRequest extends FormRequest
+{
+ public function authorize(): bool
+ {
+ abort_unless($this->route('note')->post_id === $this->route('post')->id, Response::HTTP_NOT_FOUND);
+
+ $gate = Gate::forUser($this->user());
+
+ $gate->authorize('view', $this->route('post'));
+ $gate->authorize('createPost', $this->route('post')->workspace);
+
+ return true;
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ public function rules(): array
+ {
+ return [
+ 'emoji' => ['required', 'string', new SingleEmoji],
+ ];
+ }
+}
diff --git a/app/Http/Requests/App/PostNote/StorePostNoteRequest.php b/app/Http/Requests/App/PostNote/StorePostNoteRequest.php
index cd172cb75..faa9f59f4 100644
--- a/app/Http/Requests/App/PostNote/StorePostNoteRequest.php
+++ b/app/Http/Requests/App/PostNote/StorePostNoteRequest.php
@@ -19,4 +19,14 @@ class StorePostNoteRequest extends FormRequest
'body' => ['required', 'string', 'max:2000'],
];
}
+
+ /**
+ * @return array<string, string>
+ */
+ public function messages(): array
+ {
+ return [
+ 'body.max' => __('notes.errors.too_long'),
+ ];
+ }
}
diff --git a/app/Http/Requests/App/PostNote/UpdatePostNoteRequest.php b/app/Http/Requests/App/PostNote/UpdatePostNoteRequest.php
index d7b6d310c..20088b034 100644
--- a/app/Http/Requests/App/PostNote/UpdatePostNoteRequest.php
+++ b/app/Http/Requests/App/PostNote/UpdatePostNoteRequest.php
@@ -19,4 +19,14 @@ class UpdatePostNoteRequest extends FormRequest
'body' => ['required', 'string', 'max:2000'],
];
}
+
+ /**
+ * @return array<string, string>
+ */
+ public function messages(): array
+ {
+ return [
+ 'body.max' => __('notes.errors.too_long'),
+ ];
+ }
}
diff --git a/app/Http/Requests/App/PostNoteReaction/DestroyPostNoteReactionRequest.php b/app/Http/Requests/App/PostNoteReaction/DestroyPostNoteReactionRequest.php
new file mode 100644
index 000000000..dd4b8894a
--- /dev/null
+++ b/app/Http/Requests/App/PostNoteReaction/DestroyPostNoteReactionRequest.php
@@ -0,0 +1,26 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Requests\App\PostNoteReaction;
+
+use App\Rules\SingleEmoji;
+use Illuminate\Foundation\Http\FormRequest;
+
+class DestroyPostNoteReactionRequest extends FormRequest
+{
+ public function authorize(): bool
+ {
+ return true;
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ public function rules(): array
+ {
+ return [
+ 'emoji' => ['required', 'string', new SingleEmoji],
+ ];
+ }
+}
diff --git a/app/Http/Requests/App/PostNoteReaction/UpdatePostNoteReactionRequest.php b/app/Http/Requests/App/PostNoteReaction/UpdatePostNoteReactionRequest.php
new file mode 100644
index 000000000..d6e31b799
--- /dev/null
+++ b/app/Http/Requests/App/PostNoteReaction/UpdatePostNoteReactionRequest.php
@@ -0,0 +1,26 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Requests\App\PostNoteReaction;
+
+use App\Rules\SingleEmoji;
+use Illuminate\Foundation\Http\FormRequest;
+
+class UpdatePostNoteReactionRequest extends FormRequest
+{
+ public function authorize(): bool
+ {
+ return true;
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ public function rules(): array
+ {
+ return [
+ 'emoji' => ['required', 'string', new SingleEmoji],
+ ];
+ }
+}
diff --git a/app/Http/Resources/Api/PostNoteMentionableResource.php b/app/Http/Resources/Api/PostNoteMentionableResource.php
new file mode 100644
index 000000000..3bb63d7a6
--- /dev/null
+++ b/app/Http/Resources/Api/PostNoteMentionableResource.php
@@ -0,0 +1,31 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Resources\Api;
+
+use App\Models\User;
+use Illuminate\Http\Request;
+use Illuminate\Http\Resources\Json\JsonResource;
+
+/**
+ * A member a note may mention, written in the body as `@[user:id]`, with
+ * what the mention card shows.
+ *
+ * @mixin User
+ */
+class PostNoteMentionableResource extends JsonResource
+{
+ /**
+ * @return array{id: string, name: string, photo_url: string|null, timezone: string}
+ */
+ public function toArray(Request $request): array
+ {
+ return [
+ 'id' => $this->id,
+ 'name' => $this->name,
+ 'photo_url' => $this->photo_url,
+ 'timezone' => $this->timezone,
+ ];
+ }
+}
diff --git a/app/Http/Resources/Api/PostNoteResource.php b/app/Http/Resources/Api/PostNoteResource.php
index 0791670db..09fcbfbf4 100644
--- a/app/Http/Resources/Api/PostNoteResource.php
+++ b/app/Http/Resources/Api/PostNoteResource.php
@@ -4,7 +4,9 @@ declare(strict_types=1);
namespace App\Http\Resources\Api;
+use App\Actions\PostNote\SummarizePostNoteReactions;
use App\Models\PostNote;
+use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -14,7 +16,7 @@ use Illuminate\Http\Resources\Json\JsonResource;
class PostNoteResource extends JsonResource
{
/**
- * @return array{id: string, post_id: string, body: string, author: array{id: string, name: string|null, photo_url: string|null}|null, created_at: string, updated_at: string}
+ * @return array{id: string, post_id: string, body: string, mentions: list<array{id: string, name: string}>, reactions: list<array{emoji: string, count: int, users: list<array{id: string, name: string}>}>, author: array{id: string, name: string|null, photo_url: string|null}|null, created_at: string, updated_at: string}
*/
public function toArray(Request $request): array
{
@@ -22,6 +24,8 @@ class PostNoteResource extends JsonResource
'id' => $this->id,
'post_id' => $this->post_id,
'body' => $this->body,
+ 'mentions' => $this->mentions->map(fn (User $user): array => ['id' => $user->id, 'name' => $user->name])->values()->all(),
+ 'reactions' => SummarizePostNoteReactions::execute($this->resource),
'author' => $this->user === null ? null : [
'id' => $this->user->id,
'name' => $this->user->name,
diff --git a/app/Http/Resources/App/PostNoteMentionableResource.php b/app/Http/Resources/App/PostNoteMentionableResource.php
new file mode 100644
index 000000000..2179d9bba
--- /dev/null
+++ b/app/Http/Resources/App/PostNoteMentionableResource.php
@@ -0,0 +1,31 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Resources\App;
+
+use App\Models\User;
+use Illuminate\Http\Request;
+use Illuminate\Http\Resources\Json\JsonResource;
+
+/**
+ * A member a note may mention, written in the body as `@[user:id]`, with
+ * what the mention card shows.
+ *
+ * @mixin User
+ */
+class PostNoteMentionableResource extends JsonResource
+{
+ /**
+ * @return array{id: string, name: string, photo_url: string|null, timezone: string}
+ */
+ public function toArray(Request $request): array
+ {
+ return [
+ 'id' => $this->id,
+ 'name' => $this->name,
+ 'photo_url' => $this->photo_url,
+ 'timezone' => $this->timezone,
+ ];
+ }
+}
diff --git a/app/Http/Resources/App/PostNoteResource.php b/app/Http/Resources/App/PostNoteResource.php
index 367a00612..2383ce009 100644
--- a/app/Http/Resources/App/PostNoteResource.php
+++ b/app/Http/Resources/App/PostNoteResource.php
@@ -4,7 +4,10 @@ declare(strict_types=1);
namespace App\Http\Resources\App;
+use App\Actions\PostNote\SummarizePostNoteReactions;
use App\Models\PostNote;
+use App\Models\User;
+use App\Support\PostNoteMentions;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -14,7 +17,7 @@ use Illuminate\Http\Resources\Json\JsonResource;
class PostNoteResource extends JsonResource
{
/**
- * @return array{id: string, body: string, user_id: string, created_at: mixed, updated_at: mixed, user: array{id: string, name: string|null, photo_url: string|null}|null}
+ * @return array{id: string, body: string, user_id: string, created_at: mixed, updated_at: mixed, mentions: list<array{id: string, name: string}>, parts: list<array<string, string|null>>, reactions: list<array{emoji: string, count: int, users: list<array{id: string, name: string}>}>, user: array{id: string, name: string|null, photo_url: string|null}|null}
*/
public function toArray(Request $request): array
{
@@ -22,6 +25,9 @@ class PostNoteResource extends JsonResource
'id' => $this->id,
'body' => $this->body,
'user_id' => $this->user_id,
+ 'mentions' => $this->mentions->map(fn (User $user): array => ['id' => $user->id, 'name' => $user->name])->values()->all(),
+ 'parts' => PostNoteMentions::parts($this->body, $this->mentions),
+ 'reactions' => SummarizePostNoteReactions::execute($this->resource),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'user' => $this->user === null ? null : [
diff --git a/app/Jobs/SendNotification.php b/app/Jobs/SendNotification.php
index 0b912d642..7f88b9f9d 100644
--- a/app/Jobs/SendNotification.php
+++ b/app/Jobs/SendNotification.php
@@ -14,10 +14,16 @@ use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Mail\Mailable;
+use Illuminate\Queue\Attributes\DeleteWhenMissingModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
+/**
+ * Emails one member about something that happened. A job whose user or
+ * subject (a note deleted before its email went out) is gone is dropped.
+ */
+#[DeleteWhenMissingModels]
class SendNotification implements ShouldQueue
{
use Queueable {
diff --git a/app/Mail/PostNoteAdded.php b/app/Mail/PostNoteAdded.php
index 718bd7140..6ffa26eed 100644
--- a/app/Mail/PostNoteAdded.php
+++ b/app/Mail/PostNoteAdded.php
@@ -4,54 +4,13 @@ declare(strict_types=1);
namespace App\Mail;
-use App\Models\PostNote;
-use App\Models\User;
-use App\Support\Mail\PostExcerpt;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Mail\Mailable;
-use Illuminate\Mail\Mailables\Content;
-use Illuminate\Mail\Mailables\Envelope;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Str;
-
-class PostNoteAdded extends Mailable implements ShouldQueue
+/**
+ * A new note on a post the recipient takes part in.
+ */
+class PostNoteAdded extends PostNoteEmail
{
- use Queueable, SerializesModels;
-
- public function __construct(
- public PostNote $note,
- public User $author,
- ) {}
-
- public function envelope(): Envelope
- {
- return new Envelope(
- subject: __('mail.post_note_added.subject', ['author' => $this->author->name]),
- );
- }
-
- public function content(): Content
- {
- $post = $this->note->post;
-
- return new Content(
- view: 'mail.post-note-added',
- with: [
- 'title' => __('mail.post_note_added.title', ['author' => $this->author->name]),
- 'previewText' => Str::limit((string) $this->note->body, 100),
- 'authorName' => $this->author->name,
- 'workspaceName' => $post->workspace->name,
- 'noteBody' => (string) $this->note->body,
- 'postExcerpt' => PostExcerpt::from($post->content, 200),
- 'channel' => $post->loadMissing('socialAccount')->hasDestination() ? $post : null,
- 'url' => route('app.posts.edit', ['post' => $post, 'comment' => $this->note->id]),
- ],
- );
- }
-
- public function attachments(): array
+ protected function template(): string
{
- return [];
+ return 'post-note-added';
}
}
diff --git a/app/Mail/PostNoteEmail.php b/app/Mail/PostNoteEmail.php
new file mode 100644
index 000000000..15ed6739d
--- /dev/null
+++ b/app/Mail/PostNoteEmail.php
@@ -0,0 +1,78 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Mail;
+
+use App\Models\PostNote;
+use App\Models\User;
+use App\Support\Mail\PostExcerpt;
+use App\Support\PostNoteMentions;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Mail\Mailable;
+use Illuminate\Mail\Mailables\Content;
+use Illuminate\Mail\Mailables\Envelope;
+use Illuminate\Queue\Attributes\DeleteWhenMissingModels;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Support\Str;
+
+/**
+ * An email about a note: the note, its author and the post it is on. Each
+ * email names its Maizzle template, whose slug also names its `mail.*` block.
+ * It is dropped when the note was deleted before it went out.
+ */
+#[DeleteWhenMissingModels]
+abstract class PostNoteEmail extends Mailable implements ShouldQueue
+{
+ use Queueable, SerializesModels;
+
+ public function __construct(
+ public PostNote $note,
+ public User $author,
+ ) {}
+
+ public function envelope(): Envelope
+ {
+ return new Envelope(
+ subject: __("mail.{$this->copyKey()}.subject", ['author' => $this->author->name]),
+ );
+ }
+
+ public function content(): Content
+ {
+ $post = $this->note->post;
+ $noteBody = PostNoteMentions::toPlainText(
+ $this->note->body,
+ $this->note->mentions,
+ everyone: __("mail.{$this->copyKey()}.mention_everyone"),
+ unknown: __("mail.{$this->copyKey()}.mention_unknown"),
+ );
+
+ return new Content(
+ view: "mail.{$this->template()}",
+ with: [
+ 'title' => __("mail.{$this->copyKey()}.title", ['author' => $this->author->name]),
+ 'previewText' => Str::limit($noteBody, 100),
+ 'authorName' => $this->author->name,
+ 'workspaceName' => $post->workspace->name,
+ 'noteBody' => $noteBody,
+ 'postExcerpt' => PostExcerpt::from($post->content, 200),
+ 'channel' => $post->loadMissing('socialAccount')->hasDestination() ? $post : null,
+ 'url' => route('app.posts.edit', ['post' => $post, 'comment' => $this->note->id]),
+ ],
+ );
+ }
+
+ public function attachments(): array
+ {
+ return [];
+ }
+
+ abstract protected function template(): string;
+
+ private function copyKey(): string
+ {
+ return Str::replace('-', '_', $this->template());
+ }
+}
diff --git a/app/Mail/PostNoteMentioned.php b/app/Mail/PostNoteMentioned.php
new file mode 100644
index 000000000..ea2d532f9
--- /dev/null
+++ b/app/Mail/PostNoteMentioned.php
@@ -0,0 +1,16 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Mail;
+
+/**
+ * A note that mentions the recipient.
+ */
+class PostNoteMentioned extends PostNoteEmail
+{
+ protected function template(): string
+ {
+ return 'post-note-mentioned';
+ }
+}
diff --git a/app/Mcp/Servers/TryPostServer.php b/app/Mcp/Servers/TryPostServer.php
index 810f41f1a..18b0b0b98 100644
--- a/app/Mcp/Servers/TryPostServer.php
+++ b/app/Mcp/Servers/TryPostServer.php
@@ -30,6 +30,7 @@ use App\Mcp\Tools\Label\DeleteLabelTool;
use App\Mcp\Tools\Label\ListLabelsTool;
use App\Mcp\Tools\Label\UpdateLabelTool;
use App\Mcp\Tools\Platform\ListContentTypesTool;
+use App\Mcp\Tools\Post\AddPostNoteReactionTool;
use App\Mcp\Tools\Post\ApprovePostTool;
use App\Mcp\Tools\Post\AttachMediaFromUploadTool;
use App\Mcp\Tools\Post\AttachMediaFromUrlTool;
@@ -41,11 +42,13 @@ use App\Mcp\Tools\Post\DeletePostNoteTool;
use App\Mcp\Tools\Post\DeletePostTool;
use App\Mcp\Tools\Post\GetPostMetricsTool;
use App\Mcp\Tools\Post\GetPostTool;
+use App\Mcp\Tools\Post\ListPostNoteMentionablesTool;
use App\Mcp\Tools\Post\ListPostNotesTool;
use App\Mcp\Tools\Post\ListPostsTool;
use App\Mcp\Tools\Post\PreviewPostTool;
use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\RejectPostTool;
+use App\Mcp\Tools\Post\RemovePostNoteReactionTool;
use App\Mcp\Tools\Post\RequestMediaUploadTool;
use App\Mcp\Tools\Post\SetPostRecurrenceTool;
use App\Mcp\Tools\Post\UpdatePostNoteTool;
@@ -124,6 +127,9 @@ class TryPostServer extends Server
CreatePostNoteTool::class,
UpdatePostNoteTool::class,
DeletePostNoteTool::class,
+ ListPostNoteMentionablesTool::class,
+ AddPostNoteReactionTool::class,
+ RemovePostNoteReactionTool::class,
GetAnalyticsReportTool::class,
GetAnalyticsPublicationTool::class,
diff --git a/app/Mcp/Tools/Post/AddPostNoteReactionTool.php b/app/Mcp/Tools/Post/AddPostNoteReactionTool.php
new file mode 100644
index 000000000..c6a9e1b54
--- /dev/null
+++ b/app/Mcp/Tools/Post/AddPostNoteReactionTool.php
@@ -0,0 +1,73 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Mcp\Tools\Post;
+
+use App\Actions\PostNote\AddPostNoteReaction;
+use App\Http\Resources\Api\PostNoteResource;
+use App\Mcp\Concerns\AuthorizesMcpTool;
+use App\Mcp\Concerns\ResolvesPostNotes;
+use App\Models\Post;
+use App\Models\PostNote;
+use App\Models\Workspace;
+use App\Rules\SingleEmoji;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Tool;
+use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[IsReadOnly(false)]
+#[IsDestructive(false)]
+#[IsOpenWorld(false)]
+#[Description('React to a note on a post with one emoji, as the connected user. Any single emoji works, a skin tone, flag or keycap included. Reacting again with the same emoji changes nothing. Nobody is emailed; everyone with the post open sees the reaction at once. Take it back with remove-post-note-reaction-tool. Returns the note with its reactions [{emoji, count, users [{id, name}]}].')]
+class AddPostNoteReactionTool extends Tool
+{
+ use AuthorizesMcpTool, ResolvesPostNotes;
+
+ public function handle(Request $request): Response|ResponseFactory
+ {
+ $workspace = $this->currentWorkspace($request);
+
+ if (! $workspace instanceof Workspace) {
+ return $workspace;
+ }
+
+ $ids = $request->validate([
+ 'post_id' => ['required', 'uuid'],
+ 'note_id' => ['required', 'uuid'],
+ ]);
+
+ $post = $this->notesPost($request, $workspace, data_get($ids, 'post_id'));
+
+ if (! $post instanceof Post) {
+ return $post;
+ }
+
+ $note = $this->noteOfPost($post, data_get($ids, 'note_id'));
+
+ if (! $note instanceof PostNote) {
+ return $note;
+ }
+
+ $validated = $request->validate([
+ 'emoji' => ['required', 'string', new SingleEmoji],
+ ]);
+
+ return Response::structured((new PostNoteResource(AddPostNoteReaction::execute($post, $note, $request->user(), data_get($validated, 'emoji'))))->resolve());
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'post_id' => $schema->string()->required()->description('The UUID of the post.'),
+ 'note_id' => $schema->string()->required()->description('The UUID of the note, from list-post-notes-tool.'),
+ 'emoji' => $schema->string()->required()->description('The emoji to react with, exactly one (e.g. 👍, 👀, 🇧🇷).'),
+ ];
+ }
+}
diff --git a/app/Mcp/Tools/Post/CreatePostNoteTool.php b/app/Mcp/Tools/Post/CreatePostNoteTool.php
index e07d200dd..706f73850 100644
--- a/app/Mcp/Tools/Post/CreatePostNoteTool.php
+++ b/app/Mcp/Tools/Post/CreatePostNoteTool.php
@@ -23,7 +23,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly(false)]
#[IsDestructive(true)]
#[IsOpenWorld(false)]
-#[Description('Add a note (internal team comment) to a post. Notes are never published to the network. Every other workspace member is emailed about it; on a post pending approval, only the approvers and the member who asked are.')]
+#[Description('Add a note (an internal team comment, never published to the network) to a post, as the connected user. To mention a member, write @[user:id] with an id from list-post-note-mentionables-tool; to mention everyone who sees the post, write @[everyone]. A mention of someone who cannot see the post is removed. Emails: each mentioned member gets a mention email; the post\'s other participants (its author, the member who asked for approval and everyone who already wrote a note on it) get a new-note email; nobody else is emailed, and each member\'s notification settings apply. Everyone with the post open sees the note at once. On a post pending approval, only the approvers and the member who asked can see its notes. Returns the new note with mentions [{id, name}].')]
class CreatePostNoteTool extends Tool
{
use AuthorizesMcpTool, ResolvesPostNotes;
@@ -55,7 +55,7 @@ class CreatePostNoteTool extends Tool
{
return [
'post_id' => $schema->string()->required()->description('The UUID of the post.'),
- 'body' => $schema->string()->required()->description('The note text (max 2000 characters).'),
+ 'body' => $schema->string()->required()->description('The note text (max 2000 characters). Mention a teammate with @[user:id], or everyone with @[everyone].'),
];
}
}
diff --git a/app/Mcp/Tools/Post/DeletePostNoteTool.php b/app/Mcp/Tools/Post/DeletePostNoteTool.php
index ee4ab92fc..7afaaaf08 100644
--- a/app/Mcp/Tools/Post/DeletePostNoteTool.php
+++ b/app/Mcp/Tools/Post/DeletePostNoteTool.php
@@ -23,7 +23,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly(false)]
#[IsDestructive(true)]
#[IsOpenWorld(false)]
-#[Description('Delete a note from a post. Only the note author can delete it. This cannot be undone.')]
+#[Description('Delete a note from a post, with its reactions. Only the note\'s author can delete it. Nobody is emailed. This cannot be undone.')]
class DeletePostNoteTool extends Tool
{
use AuthorizesMcpTool, ResolvesPostNotes;
@@ -66,7 +66,7 @@ class DeletePostNoteTool extends Tool
{
return [
'post_id' => $schema->string()->required()->description('The UUID of the post.'),
- 'note_id' => $schema->string()->required()->description('The UUID of the note to delete.'),
+ 'note_id' => $schema->string()->required()->description('The UUID of the note to delete, from list-post-notes-tool.'),
];
}
}
diff --git a/app/Mcp/Tools/Post/ListPostNoteMentionablesTool.php b/app/Mcp/Tools/Post/ListPostNoteMentionablesTool.php
new file mode 100644
index 000000000..f27fc191d
--- /dev/null
+++ b/app/Mcp/Tools/Post/ListPostNoteMentionablesTool.php
@@ -0,0 +1,56 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Mcp\Tools\Post;
+
+use App\Actions\PostNote\ListPostNoteAudience;
+use App\Http\Resources\Api\PostNoteMentionableResource;
+use App\Mcp\Concerns\AuthorizesMcpTool;
+use App\Mcp\Concerns\ResolvesPostNotes;
+use App\Models\Post;
+use App\Models\Workspace;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Tool;
+use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[IsReadOnly(true)]
+#[IsDestructive(false)]
+#[IsOpenWorld(false)]
+#[Description('List the members who can see a post, the connected user included: the people a note on it can mention. Returns [{id, name, photo_url, timezone}], timezone being an IANA name (e.g. America/Sao_Paulo) to tell someone\'s local time. Mention one of them in a note body as @[user:id], or all of them as @[everyone]. On a post pending approval, only the approvers and the member who asked are listed.')]
+class ListPostNoteMentionablesTool extends Tool
+{
+ use AuthorizesMcpTool, ResolvesPostNotes;
+
+ public function handle(Request $request): Response|ResponseFactory
+ {
+ $workspace = $this->currentWorkspace($request);
+
+ if (! $workspace instanceof Workspace) {
+ return $workspace;
+ }
+
+ $post = $this->notesPost($request, $workspace, data_get($request->validate(['post_id' => ['required', 'uuid']]), 'post_id'));
+
+ if (! $post instanceof Post) {
+ return $post;
+ }
+
+ return Response::structured([
+ 'mentionables' => PostNoteMentionableResource::collection(ListPostNoteAudience::execute($post))->resolve(),
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'post_id' => $schema->string()->required()->description('The UUID of the post.'),
+ ];
+ }
+}
diff --git a/app/Mcp/Tools/Post/ListPostNotesTool.php b/app/Mcp/Tools/Post/ListPostNotesTool.php
index bbc311d19..b9b66c508 100644
--- a/app/Mcp/Tools/Post/ListPostNotesTool.php
+++ b/app/Mcp/Tools/Post/ListPostNotesTool.php
@@ -23,7 +23,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly(true)]
#[IsDestructive(false)]
#[IsOpenWorld(false)]
-#[Description('List the notes (internal team comments) on a post, newest first. Notes are never published to the network. Each note has its body and its author (id, name, photo_url). Paginated with the app page size: pass page; the response carries total, per_page, current_page and last_page.')]
+#[Description('List the notes (internal team comments, never published to the network) on a post, newest first. Use it to read the team\'s discussion before replying, or to get a note_id for update-post-note-tool, delete-post-note-tool and the reaction tools. Each note has id, body, author {id, name, photo_url}, mentions [{id, name}], reactions [{emoji, count, users [{id, name}]}], created_at and updated_at. In a body, @[user:id] mentions a member (their name is in mentions) and @[everyone] mentions everyone who sees the post; an id missing from mentions belongs to a user who no longer exists. Paginated with the app page size: pass page; the response carries total, per_page, current_page and last_page.')]
class ListPostNotesTool extends Tool
{
use AuthorizesMcpTool, ResolvesPostNotes;
diff --git a/app/Mcp/Tools/Post/RemovePostNoteReactionTool.php b/app/Mcp/Tools/Post/RemovePostNoteReactionTool.php
new file mode 100644
index 000000000..573741963
--- /dev/null
+++ b/app/Mcp/Tools/Post/RemovePostNoteReactionTool.php
@@ -0,0 +1,73 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Mcp\Tools\Post;
+
+use App\Actions\PostNote\RemovePostNoteReaction;
+use App\Http\Resources\Api\PostNoteResource;
+use App\Mcp\Concerns\AuthorizesMcpTool;
+use App\Mcp\Concerns\ResolvesPostNotes;
+use App\Models\Post;
+use App\Models\PostNote;
+use App\Models\Workspace;
+use App\Rules\SingleEmoji;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Tool;
+use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[IsReadOnly(false)]
+#[IsDestructive(true)]
+#[IsOpenWorld(false)]
+#[Description('Take back the connected user\'s reaction with that emoji on a note of a post. Only your own reaction is removed; when you had not reacted with that emoji, nothing changes. Returns the note with its reactions [{emoji, count, users [{id, name}]}].')]
+class RemovePostNoteReactionTool extends Tool
+{
+ use AuthorizesMcpTool, ResolvesPostNotes;
+
+ public function handle(Request $request): Response|ResponseFactory
+ {
+ $workspace = $this->currentWorkspace($request);
+
+ if (! $workspace instanceof Workspace) {
+ return $workspace;
+ }
+
+ $ids = $request->validate([
+ 'post_id' => ['required', 'uuid'],
+ 'note_id' => ['required', 'uuid'],
+ ]);
+
+ $post = $this->notesPost($request, $workspace, data_get($ids, 'post_id'));
+
+ if (! $post instanceof Post) {
+ return $post;
+ }
+
+ $note = $this->noteOfPost($post, data_get($ids, 'note_id'));
+
+ if (! $note instanceof PostNote) {
+ return $note;
+ }
+
+ $validated = $request->validate([
+ 'emoji' => ['required', 'string', new SingleEmoji],
+ ]);
+
+ return Response::structured((new PostNoteResource(RemovePostNoteReaction::execute($post, $note, $request->user(), data_get($validated, 'emoji'))))->resolve());
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'post_id' => $schema->string()->required()->description('The UUID of the post.'),
+ 'note_id' => $schema->string()->required()->description('The UUID of the note, from list-post-notes-tool.'),
+ 'emoji' => $schema->string()->required()->description('The emoji of your reaction to remove.'),
+ ];
+ }
+}
diff --git a/app/Mcp/Tools/Post/UpdatePostNoteTool.php b/app/Mcp/Tools/Post/UpdatePostNoteTool.php
index c3d56c625..28ea38146 100644
--- a/app/Mcp/Tools/Post/UpdatePostNoteTool.php
+++ b/app/Mcp/Tools/Post/UpdatePostNoteTool.php
@@ -24,7 +24,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly(false)]
#[IsDestructive(true)]
#[IsOpenWorld(false)]
-#[Description('Edit the text of a note on a post. Only the note author can edit it. No email is sent.')]
+#[Description('Edit the text of a note on a post. Only the note\'s author can edit it. Mentions work as in create-post-note-tool: @[user:id] for a member, @[everyone] for everyone who sees the post; a mention of someone who cannot see the post is removed. Only the people this edit adds as mentions are emailed, not those the note already mentioned. Everyone with the post open sees the change at once. Returns the updated note with mentions [{id, name}] and reactions.')]
class UpdatePostNoteTool extends Tool
{
use AuthorizesMcpTool, ResolvesPostNotes;
@@ -62,7 +62,7 @@ class UpdatePostNoteTool extends Tool
'body' => ['required', 'string', 'max:2000'],
]);
- return Response::structured((new PostNoteResource(UpdatePostNote::execute($post, $note, $validated)))->resolve());
+ return Response::structured((new PostNoteResource(UpdatePostNote::execute($post, $note, $request->user(), $validated)))->resolve());
}
public function schema(JsonSchema $schema): array
@@ -70,7 +70,7 @@ class UpdatePostNoteTool extends Tool
return [
'post_id' => $schema->string()->required()->description('The UUID of the post.'),
'note_id' => $schema->string()->required()->description('The UUID of the note, from list-post-notes-tool.'),
- 'body' => $schema->string()->required()->description('The new note text (max 2000 characters).'),
+ 'body' => $schema->string()->required()->description('The new note text (max 2000 characters). Mention a teammate with @[user:id], or everyone with @[everyone].'),
];
}
}
diff --git a/app/Models/PostNote.php b/app/Models/PostNote.php
index d718b4542..e0274e420 100644
--- a/app/Models/PostNote.php
+++ b/app/Models/PostNote.php
@@ -9,12 +9,17 @@ use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\BelongsToMany;
+use Illuminate\Database\Eloquent\Relations\HasMany;
class PostNote extends Model
{
/** @use HasFactory<PostNoteFactory> */
use HasFactory, HasUuids;
+ /** What a note is shown with: its author, its reactions and who it mentions. */
+ public const DISPLAY_RELATIONS = ['user.avatarMedia', 'reactions.user', 'mentions'];
+
protected $fillable = [
'post_id',
'user_id',
@@ -30,4 +35,15 @@ class PostNote extends Model
{
return $this->belongsTo(User::class);
}
+
+ public function reactions(): HasMany
+ {
+ return $this->hasMany(PostNoteReaction::class)->oldest()->orderBy('id');
+ }
+
+ /** The members the note mentions by id (`@[user:{id}]`), kept in step with its body. */
+ public function mentions(): BelongsToMany
+ {
+ return $this->belongsToMany(User::class, 'post_note_mentions');
+ }
}
diff --git a/app/Models/PostNoteReaction.php b/app/Models/PostNoteReaction.php
new file mode 100644
index 000000000..174b41ca2
--- /dev/null
+++ b/app/Models/PostNoteReaction.php
@@ -0,0 +1,36 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Models;
+
+use Database\Factories\PostNoteReactionFactory;
+use Illuminate\Database\Eloquent\Concerns\HasUuids;
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+
+/**
+ * An emoji a member reacted to a note with. One row per note, user and emoji.
+ */
+class PostNoteReaction extends Model
+{
+ /** @use HasFactory<PostNoteReactionFactory> */
+ use HasFactory, HasUuids;
+
+ protected $fillable = [
+ 'post_note_id',
+ 'user_id',
+ 'emoji',
+ ];
+
+ public function note(): BelongsTo
+ {
+ return $this->belongsTo(PostNote::class, 'post_note_id');
+ }
+
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+}
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index ca40bdd4b..95e2d3903 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -23,6 +23,7 @@ use App\Models\Offer;
use App\Models\Plan;
use App\Models\Post;
use App\Models\PostNote;
+use App\Models\PostNoteReaction;
use App\Models\PostTemplate;
use App\Models\Repurpose;
use App\Models\RepurposeItem;
@@ -145,6 +146,7 @@ class AppServiceProvider extends ServiceProvider
'rssFeedCollection' => RssFeedCollection::class,
'rssFeedItem' => RssFeedItem::class,
'postComment' => PostNote::class,
+ 'postNoteReaction' => PostNoteReaction::class,
'postTemplate' => PostTemplate::class,
'socialAccount' => SocialAccount::class,
'subscription' => Subscription::class,
diff --git a/app/Rules/SingleEmoji.php b/app/Rules/SingleEmoji.php
new file mode 100644
index 000000000..95d9d5489
--- /dev/null
+++ b/app/Rules/SingleEmoji.php
@@ -0,0 +1,34 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Rules;
+
+use Closure;
+use Illuminate\Contracts\Validation\ValidationRule;
+use Illuminate\Support\Str;
+
+/**
+ * Exactly one emoji: a single grapheme that is a pictograph (with its skin
+ * tone, variation selector or joined pictographs), a flag or a keycap. The
+ * longest emoji takes a few code points; the cap keeps a pictograph followed
+ * by stacked combining marks out of the column.
+ */
+class SingleEmoji implements ValidationRule
+{
+ private const MAX_CODE_POINTS = 16;
+
+ private const PATTERN = '/^(?:\p{Regional_Indicator}{2}|[0-9#*]\x{FE0F}?\x{20E3}|\p{Extended_Pictographic})/u';
+
+ public function validate(string $attribute, mixed $value, Closure $fail): void
+ {
+ $isEmoji = is_string($value)
+ && Str::length($value) <= self::MAX_CODE_POINTS
+ && grapheme_strlen($value) === 1
+ && Str::isMatch(self::PATTERN, $value);
+
+ if (! $isEmoji) {
+ $fail('notes.errors.invalid_emoji')->translate();
+ }
+ }
+}
diff --git a/app/Support/PostNoteMentions.php b/app/Support/PostNoteMentions.php
new file mode 100644
index 000000000..56f39afd9
--- /dev/null
+++ b/app/Support/PostNoteMentions.php
@@ -0,0 +1,107 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Support;
+
+use App\Models\User;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Str;
+
+/**
+ * Mentions inside a note body, by id only: a person is written `@[user:{uuid}]`
+ * and everyone who sees the post `@[everyone]`. Names are never stored in the
+ * body; they come from the note's `mentions`, and everyone is read in each
+ * reader's language. This is the one place that reads the markup: the app gets
+ * a note split into parts (`parts()`), and the note editor writes the markup
+ * back through TipTap (`components/tiptap/plugins/noteBody.ts`).
+ */
+final class PostNoteMentions
+{
+ private const UUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
+
+ /** A mention of a person (group 1 holds their uuid) or of everyone (no group 1). */
+ private const PATTERN = '/@\[(?:user:('.self::UUID.')|everyone)\]/u';
+
+ /** The same mentions, captured whole, to split a body around them. */
+ private const SPLIT = '/(@\[(?:user:'.self::UUID.'|everyone)\])/u';
+
+ private const EVERYONE = '@[everyone]';
+
+ /**
+ * The unique user ids mentioned in the body, in order of appearance.
+ *
+ * @return Collection<int, string>
+ */
+ public static function extract(?string $body): Collection
+ {
+ return Str::matchAll(self::PATTERN, (string) $body)
+ ->filter()
+ ->map(fn (string $id): string => Str::lower($id))
+ ->unique()
+ ->values();
+ }
+
+ /**
+ * Whether the body mentions everyone who sees the post.
+ */
+ public static function mentionsEveryone(?string $body): bool
+ {
+ return Str::contains((string) $body, self::EVERYONE);
+ }
+
+ /**
+ * The body without its mentions of anyone outside `$people` (the members who
+ * see the post), so a note never names someone it cannot reach.
+ *
+ * @param Collection<int, User> $people
+ */
+ public static function withoutMentionsOutside(string $body, Collection $people): string
+ {
+ return Str::replaceMatches(
+ self::PATTERN,
+ function (array $match) use ($people): string {
+ $id = data_get($match, 1);
+
+ return blank($id) || $people->contains('id', Str::lower($id)) ? data_get($match, 0) : '';
+ },
+ $body,
+ );
+ }
+
+ /**
+ * The body split into its text and its mentions, in order, each mention of
+ * a person named from `$people` (null when the person is gone), so the app
+ * shows and edits a note without reading the markup itself.
+ *
+ * @param Collection<int, User> $people
+ * @return list<array{type: 'text', text: string}|array{type: 'mention', id: string, name: string|null}|array{type: 'everyone'}>
+ */
+ public static function parts(string $body, Collection $people): array
+ {
+ return collect(preg_split(self::SPLIT, $body, flags: PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY))
+ ->map(fn (string $piece): array => match (true) {
+ $piece === self::EVERYONE => ['type' => 'everyone'],
+ filled($id = self::extract($piece)->first()) => ['type' => 'mention', 'id' => $id, 'name' => $people->firstWhere('id', $id)?->name],
+ default => ['type' => 'text', 'text' => $piece],
+ })
+ ->all();
+ }
+
+ /**
+ * The body as people read it: each mention becomes `@Name` from `$people`
+ * (`@{$unknown}` when the person is gone), and everyone `@{$everyone}`.
+ *
+ * @param Collection<int, User> $people
+ */
+ public static function toPlainText(?string $body, Collection $people, string $everyone, string $unknown): string
+ {
+ return collect(self::parts((string) $body, $people))
+ ->map(fn (array $part): string => match (data_get($part, 'type')) {
+ 'text' => data_get($part, 'text'),
+ 'everyone' => "@{$everyone}",
+ default => '@'.(data_get($part, 'name') ?? $unknown),
+ })
+ ->implode('');
+ }
+}
diff --git a/app/Support/RequestIds.php b/app/Support/RequestIds.php
index e0a31eaa1..2e20be509 100644
--- a/app/Support/RequestIds.php
+++ b/app/Support/RequestIds.php
@@ -9,6 +9,16 @@ use Illuminate\Support\Str;
final class RequestIds
{
+ /**
+ * The value when it is a uuid, else null: an id read from a link's query is
+ * ignored when malformed instead of failing the page (PostgreSQL refuses a
+ * non-uuid in a uuid column).
+ */
+ public static function uuid(mixed $value): ?string
+ {
+ return Str::isUuid($value) ? $value : null;
+ }
+
/**
* @param Collection<int, mixed> $values
* @return list<string>
diff --git a/database/factories/PostNoteReactionFactory.php b/database/factories/PostNoteReactionFactory.php
new file mode 100644
index 000000000..30e741415
--- /dev/null
+++ b/database/factories/PostNoteReactionFactory.php
@@ -0,0 +1,23 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Database\Factories;
+
+use App\Models\PostNote;
+use App\Models\PostNoteReaction;
+use App\Models\User;
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/** @extends Factory<PostNoteReaction> */
+class PostNoteReactionFactory extends Factory
+{
+ public function definition(): array
+ {
+ return [
+ 'post_note_id' => PostNote::factory(),
+ 'user_id' => User::factory(),
+ 'emoji' => '👍',
+ ];
+ }
+}
diff --git a/database/migrations/2026_11_12_134947_create_post_note_reactions_table.php b/database/migrations/2026_11_12_134947_create_post_note_reactions_table.php
new file mode 100644
index 000000000..9cae3be9d
--- /dev/null
+++ b/database/migrations/2026_11_12_134947_create_post_note_reactions_table.php
@@ -0,0 +1,32 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ public function up(): void
+ {
+ Schema::create('post_note_reactions', function (Blueprint $table): void {
+ $table->uuid('id')->primary();
+ $table->foreignUuid('post_note_id')->constrained()->cascadeOnDelete();
+ $table->foreignUuid('user_id')->constrained()->cascadeOnDelete();
+ $emoji = $table->string('emoji', 64);
+ $table->timestamps();
+
+ if (in_array(Schema::getConnection()->getDriverName(), ['mysql', 'mariadb'], true)) {
+ $emoji->collation('utf8mb4_bin');
+ }
+
+ $table->unique(['post_note_id', 'user_id', 'emoji']);
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::dropIfExists('post_note_reactions');
+ }
+};
diff --git a/database/migrations/2026_11_12_191143_create_post_note_mentions_table.php b/database/migrations/2026_11_12_191143_create_post_note_mentions_table.php
new file mode 100644
index 000000000..26e2f2cd0
--- /dev/null
+++ b/database/migrations/2026_11_12_191143_create_post_note_mentions_table.php
@@ -0,0 +1,25 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ public function up(): void
+ {
+ Schema::create('post_note_mentions', function (Blueprint $table): void {
+ $table->foreignUuid('post_note_id')->constrained()->cascadeOnDelete();
+ $table->foreignUuid('user_id')->constrained()->cascadeOnDelete();
+
+ $table->primary(['post_note_id', 'user_id']);
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::dropIfExists('post_note_mentions');
+ }
+};
diff --git a/lang/ar/mail.php b/lang/ar/mail.php
index dc6de63ea..45ee81735 100644
--- a/lang/ar/mail.php
+++ b/lang/ar/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'المنشور',
'post_without_text' => 'لا يحتوي هذا المنشور على نص بعد.',
'button' => 'عرض الملاحظة',
+ 'mention_everyone' => 'الجميع',
+ 'mention_unknown' => 'غير معروف',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => 'أشار إليك :author في ملاحظة',
+ 'title' => 'أشار إليك :author',
+ 'heading' => 'تمت الإشارة إليك في ملاحظة',
+ 'body' => 'أشار إليك :author في ملاحظة على منشور في مساحة العمل :workspace.',
+ 'post_title' => 'المنشور',
+ 'post_without_text' => 'لا يحتوي هذا المنشور على نص بعد.',
+ 'button' => 'عرض الملاحظة',
+ 'mention_everyone' => 'الجميع',
+ 'mention_unknown' => 'غير معروف',
],
'post_approval_requested' => [
'subject' => ':name طلب منك الموافقة على منشور',
diff --git a/lang/ar/notes.php b/lang/ar/notes.php
index 61f205a52..c19811c06 100644
--- a/lang/ar/notes.php
+++ b/lang/ar/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'إرسال',
'empty' => 'لا توجد ملاحظات بعد. فريقك فقط يراها.',
'actions' => 'إجراءات الملاحظة',
- 'load_more' => 'تحميل الملاحظات الأقدم',
+ 'react' => 'إضافة تفاعل',
+ 'no_mentionables' => 'لا يوجد عضو مطابق',
+ 'mention_unknown' => 'غير معروف',
+ 'mention_everyone' => [
+ 'word' => 'الجميع',
+ 'description' => 'كل من في هذا المنشور',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time بالتوقيت المحلي',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'اختر رمزًا تعبيريًا واحدًا.',
+ 'not_saved' => 'تعذّر حفظ ملاحظتك. حاول مرة أخرى.',
+ 'not_deleted' => 'تعذّر حذف الملاحظة. حاول مرة أخرى.',
+ 'not_reacted' => 'تعذّر تحديث التفاعل. حاول مرة أخرى.',
+ 'too_long' => 'يمكن أن تحتوي الملاحظة على :max حرف كحد أقصى.',
+ ],
];
diff --git a/lang/ar/settings.php b/lang/ar/settings.php
index 23c848fd4..9dd89e1cb 100644
--- a/lang/ar/settings.php
+++ b/lang/ar/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'تم فصل الحساب',
'account_disconnected_description' => 'استلم بريدًا إلكترونيًا عند فصل حساب اجتماعي',
'post_note_added' => 'ملاحظة جديدة على منشور',
- 'post_note_added_description' => 'تلقَّ بريدًا إلكترونيًا عندما يضيف أحد أعضاء الفريق ملاحظة إلى منشور',
+ 'post_note_added_description' => 'تلقَّ بريدًا إلكترونيًا عندما يشير إليك أحد أعضاء الفريق في ملاحظة أو يضيف ملاحظة إلى منشور أنشأته أو علّقت عليه',
'collaboration' => 'التعاون',
'collaboration_description' => 'تلقَّ رسائل حول طلبات الموافقة والمنشورات المقبولة أو المرفوضة',
'save_failed' => 'تعذّر حفظ تفضيلات الإشعارات. حاول مرة أخرى.',
diff --git a/lang/de/mail.php b/lang/de/mail.php
index ce0533421..54325a670 100644
--- a/lang/de/mail.php
+++ b/lang/de/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Beitrag',
'post_without_text' => 'Dieser Beitrag hat noch keinen Text.',
'button' => 'Notiz ansehen',
+ 'mention_everyone' => 'alle',
+ 'mention_unknown' => 'unbekannt',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author hat dich in einer Notiz erwähnt',
+ 'title' => ':author hat dich erwähnt',
+ 'heading' => 'Du wurdest in einer Notiz erwähnt',
+ 'body' => ':author hat dich in einer Notiz zu einem Beitrag im Workspace :workspace erwähnt.',
+ 'post_title' => 'Beitrag',
+ 'post_without_text' => 'Dieser Beitrag hat noch keinen Text.',
+ 'button' => 'Notiz ansehen',
+ 'mention_everyone' => 'alle',
+ 'mention_unknown' => 'unbekannt',
],
'post_approval_requested' => [
'subject' => ':name bittet dich um Freigabe eines Beitrags',
diff --git a/lang/de/notes.php b/lang/de/notes.php
index d456a0d01..f89c90840 100644
--- a/lang/de/notes.php
+++ b/lang/de/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Senden',
'empty' => 'Noch keine Notizen. Nur dein Team sieht sie.',
'actions' => 'Notizaktionen',
- 'load_more' => 'Ältere Notizen laden',
+ 'react' => 'Reaktion hinzufügen',
+ 'no_mentionables' => 'Kein Teammitglied gefunden',
+ 'mention_unknown' => 'unbekannt',
+ 'mention_everyone' => [
+ 'word' => 'alle',
+ 'description' => 'Alle bei diesem Beitrag',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time Ortszeit',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Wähle ein einzelnes Emoji.',
+ 'not_saved' => 'Deine Notiz konnte nicht gespeichert werden. Versuch es noch einmal.',
+ 'not_deleted' => 'Die Notiz konnte nicht gelöscht werden. Versuch es noch einmal.',
+ 'not_reacted' => 'Die Reaktion konnte nicht aktualisiert werden. Versuch es noch einmal.',
+ 'too_long' => 'Notizen können bis zu :max Zeichen haben.',
+ ],
];
diff --git a/lang/de/settings.php b/lang/de/settings.php
index dd542a013..755e39fcf 100644
--- a/lang/de/settings.php
+++ b/lang/de/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Konto getrennt',
'account_disconnected_description' => 'Erhalte eine E-Mail, wenn ein Social-Media-Konto getrennt wird',
'post_note_added' => 'Neue Notiz zu einem Beitrag',
- 'post_note_added_description' => 'Erhalte eine E-Mail, wenn ein Teammitglied eine Notiz zu einem Beitrag hinzufügt',
+ 'post_note_added_description' => 'Erhalte eine E-Mail, wenn dich ein Teammitglied in einer Notiz erwähnt oder eine Notiz zu einem Beitrag hinzufügt, den du erstellt oder kommentiert hast',
'collaboration' => 'Zusammenarbeit',
'collaboration_description' => 'Erhalte E-Mails zu Freigabeanfragen und freigegebenen oder abgelehnten Beiträgen',
'save_failed' => 'Die Benachrichtigungseinstellungen konnten nicht gespeichert werden. Bitte versuche es erneut.',
diff --git a/lang/el/mail.php b/lang/el/mail.php
index edc9fc7d3..30cbc4190 100644
--- a/lang/el/mail.php
+++ b/lang/el/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Δημοσίευση',
'post_without_text' => 'Αυτή η δημοσίευση δεν έχει ακόμη κείμενο.',
'button' => 'Προβολή σημείωσης',
+ 'mention_everyone' => 'όλοι',
+ 'mention_unknown' => 'άγνωστος',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => 'Ο/Η :author σας ανέφερε σε μια σημείωση',
+ 'title' => 'Ο/Η :author σας ανέφερε',
+ 'heading' => 'Σας ανέφεραν σε μια σημείωση',
+ 'body' => 'Ο/Η :author σας ανέφερε σε μια σημείωση δημοσίευσης στο workspace :workspace.',
+ 'post_title' => 'Δημοσίευση',
+ 'post_without_text' => 'Αυτή η δημοσίευση δεν έχει ακόμη κείμενο.',
+ 'button' => 'Προβολή σημείωσης',
+ 'mention_everyone' => 'όλοι',
+ 'mention_unknown' => 'άγνωστος',
],
'post_approval_requested' => [
'subject' => 'Ο/Η :name σας ζήτησε να εγκρίνετε μια ανάρτηση',
diff --git a/lang/el/notes.php b/lang/el/notes.php
index 5e848e1f3..29f693f02 100644
--- a/lang/el/notes.php
+++ b/lang/el/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Αποστολή',
'empty' => 'Δεν υπάρχουν σημειώσεις ακόμη. Τις βλέπει μόνο η ομάδα σου.',
'actions' => 'Ενέργειες σημείωσης',
- 'load_more' => 'Φόρτωση παλαιότερων σημειώσεων',
+ 'react' => 'Προσθήκη αντίδρασης',
+ 'no_mentionables' => 'Κανένα μέλος δεν ταιριάζει',
+ 'mention_unknown' => 'άγνωστος',
+ 'mention_everyone' => [
+ 'word' => 'όλοι',
+ 'description' => 'Όλοι σε αυτή τη δημοσίευση',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time τοπική ώρα',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Επιλέξτε ένα μόνο emoji.',
+ 'not_saved' => 'Δεν ήταν δυνατή η αποθήκευση της σημείωσης. Δοκιμάστε ξανά.',
+ 'not_deleted' => 'Δεν ήταν δυνατή η διαγραφή της σημείωσης. Δοκιμάστε ξανά.',
+ 'not_reacted' => 'Δεν ήταν δυνατή η ενημέρωση της αντίδρασης. Δοκιμάστε ξανά.',
+ 'too_long' => 'Μια σημείωση μπορεί να έχει έως :max χαρακτήρες.',
+ ],
];
diff --git a/lang/el/settings.php b/lang/el/settings.php
index 1b192c0da..fee51150d 100644
--- a/lang/el/settings.php
+++ b/lang/el/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Λογαριασμός αποσυνδέθηκε',
'account_disconnected_description' => 'Λάβετε email όταν ένας λογαριασμός κοινωνικού δικτύου αποσυνδεθεί',
'post_note_added' => 'Νέα σημείωση σε δημοσίευση',
- 'post_note_added_description' => 'Λάβετε email όταν ένα μέλος της ομάδας προσθέτει σημείωση σε μια δημοσίευση',
+ 'post_note_added_description' => 'Λάβετε email όταν ένα μέλος της ομάδας σας αναφέρει σε μια σημείωση ή προσθέτει σημείωση σε δημοσίευση που δημιουργήσατε ή σχολιάσατε',
'collaboration' => 'Συνεργασία',
'collaboration_description' => 'Λάβετε email για αιτήματα έγκρισης και για αναρτήσεις που εγκρίθηκαν ή απορρίφθηκαν',
'save_failed' => 'Δεν ήταν δυνατή η αποθήκευση των προτιμήσεων ειδοποιήσεων. Δοκιμάστε ξανά.',
diff --git a/lang/en/mail.php b/lang/en/mail.php
index d865ae819..495e1e1b9 100644
--- a/lang/en/mail.php
+++ b/lang/en/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Post',
'post_without_text' => 'This post has no text yet.',
'button' => 'View note',
+ 'mention_everyone' => 'all',
+ 'mention_unknown' => 'unknown',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author mentioned you in a note',
+ 'title' => ':author mentioned you',
+ 'heading' => 'You were mentioned in a note',
+ 'body' => ':author mentioned you in a note on a post in the :workspace workspace.',
+ 'post_title' => 'Post',
+ 'post_without_text' => 'This post has no text yet.',
+ 'button' => 'View note',
+ 'mention_everyone' => 'all',
+ 'mention_unknown' => 'unknown',
],
'post_approval_requested' => [
'subject' => ':name asked you to approve a post',
diff --git a/lang/en/notes.php b/lang/en/notes.php
index e96013da9..3ea88da4a 100644
--- a/lang/en/notes.php
+++ b/lang/en/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Send',
'empty' => 'No notes yet. Only your team sees them.',
'actions' => 'Note actions',
- 'load_more' => 'Load older notes',
+ 'react' => 'Add reaction',
+ 'no_mentionables' => 'No teammate matches',
+ 'mention_unknown' => 'unknown',
+ 'mention_everyone' => [
+ 'word' => 'all',
+ 'description' => 'Everyone on this post',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time local time',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Pick a single emoji.',
+ 'not_saved' => 'Couldn\'t save your note. Try again.',
+ 'not_deleted' => 'Couldn\'t delete the note. Try again.',
+ 'not_reacted' => 'Couldn\'t update the reaction. Try again.',
+ 'too_long' => 'Notes can have up to :max characters.',
+ ],
];
diff --git a/lang/en/settings.php b/lang/en/settings.php
index 9769c6d53..202d0d00f 100644
--- a/lang/en/settings.php
+++ b/lang/en/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Account disconnected',
'account_disconnected_description' => 'Receive an email when a social account is disconnected',
'post_note_added' => 'New note on a post',
- 'post_note_added_description' => 'Receive an email when a team member adds a note to a post',
+ 'post_note_added_description' => 'Receive an email when a teammate mentions you in a note, or adds one to a post you created or commented on',
'collaboration' => 'Collaboration',
'collaboration_description' => 'Get emails about approval requests and approved or rejected posts',
'save_failed' => 'Could not save your notification preferences. Please try again.',
diff --git a/lang/es/mail.php b/lang/es/mail.php
index 062c79c1a..444ea6ad6 100644
--- a/lang/es/mail.php
+++ b/lang/es/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Publicación',
'post_without_text' => 'Esta publicación aún no tiene texto.',
'button' => 'Ver nota',
+ 'mention_everyone' => 'todos',
+ 'mention_unknown' => 'desconocido',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author te mencionó en una nota',
+ 'title' => ':author te mencionó',
+ 'heading' => 'Te mencionaron en una nota',
+ 'body' => ':author te mencionó en una nota de una publicación en el workspace :workspace.',
+ 'post_title' => 'Publicación',
+ 'post_without_text' => 'Esta publicación aún no tiene texto.',
+ 'button' => 'Ver nota',
+ 'mention_everyone' => 'todos',
+ 'mention_unknown' => 'desconocido',
],
'post_approval_requested' => [
'subject' => ':name te pidió aprobar una publicación',
diff --git a/lang/es/notes.php b/lang/es/notes.php
index 30e58159b..30fa0bbd1 100644
--- a/lang/es/notes.php
+++ b/lang/es/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Enviar',
'empty' => 'Todavía no hay notas. Solo tu equipo las ve.',
'actions' => 'Acciones de la nota',
- 'load_more' => 'Cargar notas anteriores',
+ 'react' => 'Añadir reacción',
+ 'no_mentionables' => 'Nadie del equipo coincide',
+ 'mention_unknown' => 'desconocido',
+ 'mention_everyone' => [
+ 'word' => 'todos',
+ 'description' => 'Todos en esta publicación',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time hora local',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Elige un solo emoji.',
+ 'not_saved' => 'No se pudo guardar tu nota. Inténtalo de nuevo.',
+ 'not_deleted' => 'No se pudo eliminar la nota. Inténtalo de nuevo.',
+ 'not_reacted' => 'No se pudo actualizar la reacción. Inténtalo de nuevo.',
+ 'too_long' => 'Las notas pueden tener hasta :max caracteres.',
+ ],
];
diff --git a/lang/es/settings.php b/lang/es/settings.php
index 1ab8f0e08..23c3a4f5d 100644
--- a/lang/es/settings.php
+++ b/lang/es/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Cuenta desconectada',
'account_disconnected_description' => 'Recibir un correo cuando una cuenta social se desconecte',
'post_note_added' => 'Nueva nota en una publicación',
- 'post_note_added_description' => 'Recibir un correo cuando un miembro del equipo añada una nota a una publicación',
+ 'post_note_added_description' => 'Recibir un correo cuando alguien del equipo te mencione en una nota o añada una nota a una publicación que creaste o comentaste',
'collaboration' => 'Colaboración',
'collaboration_description' => 'Recibe correos sobre solicitudes de aprobación y publicaciones aprobadas o rechazadas',
'save_failed' => 'No se pudieron guardar las preferencias de notificaciones. Inténtalo de nuevo.',
diff --git a/lang/fr/mail.php b/lang/fr/mail.php
index 8292e8c6b..4ce01b403 100644
--- a/lang/fr/mail.php
+++ b/lang/fr/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Publication',
'post_without_text' => 'Cette publication n\'a pas encore de texte.',
'button' => 'Voir la note',
+ 'mention_everyone' => 'tous',
+ 'mention_unknown' => 'inconnu',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author vous a mentionné dans une note',
+ 'title' => ':author vous a mentionné',
+ 'heading' => 'Vous avez été mentionné dans une note',
+ 'body' => ':author vous a mentionné dans une note sur une publication de l\'espace de travail :workspace.',
+ 'post_title' => 'Publication',
+ 'post_without_text' => 'Cette publication n\'a pas encore de texte.',
+ 'button' => 'Voir la note',
+ 'mention_everyone' => 'tous',
+ 'mention_unknown' => 'inconnu',
],
'post_approval_requested' => [
'subject' => ':name vous demande d\'approuver une publication',
diff --git a/lang/fr/notes.php b/lang/fr/notes.php
index 4feac653a..8c377754e 100644
--- a/lang/fr/notes.php
+++ b/lang/fr/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Envoyer',
'empty' => 'Aucune note pour le moment. Seule votre équipe les voit.',
'actions' => 'Actions de la note',
- 'load_more' => 'Charger les notes plus anciennes',
+ 'react' => 'Ajouter une réaction',
+ 'no_mentionables' => 'Aucun membre ne correspond',
+ 'mention_unknown' => 'inconnu',
+ 'mention_everyone' => [
+ 'word' => 'tous',
+ 'description' => 'Tout le monde sur cette publication',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time heure locale',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Choisissez un seul emoji.',
+ 'not_saved' => 'Impossible d\'enregistrer votre note. Réessayez.',
+ 'not_deleted' => 'Impossible de supprimer la note. Réessayez.',
+ 'not_reacted' => 'Impossible de mettre à jour la réaction. Réessayez.',
+ 'too_long' => 'Une note peut contenir jusqu\'à :max caractères.',
+ ],
];
diff --git a/lang/fr/settings.php b/lang/fr/settings.php
index 077ed80cd..4be1c126b 100644
--- a/lang/fr/settings.php
+++ b/lang/fr/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Compte déconnecté',
'account_disconnected_description' => 'Recevez un e-mail lorsqu\'un compte social est déconnecté',
'post_note_added' => 'Nouvelle note sur une publication',
- 'post_note_added_description' => 'Recevoir un e-mail quand un membre de l\'équipe ajoute une note à une publication',
+ 'post_note_added_description' => 'Recevoir un e-mail quand un membre de l\'équipe vous mentionne dans une note ou ajoute une note à une publication que vous avez créée ou commentée',
'collaboration' => 'Collaboration',
'collaboration_description' => 'Recevez des e-mails sur les demandes d\'approbation et les publications approuvées ou refusées',
'save_failed' => 'Impossible d’enregistrer les préférences de notification. Veuillez réessayer.',
diff --git a/lang/it/mail.php b/lang/it/mail.php
index bd6bb95a4..ca42a53dc 100644
--- a/lang/it/mail.php
+++ b/lang/it/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Post',
'post_without_text' => 'Questo post non ha ancora testo.',
'button' => 'Vedi nota',
+ 'mention_everyone' => 'tutti',
+ 'mention_unknown' => 'sconosciuto',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author ti ha menzionato in una nota',
+ 'title' => ':author ti ha menzionato',
+ 'heading' => 'Sei stato menzionato in una nota',
+ 'body' => ':author ti ha menzionato in una nota su un post nel workspace :workspace.',
+ 'post_title' => 'Post',
+ 'post_without_text' => 'Questo post non ha ancora testo.',
+ 'button' => 'Vedi nota',
+ 'mention_everyone' => 'tutti',
+ 'mention_unknown' => 'sconosciuto',
],
'post_approval_requested' => [
'subject' => ':name ti ha chiesto di approvare un post',
diff --git a/lang/it/notes.php b/lang/it/notes.php
index d83f595a0..eeec39e08 100644
--- a/lang/it/notes.php
+++ b/lang/it/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Invia',
'empty' => 'Ancora nessuna nota. Le vede solo il tuo team.',
'actions' => 'Azioni della nota',
- 'load_more' => 'Carica note meno recenti',
+ 'react' => 'Aggiungi reazione',
+ 'no_mentionables' => 'Nessun membro corrisponde',
+ 'mention_unknown' => 'sconosciuto',
+ 'mention_everyone' => [
+ 'word' => 'tutti',
+ 'description' => 'Tutti su questo post',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time ora locale',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Scegli una sola emoji.',
+ 'not_saved' => 'Impossibile salvare la nota. Riprova.',
+ 'not_deleted' => 'Impossibile eliminare la nota. Riprova.',
+ 'not_reacted' => 'Impossibile aggiornare la reazione. Riprova.',
+ 'too_long' => 'Le note possono avere al massimo :max caratteri.',
+ ],
];
diff --git a/lang/it/settings.php b/lang/it/settings.php
index 5048b1605..839a6a7a2 100644
--- a/lang/it/settings.php
+++ b/lang/it/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Account scollegato',
'account_disconnected_description' => 'Ricevi un\'email quando un account social viene scollegato',
'post_note_added' => 'Nuova nota su un post',
- 'post_note_added_description' => 'Ricevi un\'email quando un membro del team aggiunge una nota a un post',
+ 'post_note_added_description' => 'Ricevi un\'email quando un membro del team ti menziona in una nota o aggiunge una nota a un post che hai creato o commentato',
'collaboration' => 'Collaborazione',
'collaboration_description' => 'Ricevi email sulle richieste di approvazione e sui post approvati o rifiutati',
'save_failed' => 'Impossibile salvare le preferenze di notifica. Riprova.',
diff --git a/lang/ja/mail.php b/lang/ja/mail.php
index 75db61425..eb8000516 100644
--- a/lang/ja/mail.php
+++ b/lang/ja/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => '投稿',
'post_without_text' => 'この投稿にはまだテキストがありません。',
'button' => 'メモを見る',
+ 'mention_everyone' => '全員',
+ 'mention_unknown' => '不明',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author さんがメモであなたをメンションしました',
+ 'title' => ':author さんがあなたをメンションしました',
+ 'heading' => 'メモであなたがメンションされました',
+ 'body' => ':author さんがワークスペース :workspace の投稿のメモであなたをメンションしました。',
+ 'post_title' => '投稿',
+ 'post_without_text' => 'この投稿にはまだテキストがありません。',
+ 'button' => 'メモを見る',
+ 'mention_everyone' => '全員',
+ 'mention_unknown' => '不明',
],
'post_approval_requested' => [
'subject' => ':nameさんが投稿の承認を依頼しました',
diff --git a/lang/ja/notes.php b/lang/ja/notes.php
index be8cefd32..31ac8f4a6 100644
--- a/lang/ja/notes.php
+++ b/lang/ja/notes.php
@@ -15,5 +15,21 @@ return [
'send' => '送信',
'empty' => 'まだメモがありません。チームメンバーだけが見られます。',
'actions' => 'メモの操作',
- 'load_more' => '過去のメモを読み込む',
+ 'react' => 'リアクションを追加',
+ 'no_mentionables' => '一致するメンバーがいません',
+ 'mention_unknown' => '不明',
+ 'mention_everyone' => [
+ 'word' => '全員',
+ 'description' => 'この投稿の全員',
+ ],
+ 'mention_card' => [
+ 'local_time' => '現地時間 :time',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => '絵文字を1つ選んでください。',
+ 'not_saved' => 'メモを保存できませんでした。もう一度お試しください。',
+ 'not_deleted' => 'メモを削除できませんでした。もう一度お試しください。',
+ 'not_reacted' => 'リアクションを更新できませんでした。もう一度お試しください。',
+ 'too_long' => 'メモは最大 :max 文字までです。',
+ ],
];
diff --git a/lang/ja/settings.php b/lang/ja/settings.php
index c821eeb74..a54876bd7 100644
--- a/lang/ja/settings.php
+++ b/lang/ja/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'アカウントの接続が解除されたとき',
'account_disconnected_description' => 'ソーシャルアカウントの接続が解除されたときにメールを受け取ります',
'post_note_added' => '投稿への新しいメモ',
- 'post_note_added_description' => 'チームメンバーが投稿にメモを追加したときにメールを受け取ります',
+ 'post_note_added_description' => 'チームメンバーがメモであなたをメンションしたとき、またはあなたが作成・メモした投稿にメモを追加したときにメールを受け取ります',
'collaboration' => 'コラボレーション',
'collaboration_description' => '承認リクエストや、承認・却下された投稿についてメールを受け取る',
'save_failed' => '通知設定を保存できませんでした。もう一度お試しください。',
diff --git a/lang/ko/mail.php b/lang/ko/mail.php
index f81f08f32..fed21e73a 100644
--- a/lang/ko/mail.php
+++ b/lang/ko/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => '게시물',
'post_without_text' => '이 게시물에는 아직 텍스트가 없습니다.',
'button' => '메모 보기',
+ 'mention_everyone' => '모두',
+ 'mention_unknown' => '알 수 없음',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author님이 메모에서 회원님을 언급했습니다',
+ 'title' => ':author님이 회원님을 언급했습니다',
+ 'heading' => '메모에서 언급되었습니다',
+ 'body' => ':author님이 :workspace 워크스페이스의 게시물 메모에서 회원님을 언급했습니다.',
+ 'post_title' => '게시물',
+ 'post_without_text' => '이 게시물에는 아직 텍스트가 없습니다.',
+ 'button' => '메모 보기',
+ 'mention_everyone' => '모두',
+ 'mention_unknown' => '알 수 없음',
],
'post_approval_requested' => [
'subject' => ':name님이 게시물 승인을 요청했습니다',
diff --git a/lang/ko/notes.php b/lang/ko/notes.php
index 8d2031a10..369cfee2c 100644
--- a/lang/ko/notes.php
+++ b/lang/ko/notes.php
@@ -15,5 +15,21 @@ return [
'send' => '보내기',
'empty' => '아직 메모가 없습니다. 팀원만 볼 수 있습니다.',
'actions' => '메모 작업',
- 'load_more' => '이전 메모 불러오기',
+ 'react' => '반응 추가',
+ 'no_mentionables' => '일치하는 팀원이 없습니다',
+ 'mention_unknown' => '알 수 없음',
+ 'mention_everyone' => [
+ 'word' => '모두',
+ 'description' => '이 게시물의 모든 사람',
+ ],
+ 'mention_card' => [
+ 'local_time' => '현지 시간 :time',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => '이모지를 하나만 선택하세요.',
+ 'not_saved' => '메모를 저장하지 못했습니다. 다시 시도하세요.',
+ 'not_deleted' => '메모를 삭제하지 못했습니다. 다시 시도하세요.',
+ 'not_reacted' => '반응을 업데이트하지 못했습니다. 다시 시도하세요.',
+ 'too_long' => '메모는 최대 :max자까지 입력할 수 있습니다.',
+ ],
];
diff --git a/lang/ko/settings.php b/lang/ko/settings.php
index c77fb7179..598a3cfb0 100644
--- a/lang/ko/settings.php
+++ b/lang/ko/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => '계정 연결 해제됨',
'account_disconnected_description' => '소셜 계정 연결이 해제되면 이메일을 받습니다',
'post_note_added' => '게시물의 새 메모',
- 'post_note_added_description' => '팀원이 게시물에 메모를 추가하면 이메일을 받습니다',
+ 'post_note_added_description' => '팀원이 메모에서 회원님을 언급하거나 회원님이 만들었거나 메모를 남긴 게시물에 메모를 추가하면 이메일을 받습니다',
'collaboration' => '협업',
'collaboration_description' => '승인 요청과 승인 또는 거절된 게시물에 대한 이메일 받기',
'save_failed' => '알림 설정을 저장하지 못했습니다. 다시 시도해 주세요.',
diff --git a/lang/nl/mail.php b/lang/nl/mail.php
index 9504da053..916f36b79 100644
--- a/lang/nl/mail.php
+++ b/lang/nl/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Bericht',
'post_without_text' => 'Dit bericht heeft nog geen tekst.',
'button' => 'Notitie bekijken',
+ 'mention_everyone' => 'iedereen',
+ 'mention_unknown' => 'onbekend',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author heeft je genoemd in een notitie',
+ 'title' => ':author heeft je genoemd',
+ 'heading' => 'Je bent genoemd in een notitie',
+ 'body' => ':author heeft je genoemd in een notitie bij een bericht in de workspace :workspace.',
+ 'post_title' => 'Bericht',
+ 'post_without_text' => 'Dit bericht heeft nog geen tekst.',
+ 'button' => 'Notitie bekijken',
+ 'mention_everyone' => 'iedereen',
+ 'mention_unknown' => 'onbekend',
],
'post_approval_requested' => [
'subject' => ':name vraagt je een bericht goed te keuren',
diff --git a/lang/nl/notes.php b/lang/nl/notes.php
index 5ff503b32..b0ac010ae 100644
--- a/lang/nl/notes.php
+++ b/lang/nl/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Verzenden',
'empty' => 'Nog geen notities. Alleen je team ziet ze.',
'actions' => 'Notitieacties',
- 'load_more' => 'Oudere notities laden',
+ 'react' => 'Reactie toevoegen',
+ 'no_mentionables' => 'Geen teamlid gevonden',
+ 'mention_unknown' => 'onbekend',
+ 'mention_everyone' => [
+ 'word' => 'iedereen',
+ 'description' => 'Iedereen bij dit bericht',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time lokale tijd',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Kies één emoji.',
+ 'not_saved' => 'Je notitie kon niet worden opgeslagen. Probeer het opnieuw.',
+ 'not_deleted' => 'De notitie kon niet worden verwijderd. Probeer het opnieuw.',
+ 'not_reacted' => 'De reactie kon niet worden bijgewerkt. Probeer het opnieuw.',
+ 'too_long' => 'Notities mogen maximaal :max tekens bevatten.',
+ ],
];
diff --git a/lang/nl/settings.php b/lang/nl/settings.php
index 9e41ad354..6379db35b 100644
--- a/lang/nl/settings.php
+++ b/lang/nl/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Account losgekoppeld',
'account_disconnected_description' => 'Ontvang een e-mail wanneer een social account wordt losgekoppeld',
'post_note_added' => 'Nieuwe notitie bij een bericht',
- 'post_note_added_description' => 'Ontvang een e-mail wanneer een teamlid een notitie aan een bericht toevoegt',
+ 'post_note_added_description' => 'Ontvang een e-mail wanneer een teamlid je noemt in een notitie of een notitie toevoegt aan een bericht dat je hebt gemaakt of becommentarieerd',
'collaboration' => 'Samenwerking',
'collaboration_description' => 'Ontvang e-mails over goedkeuringsverzoeken en goedgekeurde of afgewezen berichten',
'save_failed' => 'De meldingsvoorkeuren konden niet worden opgeslagen. Probeer het opnieuw.',
diff --git a/lang/pl/mail.php b/lang/pl/mail.php
index 8b9f963e9..2f82c7dac 100644
--- a/lang/pl/mail.php
+++ b/lang/pl/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Post',
'post_without_text' => 'Ten post nie ma jeszcze tekstu.',
'button' => 'Zobacz notatkę',
+ 'mention_everyone' => 'wszyscy',
+ 'mention_unknown' => 'nieznany',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author wspomniał(a) o Tobie w notatce',
+ 'title' => ':author wspomniał(a) o Tobie',
+ 'heading' => 'Wspomniano o Tobie w notatce',
+ 'body' => ':author wspomniał(a) o Tobie w notatce do posta w przestrzeni roboczej :workspace.',
+ 'post_title' => 'Post',
+ 'post_without_text' => 'Ten post nie ma jeszcze tekstu.',
+ 'button' => 'Zobacz notatkę',
+ 'mention_everyone' => 'wszyscy',
+ 'mention_unknown' => 'nieznany',
],
'post_approval_requested' => [
'subject' => ':name prosi o zatwierdzenie posta',
diff --git a/lang/pl/notes.php b/lang/pl/notes.php
index 75b36d35e..11424dac3 100644
--- a/lang/pl/notes.php
+++ b/lang/pl/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Wyślij',
'empty' => 'Brak notatek. Widzi je tylko Twój zespół.',
'actions' => 'Akcje notatki',
- 'load_more' => 'Wczytaj starsze notatki',
+ 'react' => 'Dodaj reakcję',
+ 'no_mentionables' => 'Brak pasujących członków zespołu',
+ 'mention_unknown' => 'nieznany',
+ 'mention_everyone' => [
+ 'word' => 'wszyscy',
+ 'description' => 'Wszyscy przy tym poście',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time czasu lokalnego',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Wybierz jedno emoji.',
+ 'not_saved' => 'Nie udało się zapisać notatki. Spróbuj ponownie.',
+ 'not_deleted' => 'Nie udało się usunąć notatki. Spróbuj ponownie.',
+ 'not_reacted' => 'Nie udało się zaktualizować reakcji. Spróbuj ponownie.',
+ 'too_long' => 'Notatka może mieć maksymalnie :max znaków.',
+ ],
];
diff --git a/lang/pl/settings.php b/lang/pl/settings.php
index 1264ca063..ab7d6de55 100644
--- a/lang/pl/settings.php
+++ b/lang/pl/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Konto rozłączone',
'account_disconnected_description' => 'Otrzymuj e-mail, gdy konto społecznościowe zostanie rozłączone',
'post_note_added' => 'Nowa notatka do posta',
- 'post_note_added_description' => 'Otrzymuj e-mail, gdy członek zespołu doda notatkę do posta',
+ 'post_note_added_description' => 'Otrzymuj e-mail, gdy członek zespołu wspomni o Tobie w notatce lub doda notatkę do posta, który utworzono lub skomentowano z Twojego konta',
'collaboration' => 'Współpraca',
'collaboration_description' => 'Otrzymuj e-maile o prośbach o zatwierdzenie oraz zatwierdzonych lub odrzuconych postach',
'save_failed' => 'Nie udało się zapisać preferencji powiadomień. Spróbuj ponownie.',
diff --git a/lang/pt-BR/mail.php b/lang/pt-BR/mail.php
index b02f9b783..a9108f2ce 100644
--- a/lang/pt-BR/mail.php
+++ b/lang/pt-BR/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Publicação',
'post_without_text' => 'Esta publicação ainda não tem texto.',
'button' => 'Ver nota',
+ 'mention_everyone' => 'todos',
+ 'mention_unknown' => 'desconhecido',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author mencionou você em uma nota',
+ 'title' => ':author mencionou você',
+ 'heading' => 'Você foi mencionado em uma nota',
+ 'body' => ':author mencionou você em uma nota de uma publicação na área de trabalho :workspace.',
+ 'post_title' => 'Publicação',
+ 'post_without_text' => 'Esta publicação ainda não tem texto.',
+ 'button' => 'Ver nota',
+ 'mention_everyone' => 'todos',
+ 'mention_unknown' => 'desconhecido',
],
'post_approval_requested' => [
'subject' => ':name pediu sua aprovação em um post',
diff --git a/lang/pt-BR/notes.php b/lang/pt-BR/notes.php
index 8c28a08de..003db8bac 100644
--- a/lang/pt-BR/notes.php
+++ b/lang/pt-BR/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Enviar',
'empty' => 'Nenhuma nota ainda. Só a sua equipe vê as notas.',
'actions' => 'Ações da nota',
- 'load_more' => 'Carregar notas antigas',
+ 'react' => 'Adicionar reação',
+ 'no_mentionables' => 'Ninguém da equipe encontrado',
+ 'mention_unknown' => 'desconhecido',
+ 'mention_everyone' => [
+ 'word' => 'todos',
+ 'description' => 'Todos nesta publicação',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time no horário local',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Escolha um único emoji.',
+ 'not_saved' => 'Não foi possível salvar sua nota. Tente de novo.',
+ 'not_deleted' => 'Não foi possível excluir a nota. Tente de novo.',
+ 'not_reacted' => 'Não foi possível atualizar a reação. Tente de novo.',
+ 'too_long' => 'Notas podem ter até :max caracteres.',
+ ],
];
diff --git a/lang/pt-BR/settings.php b/lang/pt-BR/settings.php
index b088035d8..4b2048d6a 100644
--- a/lang/pt-BR/settings.php
+++ b/lang/pt-BR/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Conta desconectada',
'account_disconnected_description' => 'Receber um e-mail quando uma conta social for desconectada',
'post_note_added' => 'Nova nota em uma publicação',
- 'post_note_added_description' => 'Receber um e-mail quando um membro da equipe adicionar uma nota a uma publicação',
+ 'post_note_added_description' => 'Receber um e-mail quando alguém da equipe mencionar você em uma nota ou adicionar uma nota a uma publicação que você criou ou comentou',
'collaboration' => 'Colaboração',
'collaboration_description' => 'Receba e-mails sobre pedidos de aprovação e posts aprovados ou rejeitados',
'save_failed' => 'Não foi possível salvar as preferências de notificações. Tente novamente.',
diff --git a/lang/ru/mail.php b/lang/ru/mail.php
index 7b7f5714a..47e65804c 100644
--- a/lang/ru/mail.php
+++ b/lang/ru/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Публикация',
'post_without_text' => 'В этой публикации пока нет текста.',
'button' => 'Открыть заметку',
+ 'mention_everyone' => 'все',
+ 'mention_unknown' => 'неизвестный',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author упомянул(а) вас в заметке',
+ 'title' => ':author упомянул(а) вас',
+ 'heading' => 'Вас упомянули в заметке',
+ 'body' => ':author упомянул(а) вас в заметке к публикации в рабочем пространстве :workspace.',
+ 'post_title' => 'Публикация',
+ 'post_without_text' => 'В этой публикации пока нет текста.',
+ 'button' => 'Открыть заметку',
+ 'mention_everyone' => 'все',
+ 'mention_unknown' => 'неизвестный',
],
'post_approval_requested' => [
'subject' => ':name просит одобрить публикацию',
diff --git a/lang/ru/notes.php b/lang/ru/notes.php
index 99a23500b..c853f1ddf 100644
--- a/lang/ru/notes.php
+++ b/lang/ru/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Отправить',
'empty' => 'Пока нет заметок. Их видит только ваша команда.',
'actions' => 'Действия с заметкой',
- 'load_more' => 'Загрузить старые заметки',
+ 'react' => 'Добавить реакцию',
+ 'no_mentionables' => 'Никто из команды не найден',
+ 'mention_unknown' => 'неизвестный',
+ 'mention_everyone' => [
+ 'word' => 'все',
+ 'description' => 'Все в этой публикации',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time по местному времени',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Выберите один эмодзи.',
+ 'not_saved' => 'Не удалось сохранить заметку. Попробуйте ещё раз.',
+ 'not_deleted' => 'Не удалось удалить заметку. Попробуйте ещё раз.',
+ 'not_reacted' => 'Не удалось обновить реакцию. Попробуйте ещё раз.',
+ 'too_long' => 'Заметка может содержать не более :max символов.',
+ ],
];
diff --git a/lang/ru/settings.php b/lang/ru/settings.php
index cb1b8f61a..bc95748d3 100644
--- a/lang/ru/settings.php
+++ b/lang/ru/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Аккаунт отключён',
'account_disconnected_description' => 'Получать письмо, когда социальный аккаунт отключается',
'post_note_added' => 'Новая заметка к публикации',
- 'post_note_added_description' => 'Получать письмо, когда участник команды добавляет заметку к публикации',
+ 'post_note_added_description' => 'Получать письмо, когда участник команды упоминает вас в заметке или добавляет заметку к публикации, которую вы создали или прокомментировали',
'collaboration' => 'Совместная работа',
'collaboration_description' => 'Получать письма о запросах на одобрение и об одобренных или отклонённых публикациях',
'save_failed' => 'Не удалось сохранить настройки уведомлений. Попробуйте ещё раз.',
diff --git a/lang/tr/mail.php b/lang/tr/mail.php
index 840cf93a9..63acb44da 100644
--- a/lang/tr/mail.php
+++ b/lang/tr/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Gönderi',
'post_without_text' => 'Bu gönderinin henüz metni yok.',
'button' => 'Notu görüntüle',
+ 'mention_everyone' => 'herkes',
+ 'mention_unknown' => 'bilinmeyen',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author bir notta senden bahsetti',
+ 'title' => ':author senden bahsetti',
+ 'heading' => 'Bir notta senden bahsedildi',
+ 'body' => ':author, :workspace çalışma alanındaki bir gönderinin notunda senden bahsetti.',
+ 'post_title' => 'Gönderi',
+ 'post_without_text' => 'Bu gönderinin henüz metni yok.',
+ 'button' => 'Notu görüntüle',
+ 'mention_everyone' => 'herkes',
+ 'mention_unknown' => 'bilinmeyen',
],
'post_approval_requested' => [
'subject' => ':name bir gönderi için onayınızı istedi',
diff --git a/lang/tr/notes.php b/lang/tr/notes.php
index 485e5755c..1e734a2e3 100644
--- a/lang/tr/notes.php
+++ b/lang/tr/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Gönder',
'empty' => 'Henüz not yok. Notları yalnızca ekibin görür.',
'actions' => 'Not işlemleri',
- 'load_more' => 'Daha eski notları yükle',
+ 'react' => 'Tepki ekle',
+ 'no_mentionables' => 'Eşleşen ekip üyesi yok',
+ 'mention_unknown' => 'bilinmeyen',
+ 'mention_everyone' => [
+ 'word' => 'herkes',
+ 'description' => 'Bu gönderideki herkes',
+ ],
+ 'mention_card' => [
+ 'local_time' => 'Yerel saat :time',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Tek bir emoji seç.',
+ 'not_saved' => 'Not kaydedilemedi. Tekrar dene.',
+ 'not_deleted' => 'Not silinemedi. Tekrar dene.',
+ 'not_reacted' => 'Tepki güncellenemedi. Tekrar dene.',
+ 'too_long' => 'Notlar en fazla :max karakter olabilir.',
+ ],
];
diff --git a/lang/tr/settings.php b/lang/tr/settings.php
index 909b75771..fe4961bb9 100644
--- a/lang/tr/settings.php
+++ b/lang/tr/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Hesap bağlantısı kesildi',
'account_disconnected_description' => 'Bir sosyal hesabın bağlantısı kesildiğinde bir e-posta alın',
'post_note_added' => 'Bir gönderide yeni not',
- 'post_note_added_description' => 'Bir ekip üyesi bir gönderiye not eklediğinde e-posta al',
+ 'post_note_added_description' => 'Bir ekip üyesi bir notta senden bahsettiğinde veya oluşturduğun ya da not yazdığın bir gönderiye not eklediğinde e-posta al',
'collaboration' => 'İş birliği',
'collaboration_description' => 'Onay istekleri ile onaylanan veya reddedilen gönderiler hakkında e-posta alın',
'save_failed' => 'Bildirim tercihleri kaydedilemedi. Lütfen tekrar deneyin.',
diff --git a/lang/uk/mail.php b/lang/uk/mail.php
index bea618b5e..e9f03062e 100644
--- a/lang/uk/mail.php
+++ b/lang/uk/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => 'Публікація',
'post_without_text' => 'У цій публікації ще немає тексту.',
'button' => 'Переглянути нотатку',
+ 'mention_everyone' => 'всі',
+ 'mention_unknown' => 'невідомий',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author згадав(ла) вас у нотатці',
+ 'title' => ':author згадав(ла) вас',
+ 'heading' => 'Вас згадали в нотатці',
+ 'body' => ':author згадав(ла) вас у нотатці до публікації в робочому просторі :workspace.',
+ 'post_title' => 'Публікація',
+ 'post_without_text' => 'У цій публікації ще немає тексту.',
+ 'button' => 'Переглянути нотатку',
+ 'mention_everyone' => 'всі',
+ 'mention_unknown' => 'невідомий',
],
'post_approval_requested' => [
'subject' => ':name просить схвалити публікацію',
diff --git a/lang/uk/notes.php b/lang/uk/notes.php
index fedb280ed..e8bc8ce4e 100644
--- a/lang/uk/notes.php
+++ b/lang/uk/notes.php
@@ -15,5 +15,21 @@ return [
'send' => 'Надіслати',
'empty' => 'Нотаток ще немає. Їх бачить лише ваша команда.',
'actions' => 'Дії з нотаткою',
- 'load_more' => 'Завантажити старіші нотатки',
+ 'react' => 'Додати реакцію',
+ 'no_mentionables' => 'Нікого з команди не знайдено',
+ 'mention_unknown' => 'невідомий',
+ 'mention_everyone' => [
+ 'word' => 'всі',
+ 'description' => 'Усі в цій публікації',
+ ],
+ 'mention_card' => [
+ 'local_time' => ':time за місцевим часом',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => 'Виберіть один емодзі.',
+ 'not_saved' => 'Не вдалося зберегти нотатку. Спробуйте ще раз.',
+ 'not_deleted' => 'Не вдалося видалити нотатку. Спробуйте ще раз.',
+ 'not_reacted' => 'Не вдалося оновити реакцію. Спробуйте ще раз.',
+ 'too_long' => 'Нотатка може містити не більше :max символів.',
+ ],
];
diff --git a/lang/uk/settings.php b/lang/uk/settings.php
index 38969a319..ff03d9fd5 100644
--- a/lang/uk/settings.php
+++ b/lang/uk/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => 'Акаунт від’єднано',
'account_disconnected_description' => 'Отримуйте email, коли соціальний акаунт від’єднано',
'post_note_added' => 'Нова нотатка до публікації',
- 'post_note_added_description' => 'Отримувати лист, коли учасник команди додає нотатку до публікації',
+ 'post_note_added_description' => 'Отримувати лист, коли учасник команди згадує вас у нотатці або додає нотатку до публікації, яку ви створили чи прокоментували',
'collaboration' => 'Співпраця',
'collaboration_description' => 'Отримувати листи про запити на схвалення та схвалені або відхилені публікації',
'save_failed' => 'Не вдалося зберегти налаштування сповіщень. Спробуйте ще раз.',
diff --git a/lang/zh/mail.php b/lang/zh/mail.php
index 53162b6de..97859bbd3 100644
--- a/lang/zh/mail.php
+++ b/lang/zh/mail.php
@@ -61,6 +61,19 @@ return [
'post_title' => '帖子',
'post_without_text' => '这篇帖子还没有文字。',
'button' => '查看备注',
+ 'mention_everyone' => '所有人',
+ 'mention_unknown' => '未知',
+ ],
+ 'post_note_mentioned' => [
+ 'subject' => ':author 在备注中提到了你',
+ 'title' => ':author 提到了你',
+ 'heading' => '有人在备注中提到了你',
+ 'body' => ':author 在工作区 :workspace 的一篇帖子备注中提到了你。',
+ 'post_title' => '帖子',
+ 'post_without_text' => '这篇帖子还没有文字。',
+ 'button' => '查看备注',
+ 'mention_everyone' => '所有人',
+ 'mention_unknown' => '未知',
],
'post_approval_requested' => [
'subject' => ':name 请你审批一条帖子',
diff --git a/lang/zh/notes.php b/lang/zh/notes.php
index 1746ee29c..8df8c8ea2 100644
--- a/lang/zh/notes.php
+++ b/lang/zh/notes.php
@@ -15,5 +15,21 @@ return [
'send' => '发送',
'empty' => '暂无备注。只有你的团队能看到。',
'actions' => '备注操作',
- 'load_more' => '加载更早的备注',
+ 'react' => '添加回应',
+ 'no_mentionables' => '没有匹配的成员',
+ 'mention_unknown' => '未知',
+ 'mention_everyone' => [
+ 'word' => '所有人',
+ 'description' => '此帖子的所有人',
+ ],
+ 'mention_card' => [
+ 'local_time' => '当地时间 :time',
+ ],
+ 'errors' => [
+ 'invalid_emoji' => '请选择一个表情符号。',
+ 'not_saved' => '无法保存备注。请重试。',
+ 'not_deleted' => '无法删除备注。请重试。',
+ 'not_reacted' => '无法更新回应。请重试。',
+ 'too_long' => '备注最多 :max 个字符。',
+ ],
];
diff --git a/lang/zh/settings.php b/lang/zh/settings.php
index 2ad7a5506..1323bf3a0 100644
--- a/lang/zh/settings.php
+++ b/lang/zh/settings.php
@@ -41,7 +41,7 @@ return [
'account_disconnected' => '账号已断开连接',
'account_disconnected_description' => '当某个社交账号断开连接时收到邮件',
'post_note_added' => '帖子有新备注',
- 'post_note_added_description' => '当团队成员为帖子添加备注时接收邮件',
+ 'post_note_added_description' => '当团队成员在备注中提到你,或为你创建或备注过的帖子添加备注时接收邮件',
'collaboration' => '协作',
'collaboration_description' => '接收关于审批请求以及已批准或已拒绝帖子的邮件',
'save_failed' => '无法保存通知偏好,请重试。',
diff --git a/maizzle/templates/post-note-mentioned.html b/maizzle/templates/post-note-mentioned.html
new file mode 100644
index 000000000..aed2f162c
--- /dev/null
+++ b/maizzle/templates/post-note-mentioned.html
@@ -0,0 +1,31 @@
+<x-main>
+ <x-message authenticated="true">
+ <x-heading>
+ @{{ __('mail.post_note_mentioned.heading') }}
+ </x-heading>
+
+ <p class="m-0 leading-6">
+ @{{ __('mail.post_note_mentioned.body', ['author' => $authorName, 'workspace' => $workspaceName]) }}
+ </p>
+
+ <div class="email-context">
+ <p class="m-0 leading-6 text-foreground" style="white-space: pre-line;">@{{ $noteBody }}</p>
+ </div>
+
+ <div class="email-context">
+ <p class="m-0 text-sm font-semibold text-foreground">
+ @{{ __('mail.post_note_mentioned.post_title') }}
+ </p>
+ <p class="m-0 mt-2 leading-6 text-sm" style="white-space: pre-line;">@{{ $postExcerpt !== '' ? $postExcerpt : __('mail.post_note_mentioned.post_without_text') }}</p>
+ @if($channel)
+ <x-channel-card />
+ @endif
+ </div>
+
+ <x-spacer height="24px" />
+
+ <x-button href="@{{ $url }}">
+ @{{ __('mail.post_note_mentioned.button') }}
+ </x-button>
+ </x-message>
+</x-main>
diff --git a/package-lock.json b/package-lock.json
index 86030c153..c35701038 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,6 +11,16 @@
"@tabler/icons-vue": "^3.50.0",
"@tailwindcss/typography": "^0.5.19",
"@thesvg/vue": "^4.0.0",
+ "@tiptap/core": "^3.32.2",
+ "@tiptap/extension-document": "^3.32.2",
+ "@tiptap/extension-hard-break": "^3.32.2",
+ "@tiptap/extension-mention": "^3.32.2",
+ "@tiptap/extension-paragraph": "^3.32.2",
+ "@tiptap/extension-text": "^3.32.2",
+ "@tiptap/extensions": "^3.32.2",
+ "@tiptap/pm": "^3.32.2",
+ "@tiptap/suggestion": "^3.32.2",
+ "@tiptap/vue-3": "^3.32.2",
"@unovis/ts": "^1.7.0",
"@unovis/vue": "^1.7.0",
"@vueuse/core": "^12.8.2",
@@ -1915,6 +1925,194 @@
"vue": ">=3.3"
}
},
+ "node_modules/@tiptap/core": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.32.2.tgz",
+ "integrity": "sha512-EitM8KY3agYfnp/bqhfxcaReVq4CUqVzMqoSIl7xSfYABTGYoTDtVXUdYSGutcCBFjc86BbXjrOlDlqkgC8BsQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@tiptap/pm": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/extension-bubble-menu": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.32.2.tgz",
+ "integrity": "sha512-mwxWtLHiwhtzXpvdjoegH10eIA8CJr5INGAzUSfzRp4v13zH3rDbsoafljwEi+V5JfcSY/bbXf1akOtsny4yXw==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@floating-ui/dom": "^1.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@tiptap/core": "3.32.2",
+ "@tiptap/pm": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/extension-document": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.32.2.tgz",
+ "integrity": "sha512-zKWj8jh1kpckfSwle+kqFn0ZnYvkhb7nz89nrNvpnnsQMbbGU2/+bUAfYU3XSEKZr3VBvW176FtlMPD8ggC3Cg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@tiptap/core": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/extension-floating-menu": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/extension-floating-menu/-/extension-floating-menu-3.32.2.tgz",
+ "integrity": "sha512-JPyJQvJlGDxn2v7Mr8Yft2BmcXaHiapVsXBMYiOJh5BeWbnwUYFWNH9h5PU/xTOz2zVEV79Kh4HmpgXZS3FCbg==",
+ "license": "MIT",
+ "optional": true,
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@floating-ui/dom": "^1.0.0",
+ "@tiptap/core": "3.32.2",
+ "@tiptap/pm": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/extension-hard-break": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/extension-hard-break/-/extension-hard-break-3.32.2.tgz",
+ "integrity": "sha512-oIdXmya2XBzp3Cw9Nr36agPvr9ZXP3p2fQXaFflxYYBKOG3UUzw38CId7J6K1jYxBf8c1zodbiKFEL7rttJ6fQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@tiptap/core": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/extension-mention": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/extension-mention/-/extension-mention-3.32.2.tgz",
+ "integrity": "sha512-q87HWG5iYV5jR8KxgU8shdXWjWgZmHIdnu0UkHE50NSRL88DZeiEt2ZU558P/R0JN85rVKf2z8i98MUR7lVTxQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@tiptap/core": "3.32.2",
+ "@tiptap/pm": "3.32.2",
+ "@tiptap/suggestion": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/extension-paragraph": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/extension-paragraph/-/extension-paragraph-3.32.2.tgz",
+ "integrity": "sha512-3bqC//4GEhUiux3dhW/TJuveBp9ADv4nHlqBdVQa3A+USGbaBvE9YvXxA32wZL0leSRykxEnHbNHZ1J4KjIynQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@tiptap/core": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/extension-text": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-3.32.2.tgz",
+ "integrity": "sha512-W6G7UbQ71TyvZvORDdj6u8By8B/Dymy8KoaKGaNHqB82SpM42ZK2TmeFBHI0Lo4wTkZJL3LuI+QthaDvh0USsA==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@tiptap/core": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/extensions": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/extensions/-/extensions-3.32.2.tgz",
+ "integrity": "sha512-TUE1JedPjYQ/T527f2a4xz+4Xi1a5nIgW8KwC0DjmqbaHirlz0eCNI2nMEN70pu5WPpqgXmki3lCF3LScQxIGw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@tiptap/core": "3.32.2",
+ "@tiptap/pm": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/pm": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.32.2.tgz",
+ "integrity": "sha512-4cuUbYf55NnYBIvDBK/K1VFVQ4pocKwAZC5TAy4s9dptvazxVHkQVMbiQsyhwfIbM4rxmHWkM/6omaFfTB++/g==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-changeset": "^2.4.4",
+ "prosemirror-commands": "^1.7.2",
+ "prosemirror-dropcursor": "^1.8.4",
+ "prosemirror-gapcursor": "^1.4.1",
+ "prosemirror-history": "^1.5.1",
+ "prosemirror-inputrules": "^1.5.1",
+ "prosemirror-keymap": "^1.2.3",
+ "prosemirror-model": "^1.25.12",
+ "prosemirror-schema-list": "^1.5.1",
+ "prosemirror-state": "^1.4.4",
+ "prosemirror-tables": "^1.8.5",
+ "prosemirror-transform": "^1.12.2",
+ "prosemirror-view": "^1.42.6"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ }
+ },
+ "node_modules/@tiptap/suggestion": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/suggestion/-/suggestion-3.32.2.tgz",
+ "integrity": "sha512-AD6WQ+mEFLok8svJv6Ibffyao+vXBGn3klQo4gCXH+UHwtgct5tF4goL9Rsz8J6zcDmYfx5W8AqYjBiQIyRNHA==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "peerDependencies": {
+ "@floating-ui/dom": "^1.0.0",
+ "@tiptap/core": "3.32.2",
+ "@tiptap/pm": "3.32.2"
+ }
+ },
+ "node_modules/@tiptap/vue-3": {
+ "version": "3.32.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/vue-3/-/vue-3-3.32.2.tgz",
+ "integrity": "sha512-d3v4FgfaCRO8Ku8K+ArXAjhqqMBAAWjh/tUqMLZaLYfTJIC3s5Y/6BCTun7Ds4e8I40Jf8cMqCx3xPLq7nsoEQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/ueberdosis"
+ },
+ "optionalDependencies": {
+ "@tiptap/extension-bubble-menu": "3.32.2",
+ "@tiptap/extension-floating-menu": "3.32.2"
+ },
+ "peerDependencies": {
+ "@floating-ui/dom": "^1.0.0",
+ "@tiptap/core": "3.32.2",
+ "@tiptap/pm": "3.32.2",
+ "vue": "^3.0.0"
+ }
+ },
"node_modules/@tybys/wasm-util": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
@@ -7042,6 +7240,12 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/orderedmap": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz",
+ "integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",
+ "license": "MIT"
+ },
"node_modules/own-keys": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz",
@@ -7465,6 +7669,145 @@
}
}
},
+ "node_modules/prosemirror-changeset": {
+ "version": "2.4.6",
+ "resolved": "https://registry.npmjs.org/prosemirror-changeset/-/prosemirror-changeset-2.4.6.tgz",
+ "integrity": "sha512-P0cY3DSLm4M2boUOCmHDyaID5o6HgWmb21Bvs9p8lLqfJjKBBEHG5Ma5qW5SCmwOYamtWOLf2k+yvt6077zlTg==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-transform": "^1.0.0"
+ }
+ },
+ "node_modules/prosemirror-commands": {
+ "version": "1.7.2",
+ "resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.2.tgz",
+ "integrity": "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.0.0",
+ "prosemirror-state": "^1.0.0",
+ "prosemirror-transform": "^1.10.2"
+ }
+ },
+ "node_modules/prosemirror-dropcursor": {
+ "version": "1.8.4",
+ "resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.4.tgz",
+ "integrity": "sha512-VmKxhcA6a+h5oPSYmfF1ZNeQqPbyYaIxqZsKqeYCyTlPtrjUgNaHL3P8vVaO19oqAV0zuaM/axkowZHrB1P3Tg==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-state": "^1.0.0",
+ "prosemirror-transform": "^1.1.0",
+ "prosemirror-view": "^1.1.0"
+ }
+ },
+ "node_modules/prosemirror-gapcursor": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.4.1.tgz",
+ "integrity": "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-keymap": "^1.0.0",
+ "prosemirror-model": "^1.0.0",
+ "prosemirror-state": "^1.0.0",
+ "prosemirror-view": "^1.0.0"
+ }
+ },
+ "node_modules/prosemirror-history": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.5.1.tgz",
+ "integrity": "sha512-onlwnqKvgtFg6srZOmDOAhlAy1FIHQpOExORybX0S+DvJepE5tPALrB9iGet/2sqqqrelSnB10OoiOJqAvu2DA==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-state": "^1.2.2",
+ "prosemirror-transform": "^1.0.0",
+ "prosemirror-view": "^1.31.0",
+ "rope-sequence": "^1.3.0"
+ }
+ },
+ "node_modules/prosemirror-inputrules": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz",
+ "integrity": "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-state": "^1.0.0",
+ "prosemirror-transform": "^1.0.0"
+ }
+ },
+ "node_modules/prosemirror-keymap": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz",
+ "integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-state": "^1.0.0",
+ "w3c-keyname": "^2.2.0"
+ }
+ },
+ "node_modules/prosemirror-model": {
+ "version": "1.25.13",
+ "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.13.tgz",
+ "integrity": "sha512-MlDMWGjYXaYOeCiO17jcybntCOzPnN+97U0809ke2QsgPtxW3n5/sD6ZKyJONUgMw1iP93ohZTjeKjnRJ7L6kQ==",
+ "license": "MIT",
+ "dependencies": {
+ "orderedmap": "^2.0.0"
+ }
+ },
+ "node_modules/prosemirror-schema-list": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.6.0.tgz",
+ "integrity": "sha512-G1srDtan+VqWn+qpmWFj/6j0YsZ5zMU+ZIlGVIW41a5JF2jAI3jzfMRWmSABmEH2Qoq1PmAG/o2mucMMdLOsLg==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.0.0",
+ "prosemirror-state": "^1.0.0",
+ "prosemirror-transform": "^1.7.3"
+ }
+ },
+ "node_modules/prosemirror-state": {
+ "version": "1.4.4",
+ "resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz",
+ "integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.0.0",
+ "prosemirror-transform": "^1.0.0",
+ "prosemirror-view": "^1.27.0"
+ }
+ },
+ "node_modules/prosemirror-tables": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/prosemirror-tables/-/prosemirror-tables-1.8.5.tgz",
+ "integrity": "sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-keymap": "^1.2.3",
+ "prosemirror-model": "^1.25.4",
+ "prosemirror-state": "^1.4.4",
+ "prosemirror-transform": "^1.10.5",
+ "prosemirror-view": "^1.41.4"
+ }
+ },
+ "node_modules/prosemirror-transform": {
+ "version": "1.12.5",
+ "resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.5.tgz",
+ "integrity": "sha512-3EBXZBM4h3MKuWvs9sQ7IA0/v6jCqCZ4wC08PIvzY1VSQWDL90KEyfg5C0Ex52UJesf/QVogxvuBsZdKmLc3NQ==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.21.0"
+ }
+ },
+ "node_modules/prosemirror-view": {
+ "version": "1.42.9",
+ "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.9.tgz",
+ "integrity": "sha512-bKbfzeKZOu2H2JQU2TaJmYu6EBcor3VnGIR4jR31cbEt1ztUnfUB6bKGV1+fJzOJdrVWR+tRU0208zM3oQx4wA==",
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.25.12",
+ "prosemirror-state": "^1.0.0",
+ "prosemirror-transform": "^1.1.0"
+ }
+ },
"node_modules/protobufjs": {
"version": "7.6.0",
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.0.tgz",
@@ -7779,6 +8122,12 @@
"integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
"license": "MIT"
},
+ "node_modules/rope-sequence": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz",
+ "integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==",
+ "license": "MIT"
+ },
"node_modules/run-parallel": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
@@ -9023,6 +9372,12 @@
"typescript": ">=5.0.0"
}
},
+ "node_modules/w3c-keyname": {
+ "version": "2.2.8",
+ "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
+ "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
+ "license": "MIT"
+ },
"node_modules/web-vitals": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-5.2.0.tgz",
diff --git a/package.json b/package.json
index fc896aa56..8d37b3171 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,16 @@
"@tabler/icons-vue": "^3.50.0",
"@tailwindcss/typography": "^0.5.19",
"@thesvg/vue": "^4.0.0",
+ "@tiptap/core": "^3.32.2",
+ "@tiptap/extension-document": "^3.32.2",
+ "@tiptap/extension-hard-break": "^3.32.2",
+ "@tiptap/extension-mention": "^3.32.2",
+ "@tiptap/extension-paragraph": "^3.32.2",
+ "@tiptap/extension-text": "^3.32.2",
+ "@tiptap/extensions": "^3.32.2",
+ "@tiptap/pm": "^3.32.2",
+ "@tiptap/suggestion": "^3.32.2",
+ "@tiptap/vue-3": "^3.32.2",
"@unovis/ts": "^1.7.0",
"@unovis/vue": "^1.7.0",
"@vueuse/core": "^12.8.2",
diff --git a/resources/changelog/2026-11-12-mentions-and-reactions-in-notes/cover.png b/resources/changelog/2026-11-12-mentions-and-reactions-in-notes/cover.png
new file mode 100644
index 000000000..ef56ee81f
Binary files /dev/null and b/resources/changelog/2026-11-12-mentions-and-reactions-in-notes/cover.png differ
diff --git a/resources/changelog/2026-11-12-mentions-and-reactions-in-notes/entry.md b/resources/changelog/2026-11-12-mentions-and-reactions-in-notes/entry.md
new file mode 100644
index 000000000..8be97237a
--- /dev/null
+++ b/resources/changelog/2026-11-12-mentions-and-reactions-in-notes/entry.md
@@ -0,0 +1,13 @@
+---
+title: Better notes for collaborating on posts
+date: 2026-11-12
+tags: [improved]
+---
+
+Talking a post through with your team is now easier, right where the post lives.
+
+- **Mentions:** type @ in a note to bring a teammate in, or @all for everyone.
+- **Reactions:** answer a note with any emoji.
+- **Live:** new notes and reactions show up for everyone the moment they're added.
+- **Get notified:** you get an email when someone mentions you or adds a note to a post you're part of.
+- **Works anywhere:** web, MCP and API.
diff --git a/resources/js/components/NoteBody.vue b/resources/js/components/NoteBody.vue
index 64e331877..a52ceac6b 100644
--- a/resources/js/components/NoteBody.vue
+++ b/resources/js/components/NoteBody.vue
@@ -1,13 +1,52 @@
<script setup lang="ts">
+import PostNoteMention from '@/components/posts/editor/PostNoteMention.vue';
+import { filled } from '@/lib/helpers';
+import type { PostNoteMentionable, PostNotePart } from '@/types/post-note';
+
+/**
+ * A note's text from its parts, with each mention as `@Name` and a card on
+ * hover. A mention of someone who is gone reads `@unknown` and has no card.
+ */
defineProps<{
- body: string;
+ parts: PostNotePart[];
+ people: PostNoteMentionable[] | null;
+}>();
+
+const emit = defineEmits<{
+ needPeople: [];
}>();
+
+const requestPeople = () => {
+ emit('needPeople');
+};
</script>
<template>
<p
class="mt-0.5 text-sm break-words whitespace-pre-wrap"
data-testid="note-body"
- v-text="body"
- />
+ >
+ <template v-for="(part, index) in parts" :key="index">
+ <span
+ v-if="part.type === 'everyone'"
+ class="rounded-sm bg-primary-subtle px-0.5 font-medium text-foreground"
+ data-testid="note-mention-everyone"
+ >@{{ $t('notes.mention_everyone.word') }}</span
+ >
+ <PostNoteMention
+ v-else-if="part.type === 'mention' && filled(part.name)"
+ :name="part.name"
+ :user-id="part.id"
+ :people="people"
+ @need-people="requestPeople"
+ />
+ <span
+ v-else-if="part.type === 'mention'"
+ class="rounded-sm bg-primary-subtle px-0.5 font-medium text-foreground"
+ data-testid="note-mention-unknown"
+ >@{{ $t('notes.mention_unknown') }}</span
+ >
+ <template v-else>{{ part.text }}</template>
+ </template>
+ </p>
</template>
diff --git a/resources/js/components/posts/editor/PostNoteEditor.vue b/resources/js/components/posts/editor/PostNoteEditor.vue
new file mode 100644
index 000000000..7f4e9f050
--- /dev/null
+++ b/resources/js/components/posts/editor/PostNoteEditor.vue
@@ -0,0 +1,358 @@
+<script setup lang="ts">
+import { IconUsers } from '@tabler/icons-vue';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import type { SuggestionProps } from '@tiptap/suggestion';
+import { EditorContent, useEditor } from '@tiptap/vue-3';
+import { wTrans } from 'laravel-vue-i18n';
+import { computed, ref, useAttrs, useId, watch } from 'vue';
+
+import { plainTextExtensions } from '@/components/tiptap/editor';
+import {
+ EVERYONE_ID,
+ NoteBody,
+ noteBodyOf,
+} from '@/components/tiptap/plugins/noteBody';
+import { NoteKeys } from '@/components/tiptap/plugins/noteKeys';
+import { Avatar } from '@/components/ui/avatar';
+import {
+ Popover,
+ PopoverAnchor,
+ PopoverContent,
+} from '@/components/ui/popover';
+import { blank, filled, isString } from '@/lib/helpers';
+import { filterBySearch } from '@/lib/search';
+import type { PostNoteMentionable, PostNotePart } from '@/types/post-note';
+
+/**
+ * The note editor: typing `@` lists everyone on the post (`@all` in the
+ * reader's language) and the teammates who can be mentioned; picking one
+ * inserts a mention chip that keeps the person's id. A note being edited opens
+ * from its `parts`; the model is the body to store, with mentions as markup
+ * (the `NoteBody` plugin). Enter submits and
+ * Shift+Enter breaks the line; Esc closes the list, then cancels. Attributes
+ * (class, test id, aria label) go to the editable element.
+ */
+defineOptions({ inheritAttrs: false });
+
+const MAX_LISTED = 8;
+
+const props = withDefaults(
+ defineProps<{
+ people: PostNoteMentionable[] | null;
+ currentUserId: string;
+ parts?: PostNotePart[];
+ placeholder?: string;
+ }>(),
+ {
+ parts: () => [],
+ placeholder: '',
+ },
+);
+
+const emit = defineEmits<{
+ submit: [];
+ cancel: [];
+ needPeople: [];
+}>();
+
+const body = defineModel<string>({ required: true });
+
+const attrs = useAttrs();
+
+/** A row of the `@` list: everyone on the post, or one teammate. */
+type Option = { id: string; label: string } & (
+ | { kind: 'everyone' }
+ | { kind: 'person'; person: PostNoteMentionable }
+);
+
+const everyoneWord = wTrans('notes.mention_everyone.word');
+const everyoneDescription = wTrans('notes.mention_everyone.description');
+const unknownWord = wTrans('notes.mention_unknown');
+
+/** The open `@` search: what was typed after it and how to insert a pick. */
+const search = ref<{
+ query: string;
+ insert: (mention: { id: string; label: string }) => void;
+} | null>(null);
+const highlighted = ref(0);
+
+/** Everyone first, then every teammate but the writer. */
+const options = computed((): Option[] => [
+ { kind: 'everyone', id: EVERYONE_ID, label: everyoneWord.value },
+ ...(props.people ?? [])
+ .filter((person) => person.id !== props.currentUserId)
+ .map(
+ (person): Option => ({
+ kind: 'person',
+ id: person.id,
+ label: person.name,
+ person,
+ }),
+ ),
+]);
+
+/** The options the typed query finds, searched in memory (the people load once). */
+const matches = computed(() =>
+ filterBySearch(options.value, search.value?.query, (option) =>
+ option.kind === 'everyone'
+ ? [option.label, everyoneDescription.value]
+ : [option.label],
+ ).slice(0, MAX_LISTED),
+);
+
+/** Open while a search is on and the people are loaded, until a search with a space finds nobody. */
+const listOpen = computed(
+ () =>
+ filled(search.value) &&
+ filled(props.people) &&
+ (filled(matches.value) || !search.value.query.includes(' ')),
+);
+
+const listId = useId();
+const optionId = (index: number) => `${listId}-${index}`;
+
+const pick = ({ id, label }: Option) => {
+ search.value?.insert({ id, label });
+};
+
+/**
+ * Where the cursor was when the list last saw it. The highlight follows the
+ * mouse only once it moves: a list opening under a still cursor gets mouse
+ * events too, and they must not take the highlight from the keyboard.
+ */
+let pointerAt: string | null = null;
+
+watch(listOpen, () => {
+ pointerAt = null;
+});
+
+const highlight = (event: MouseEvent, index: number) => {
+ const at = `${event.clientX},${event.clientY}`;
+ const moved = filled(pointerAt) && at !== pointerAt;
+
+ pointerAt = at;
+
+ if (moved) {
+ highlighted.value = index;
+ }
+};
+
+const moveHighlight = (step: number) => {
+ const count = matches.value.length;
+
+ highlighted.value = (highlighted.value + step + count) % count;
+};
+
+const openSearch = (suggestion: SuggestionProps) => {
+ if (props.people === null) {
+ emit('needPeople');
+ }
+
+ if (suggestion.query !== search.value?.query) {
+ highlighted.value = 0;
+ }
+
+ search.value = { query: suggestion.query, insert: suggestion.command };
+};
+
+const closeSearch = () => {
+ search.value = null;
+ highlighted.value = 0;
+};
+
+/** Arrows, Enter and Tab drive the open list; anything else types. */
+const onSearchKeydown = (event: KeyboardEvent): boolean => {
+ if (!listOpen.value || blank(matches.value)) {
+ return false;
+ }
+
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ moveHighlight(event.key === 'ArrowDown' ? 1 : -1);
+
+ return true;
+ }
+
+ if (event.key === 'Enter' || event.key === 'Tab') {
+ pick(matches.value[highlighted.value]);
+
+ return true;
+ }
+
+ return false;
+};
+
+const editor = useEditor({
+ extensions: [
+ ...plainTextExtensions(() => props.placeholder),
+ NoteBody.configure({
+ everyoneLabel: () => everyoneWord.value,
+ unknownLabel: () => unknownWord.value,
+ chipAttributes: {
+ class: 'rounded-sm bg-primary-subtle px-0.5 font-medium text-foreground',
+ 'data-testid': 'note-input-mention',
+ },
+ suggestion: {
+ allowSpaces: true,
+ items: () => [],
+ render: () => ({
+ onStart: openSearch,
+ onUpdate: openSearch,
+ onExit: closeSearch,
+ onKeyDown: ({ event }) => onSearchKeydown(event),
+ }),
+ },
+ }),
+ NoteKeys.configure({
+ onSubmit: () => emit('submit'),
+ onCancel: () => emit('cancel'),
+ submitBlocked: () => listOpen.value && filled(matches.value),
+ cancelBlocked: () => filled(search.value),
+ }),
+ ],
+ editorProps: {
+ attributes: () => ({
+ ...Object.fromEntries(
+ Object.entries(attrs).filter(([, value]) => isString(value)),
+ ),
+ class: [
+ 'whitespace-pre-wrap break-words outline-none',
+ '[&_p.is-editor-empty:first-child]:before:pointer-events-none [&_p.is-editor-empty:first-child]:before:float-left [&_p.is-editor-empty:first-child]:before:h-0 [&_p.is-editor-empty:first-child]:before:text-muted-foreground [&_p.is-editor-empty:first-child]:before:content-[attr(data-placeholder)]',
+ String(attrs.class ?? ''),
+ ].join(' '),
+ role: 'combobox',
+ 'aria-multiline': 'true',
+ 'aria-autocomplete': 'list',
+ 'aria-expanded': String(listOpen.value),
+ ...(listOpen.value && filled(matches.value)
+ ? {
+ 'aria-controls': listId,
+ 'aria-activedescendant': optionId(highlighted.value),
+ }
+ : {}),
+ }),
+ },
+ onCreate: ({ editor: created }) => {
+ created.commands.setNoteParts(props.parts);
+ },
+ onUpdate: ({ editor: current }) => {
+ body.value = noteBodyOf(current);
+ },
+});
+
+/** The editable element's combobox attributes follow the list, which is not part of the document. */
+watch([listOpen, highlighted, matches], () => {
+ editor.value?.view.setProps({});
+});
+
+/** The parent emptied the body (after sending). */
+watch(body, (stored) => {
+ const current = editor.value;
+
+ if (current && blank(stored) && filled(noteBodyOf(current))) {
+ current.commands.clearContent();
+ }
+});
+
+const focus = () => {
+ editor.value?.commands.focus('end');
+};
+
+/** What the field held when it was sent, and where that text ends. */
+let sent: { doc: ProseMirrorNode; end: number } | null = null;
+
+const markSent = () => {
+ const doc = editor.value?.state.doc;
+
+ sent = doc ? { doc, end: doc.content.size - 1 } : null;
+};
+
+/**
+ * Removes the sent text from the start of the field once it lands, keeping
+ * what was typed while it was sending. A field changed inside the sent text
+ * stays as it is, so nothing typed is lost.
+ */
+const dropSent = () => {
+ const current = editor.value;
+ const snapshot = sent;
+
+ sent = null;
+
+ if (!current || !snapshot) {
+ return;
+ }
+
+ const { doc } = current.state;
+ const unchanged =
+ snapshot.end <= doc.content.size - 1 &&
+ doc.slice(0, snapshot.end).eq(snapshot.doc.slice(0, snapshot.end));
+
+ if (unchanged) {
+ current.commands.deleteRange({ from: 1, to: snapshot.end });
+ }
+};
+
+defineExpose({ focus, markSent, dropSent });
+</script>
+
+<template>
+ <Popover :open="listOpen">
+ <PopoverAnchor as-child>
+ <EditorContent :editor="editor" class="min-w-0 flex-1" />
+ </PopoverAnchor>
+ <PopoverContent
+ side="top"
+ align="start"
+ class="w-max max-w-[calc(100vw-2rem)] min-w-64 p-1"
+ data-testid="note-mention-list"
+ @open-auto-focus.prevent
+ @close-auto-focus.prevent
+ >
+ <p
+ v-if="blank(matches)"
+ class="px-2 py-1.5 text-sm text-muted-foreground"
+ >
+ {{ $t('notes.no_mentionables') }}
+ </p>
+ <ul v-else :id="listId" role="listbox" class="flex flex-col">
+ <li
+ v-for="(option, index) in matches"
+ :id="optionId(index)"
+ :key="option.id"
+ role="option"
+ :aria-selected="index === highlighted"
+ class="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm"
+ :class="{ 'bg-accent': index === highlighted }"
+ :data-testid="
+ option.kind === 'everyone'
+ ? 'note-mention-option-everyone'
+ : 'note-mention-option'
+ "
+ @mousedown.prevent="pick(option)"
+ @mousemove="highlight($event, index)"
+ >
+ <template v-if="option.kind === 'everyone'">
+ <span
+ class="grid size-5 shrink-0 place-items-center rounded-full bg-primary-strong text-primary-strong-foreground"
+ >
+ <IconUsers class="size-3" />
+ </span>
+ <span class="font-medium whitespace-nowrap"
+ >@{{ option.label }}</span
+ >
+ <span class="whitespace-nowrap text-muted-foreground">{{
+ $t('notes.mention_everyone.description')
+ }}</span>
+ </template>
+ <template v-else>
+ <Avatar
+ :src="option.person.photo_url"
+ :name="option.label"
+ class="size-5 shrink-0 text-[10px]"
+ />
+ <span class="truncate">{{ option.label }}</span>
+ </template>
+ </li>
+ </ul>
+ </PopoverContent>
+ </Popover>
+</template>
diff --git a/resources/js/components/posts/editor/PostNoteItem.vue b/resources/js/components/posts/editor/PostNoteItem.vue
index ed8612aef..7b76e67b2 100644
--- a/resources/js/components/posts/editor/PostNoteItem.vue
+++ b/resources/js/components/posts/editor/PostNoteItem.vue
@@ -3,6 +3,8 @@ import { IconDots, IconPencil, IconTrash } from '@tabler/icons-vue';
import { computed, nextTick, ref } from 'vue';
import NoteBody from '@/components/NoteBody.vue';
+import PostNoteEditor from '@/components/posts/editor/PostNoteEditor.vue';
+import PostNoteReactions from '@/components/posts/editor/PostNoteReactions.vue';
import { Avatar } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import {
@@ -14,12 +16,15 @@ import {
} from '@/components/ui/dropdown-menu';
import { useViewTimezone } from '@/composables/useViewTimezone';
import date from '@/date';
-import type { PostNote } from '@/types/post-note';
+import { blank } from '@/lib/helpers';
+import { afterPaint } from '@/lib/utils';
+import type { PostNote, PostNoteMentionable } from '@/types/post-note';
const props = withDefaults(
defineProps<{
note: PostNote;
currentUserId: string;
+ mentionables: PostNoteMentionable[] | null;
highlighted?: boolean;
}>(),
{
@@ -28,15 +33,19 @@ const props = withDefaults(
);
const emit = defineEmits<{
- save: [body: string];
+ save: [body: string, done: (saved: boolean) => void];
delete: [];
+ react: [emoji: string, reacted: boolean];
+ needPeople: [];
}>();
const viewTimezone = useViewTimezone();
const editing = ref(false);
+const saving = ref(false);
const editBody = ref('');
-const editInput = ref<HTMLTextAreaElement | null>(null);
+const editInput = ref<InstanceType<typeof PostNoteEditor> | null>(null);
+const editContainer = ref<HTMLDivElement | null>(null);
const isOwn = computed(() => props.note.user_id === props.currentUserId);
const wasEdited = computed(
@@ -48,7 +57,8 @@ const startEdit = async () => {
editing.value = true;
await nextTick();
editInput.value?.focus();
- editInput.value?.parentElement?.scrollIntoView({ block: 'nearest' });
+ await afterPaint();
+ editContainer.value?.scrollIntoView({ block: 'nearest' });
};
const cancelEdit = () => {
@@ -56,29 +66,30 @@ const cancelEdit = () => {
editBody.value = '';
};
+/** Keeps the editor open, with the text, until the server takes the edit. */
const saveEdit = () => {
const body = editBody.value.trim();
- if (!body) {
+ if (blank(body) || saving.value) {
return;
}
- emit('save', body);
- cancelEdit();
-};
+ saving.value = true;
+ emit('save', body, (saved) => {
+ saving.value = false;
-const handleEditKeydown = (event: KeyboardEvent) => {
- if (event.key === 'Escape') {
- event.stopPropagation();
- cancelEdit();
+ if (saved) {
+ cancelEdit();
+ }
+ });
+};
- return;
- }
+const react = (emoji: string, reacted: boolean) => {
+ emit('react', emoji, reacted);
+};
- if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
- event.preventDefault();
- saveEdit();
- }
+const requestPeople = () => {
+ emit('needPeople');
};
</script>
@@ -87,6 +98,7 @@ const handleEditKeydown = (event: KeyboardEvent) => {
:data-note-id="note.id"
class="group/note relative -mx-2 flex gap-3 rounded-lg px-2 py-1 transition-colors"
:class="{ 'bg-primary-subtle': highlighted }"
+ :data-highlighted="highlighted"
data-testid="note-item"
>
<Avatar
@@ -155,14 +167,23 @@ const handleEditKeydown = (event: KeyboardEvent) => {
</div>
</div>
- <div v-if="editing" class="mt-1 flex flex-col gap-2">
- <textarea
+ <div
+ v-if="editing"
+ ref="editContainer"
+ class="mt-1 flex flex-col gap-2"
+ >
+ <PostNoteEditor
ref="editInput"
v-model="editBody"
- rows="1"
- class="field-sizing-content max-h-28 min-h-0 w-full resize-none rounded-lg border border-input bg-card px-2.5 py-1.5 text-sm text-foreground outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
+ :people="mentionables"
+ :current-user-id="currentUserId"
+ :parts="note.parts"
+ :aria-label="$t('notes.edit')"
+ class="max-h-28 min-h-0 w-full overflow-y-auto rounded-lg border border-input bg-card px-2.5 py-1.5 text-sm text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
data-testid="note-edit-input"
- @keydown="handleEditKeydown"
+ @submit="saveEdit"
+ @cancel="cancelEdit"
+ @need-people="requestPeople"
/>
<div class="flex items-center justify-end gap-1.5">
<Button
@@ -176,7 +197,8 @@ const handleEditKeydown = (event: KeyboardEvent) => {
<Button
type="button"
size="sm"
- :disabled="!editBody.trim()"
+ :disabled="blank(editBody)"
+ :loading="saving"
data-testid="note-edit-save"
@click="saveEdit"
>
@@ -185,11 +207,19 @@ const handleEditKeydown = (event: KeyboardEvent) => {
</div>
</div>
- <NoteBody
- v-else
- :body="note.body"
- class="mt-0.5 leading-relaxed text-foreground"
- />
+ <template v-else>
+ <NoteBody
+ :parts="note.parts"
+ :people="mentionables"
+ class="mt-0.5 leading-relaxed text-foreground"
+ @need-people="requestPeople"
+ />
+ <PostNoteReactions
+ :reactions="note.reactions"
+ :current-user-id="currentUserId"
+ @toggle="react"
+ />
+ </template>
</div>
</div>
</template>
diff --git a/resources/js/components/posts/editor/PostNoteMention.vue b/resources/js/components/posts/editor/PostNoteMention.vue
new file mode 100644
index 000000000..f5c324805
--- /dev/null
+++ b/resources/js/components/posts/editor/PostNoteMention.vue
@@ -0,0 +1,102 @@
+<script setup lang="ts">
+import { IconClock } from '@tabler/icons-vue';
+import { computed, ref } from 'vue';
+
+import { Avatar } from '@/components/ui/avatar';
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from '@/components/ui/hover-card';
+import date from '@/date';
+import dayjs from '@/dayjs';
+import { filled, transform } from '@/lib/helpers';
+import type { PostNoteMentionable } from '@/types/post-note';
+
+/**
+ * A mention in a note, as `@Name`. Hovering or focusing it shows who it is:
+ * photo, name and their local time. The people
+ * load the first time a card opens; someone no longer on the post shows by
+ * name only.
+ */
+const props = defineProps<{
+ name: string;
+ userId: string;
+ people: PostNoteMentionable[] | null;
+}>();
+
+const emit = defineEmits<{
+ needPeople: [];
+}>();
+
+const openedAt = ref(dayjs.utc());
+
+const person = computed(() =>
+ props.people?.find((candidate) => candidate.id === props.userId),
+);
+
+const localTime = computed(() =>
+ transform(person.value, (mentioned) =>
+ date.formatTimeInTimezone(openedAt.value.format(), mentioned.timezone),
+ ),
+);
+
+const onOpenChange = (open: boolean) => {
+ if (!open) {
+ return;
+ }
+
+ openedAt.value = dayjs.utc();
+
+ if (props.people === null) {
+ emit('needPeople');
+ }
+};
+</script>
+
+<template>
+ <HoverCard :open-delay="300" :close-delay="100" @update:open="onOpenChange">
+ <HoverCardTrigger as-child>
+ <span
+ tabindex="0"
+ class="rounded-sm bg-primary-subtle px-0.5 font-medium text-foreground outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
+ data-testid="note-mention"
+ >@{{ name }}</span
+ >
+ </HoverCardTrigger>
+ <HoverCardContent
+ side="top"
+ align="start"
+ class="w-auto max-w-72 min-w-56 rounded-xl border-0 p-3 shadow-md dark:border dark:border-border"
+ data-testid="note-mention-card"
+ >
+ <div class="flex min-w-0 items-center gap-3">
+ <Avatar
+ :src="person?.photo_url"
+ :name="person?.name ?? name"
+ class="size-10 shrink-0 rounded-lg"
+ fallback-class="bg-primary-subtle text-sm font-bold text-primary-text"
+ />
+ <div class="grid min-w-0">
+ <span
+ class="truncate text-sm leading-5 font-semibold text-foreground"
+ data-testid="note-mention-card-name"
+ >{{ person?.name ?? name }}</span
+ >
+ <span
+ v-if="filled(localTime)"
+ class="flex items-center gap-1 text-xs leading-4 text-muted-foreground"
+ data-testid="note-mention-card-time"
+ >
+ <IconClock class="size-3.5 shrink-0" />
+ {{
+ $t('notes.mention_card.local_time', {
+ time: localTime,
+ })
+ }}
+ </span>
+ </div>
+ </div>
+ </HoverCardContent>
+ </HoverCard>
+</template>
diff --git a/resources/js/components/posts/editor/PostNoteReactions.vue b/resources/js/components/posts/editor/PostNoteReactions.vue
new file mode 100644
index 000000000..0ebabbba6
--- /dev/null
+++ b/resources/js/components/posts/editor/PostNoteReactions.vue
@@ -0,0 +1,108 @@
+<script setup lang="ts">
+import { IconMoodPlus } from '@tabler/icons-vue';
+import { ref } from 'vue';
+
+import EmojiPicker from '@/components/posts/EmojiPicker.vue';
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@/components/ui/popover';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
+import { blank, transform } from '@/lib/helpers';
+import type { PostNoteReaction } from '@/types/post-note';
+
+/**
+ * A note's reactions as chips (emoji and count, who reacted on hover);
+ * clicking a chip adds or takes back the viewer's reaction, and the smiley
+ * opens the emoji picker.
+ */
+const props = defineProps<{
+ reactions: PostNoteReaction[];
+ currentUserId: string;
+}>();
+
+const emit = defineEmits<{
+ toggle: [emoji: string, reacted: boolean];
+}>();
+
+const pickerOpen = ref(false);
+
+const hasReacted = (reaction: PostNoteReaction) =>
+ reaction.users.some((user) => user.id === props.currentUserId);
+
+const reactorNames = (reaction: PostNoteReaction) =>
+ reaction.users.map((user) => user.name).join(', ');
+
+const toggle = (reaction: PostNoteReaction) => {
+ emit('toggle', reaction.emoji, hasReacted(reaction));
+};
+
+const pick = (emoji: string) => {
+ pickerOpen.value = false;
+
+ const existing = props.reactions.find(
+ (reaction) => reaction.emoji === emoji,
+ );
+
+ emit('toggle', emoji, transform(existing, hasReacted, false));
+};
+</script>
+
+<template>
+ <div
+ class="mt-1 flex flex-wrap items-center gap-1"
+ data-testid="note-reactions"
+ >
+ <TooltipProvider :delay-duration="300">
+ <Tooltip v-for="reaction in reactions" :key="reaction.emoji">
+ <TooltipTrigger as-child>
+ <button
+ type="button"
+ class="inline-flex h-6 items-center gap-1 rounded-full border px-2 text-xs transition-colors"
+ :class="
+ hasReacted(reaction)
+ ? 'border-primary bg-primary-subtle text-foreground'
+ : 'border-border bg-card text-muted-foreground hover:border-border-strong'
+ "
+ :aria-pressed="hasReacted(reaction)"
+ :aria-label="`${reaction.emoji} ${reactorNames(reaction)}`"
+ :data-testid="`note-reaction-${reaction.emoji}`"
+ @click="toggle(reaction)"
+ >
+ <span class="text-sm leading-none">{{
+ reaction.emoji
+ }}</span>
+ <span class="tabular-nums">{{ reaction.count }}</span>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{{ reactorNames(reaction) }}</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+
+ <Popover v-model:open="pickerOpen">
+ <PopoverTrigger as-child>
+ <button
+ type="button"
+ class="inline-flex size-6 items-center justify-center rounded-full text-muted-foreground transition-[color,opacity] hover:bg-muted hover:text-foreground data-[state=open]:opacity-100"
+ :class="{
+ 'lg:opacity-0 lg:group-focus-within/note:opacity-100 lg:group-hover/note:opacity-100':
+ blank(reactions),
+ }"
+ :aria-label="$t('notes.react')"
+ data-testid="note-react"
+ >
+ <IconMoodPlus class="size-4" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent class="w-auto p-0" align="start">
+ <EmojiPicker @select="pick" />
+ </PopoverContent>
+ </Popover>
+ </div>
+</template>
diff --git a/resources/js/components/posts/editor/PostNotesPanel.vue b/resources/js/components/posts/editor/PostNotesPanel.vue
index 830b7c882..76534b6ed 100644
--- a/resources/js/components/posts/editor/PostNotesPanel.vue
+++ b/resources/js/components/posts/editor/PostNotesPanel.vue
@@ -1,35 +1,55 @@
<script setup lang="ts">
-import { usePage } from '@inertiajs/vue3';
+import type { InfiniteScrollRef } from '@inertiajs/core';
+import { InfiniteScroll, router, useHttp, usePage } from '@inertiajs/vue3';
import { IconArrowUp, IconLoader2 } from '@tabler/icons-vue';
-import { computed, nextTick, onMounted, ref, watch } from 'vue';
-
+import { trans } from 'laravel-vue-i18n';
+import {
+ computed,
+ nextTick,
+ onMounted,
+ ref,
+ watch,
+ type ComponentPublicInstance,
+} from 'vue';
+import { toast } from 'vue-sonner';
+
+import PostNoteEditor from '@/components/posts/editor/PostNoteEditor.vue';
import PostNoteItem from '@/components/posts/editor/PostNoteItem.vue';
import { Avatar } from '@/components/ui/avatar';
-import { Button } from '@/components/ui/button';
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
- InputGroupTextarea,
} from '@/components/ui/input-group';
import { usePostEcho } from '@/composables/echo/usePostEcho';
+import { blank, filled } from '@/lib/helpers';
+import { afterPaint } from '@/lib/utils';
import {
destroy as destroyNote,
- index as fetchNotes,
+ show as showNote,
store as storeNote,
update as updateNote,
} from '@/routes/app/posts/notes';
-import type { PostNote } from '@/types/post-note';
-
-interface PaginatedResponse {
- data: PostNote[];
- meta: {
- current_page: number;
- last_page: number;
- total: number;
- };
-}
-
+import { index as fetchMentionables } from '@/routes/app/posts/notes/mentionables';
+import {
+ destroy as removeReaction,
+ update as addReaction,
+} from '@/routes/app/posts/notes/reactions';
+import type { SharedData } from '@/types';
+import type {
+ PostNote,
+ PostNoteMentionable,
+ PostNotesPage,
+} from '@/types/post-note';
+
+/**
+ * The notes thread of the post whose notes the page has open: the notes come
+ * from the page's `postNotes` scroll prop (newest first, shown oldest first),
+ * and scrolling up loads older pages through `<InfiniteScroll reverse>`. A
+ * change touches only its note, from the request's answer or from the
+ * `post.note.changed` broadcast (which names the note), so older pages and
+ * the scroll stay where they are.
+ */
const props = defineProps<{
postId: string;
currentUserId: string;
@@ -40,42 +60,70 @@ const emit = defineEmits<{
count: [total: number];
}>();
-const page = usePage();
+const page = usePage<
+ SharedData & {
+ openPostNotesId?: string | null;
+ postNotes?: PostNotesPage | null;
+ }
+>();
const currentUser = computed(() => page.props.auth.user);
-const csrfToken =
- document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')
- ?.content ?? '';
+const sendHttp = useHttp<{ body: string }, PostNote>({ body: '' });
+const noteHttp = useHttp<{ body: string }, PostNote>({ body: '' });
+const fetchHttp = useHttp<Record<string, never>, PostNote>({});
+const deleteHttp = useHttp({});
+const reactionHttp = useHttp<{ emoji: string }, PostNote>({ emoji: '' });
+const mentionablesHttp = useHttp<
+ Record<string, never>,
+ PostNoteMentionable[]
+>({});
+
+/** This post's notes as the page holds them (newest first), once loaded. */
+const thread = computed(() =>
+ page.props.openPostNotesId === props.postId ? page.props.postNotes : null,
+);
-const notes = ref<PostNote[]>([]);
-const total = ref(0);
-const currentPage = ref(1);
-const lastPage = ref(1);
-const loading = ref(false);
-const sending = ref(false);
+/** Oldest first, each note once: a page loaded after a new note can repeat the last one. */
+const notes = computed(() => [
+ ...new Map(
+ [...(thread.value?.data ?? [])].reverse().map((note) => [note.id, note]),
+ ).values(),
+]);
const newBody = ref('');
const highlightedId = ref<string | null>(null);
const scrollContainer = ref<HTMLDivElement | null>(null);
-const composerInput = ref<{ $el: HTMLTextAreaElement } | null>(null);
-
-watch(total, (count) => emit('count', count));
-
-const hasOlderNotes = computed(() => currentPage.value < lastPage.value);
-const canSend = computed(() => newBody.value.trim() !== '' && !sending.value);
-
-const request = (url: string, method = 'GET', body?: object) =>
- fetch(url, {
- method,
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- 'X-CSRF-TOKEN': csrfToken,
- 'X-Requested-With': 'XMLHttpRequest',
- },
- body: body ? JSON.stringify(body) : undefined,
- });
+const notesList = ref<HTMLOListElement | null>(null);
+const noteElements = new Map<string, Element>();
+
+/** Keeps each rendered note's element by id, for scrolling to a linked note. */
+const trackNote = (
+ noteId: string,
+ element: Element | ComponentPublicInstance | null,
+): void => {
+ if (element instanceof Element) {
+ noteElements.set(noteId, element);
+ } else {
+ noteElements.delete(noteId);
+ }
+};
+const infiniteScroll = ref<InfiniteScrollRef | null>(null);
+const composerInput = ref<InstanceType<typeof PostNoteEditor> | null>(
+ null,
+);
+const mentionables = ref<PostNoteMentionable[] | null>(null);
+
+watch(
+ () => thread.value?.meta.total,
+ (total) => {
+ if (filled(total)) {
+ emit('count', total);
+ }
+ },
+);
+
+const canSend = computed(() => filled(newBody.value) && !sendHttp.processing);
const scrollToBottom = () => {
if (scrollContainer.value) {
@@ -83,139 +131,239 @@ const scrollToBottom = () => {
}
};
-const loadNotes = async (page = 1) => {
- loading.value = true;
+/** Whether the list shows its last note, so a new one should keep it in view. */
+const isAtBottom = (): boolean => {
+ const container = scrollContainer.value;
- try {
- const response = await request(
- fetchNotes.url(props.postId, { query: { page } }),
- );
+ return (
+ !container ||
+ container.scrollHeight - container.scrollTop - container.clientHeight < 48
+ );
+};
- if (!response.ok) {
- return;
- }
+/**
+ * Puts a note in the thread: replaces it wherever it shows (a page loaded after
+ * a new note can repeat one), or, for a new note, adds it as the newest.
+ */
+const putNote = async (note: PostNote, isNew = false): Promise<void> => {
+ const loaded = thread.value;
- const data: PaginatedResponse = await response.json();
- const chronological = [...data.data].reverse();
- currentPage.value = data.meta.current_page;
- lastPage.value = data.meta.last_page;
- total.value = data.meta.total;
-
- if (page === 1) {
- notes.value = chronological;
- await nextTick();
- scrollToBottom();
- } else {
- notes.value = [...chronological, ...notes.value];
- }
- } finally {
- loading.value = false;
+ if (!loaded) {
+ return;
}
-};
-usePostEcho(props.postId, '.post.note.changed', () => {
- void loadNotes(1);
-});
+ if (loaded.data.some((item) => item.id === note.id)) {
+ loaded.data = loaded.data.map((item) =>
+ item.id === note.id ? note : item,
+ );
-const loadOlderNotes = () => {
- if (hasOlderNotes.value && !loading.value) {
- void loadNotes(currentPage.value + 1);
+ return;
}
-};
-const focusComposer = () => {
- composerInput.value?.$el.focus();
+ if (!isNew) {
+ return;
+ }
+
+ const follow = isAtBottom();
+
+ loaded.data.unshift(note);
+ loaded.meta.total++;
+
+ if (follow) {
+ await nextTick();
+ scrollToBottom();
+ }
};
-const sendNote = async () => {
- const body = newBody.value.trim();
+/** Takes a note out of the thread, every copy of it. */
+const dropNote = (noteId: string): void => {
+ const loaded = thread.value;
- if (!body || sending.value) {
+ if (!loaded?.data.some((item) => item.id === noteId)) {
return;
}
- sending.value = true;
+ loaded.data = loaded.data.filter((item) => item.id !== noteId);
+ loaded.meta.total--;
+};
- try {
- const response = await request(storeNote.url(props.postId), 'POST', {
- body,
- });
+const failed = (message: string): void => {
+ toast.error(message, { testId: 'note-error-toast' });
+};
- if (!response.ok) {
+/** Another member (or this page) changed a note: refresh that note alone. */
+usePostEcho<{ note_id: string | null; change: string }>(
+ props.postId,
+ '.post.note.changed',
+ async ({ note_id: noteId, change }) => {
+ if (!filled(noteId)) {
return;
}
- const created: PostNote = await response.json();
- notes.value.push(created);
+ if (change === 'deleted') {
+ dropNote(noteId);
- total.value++;
- newBody.value = '';
- await nextTick();
- scrollToBottom();
- focusComposer();
- } finally {
- sending.value = false;
+ return;
+ }
+
+ const note = await fetchHttp
+ .get(showNote.url({ post: props.postId, note: noteId }))
+ .catch(() => null);
+
+ if (filled(note)) {
+ await putNote(note, change === 'created');
+ }
+ },
+);
+
+const focusComposer = () => {
+ composerInput.value?.focus();
+};
+
+/** The people a note can mention, loaded once when the first `@` is typed. */
+const loadMentionables = async () => {
+ if (mentionables.value !== null || mentionablesHttp.processing) {
+ return;
+ }
+
+ const people = await mentionablesHttp
+ .get(fetchMentionables.url(props.postId))
+ .catch(() => null);
+
+ if (people) {
+ mentionables.value = people;
}
};
-const saveNote = async (note: PostNote, body: string) => {
- const response = await request(
- updateNote.url({ post: props.postId, note: note.id }),
- 'PUT',
- { body },
- );
+const toggleReaction = async (
+ note: PostNote,
+ emoji: string,
+ reacted: boolean,
+) => {
+ reactionHttp.emoji = emoji;
+
+ const updated = await reactionHttp
+ .submit((reacted ? removeReaction : addReaction)({
+ post: props.postId,
+ note: note.id,
+ }))
+ .catch(() => null);
+
+ if (filled(updated)) {
+ await putNote(updated);
+ } else {
+ failed(reactionHttp.errors.emoji ?? trans('notes.errors.not_reacted'));
+ }
+};
- if (!response.ok) {
+const sendNote = async () => {
+ const body = newBody.value.trim();
+
+ if (blank(body) || sendHttp.processing) {
return;
}
- const updated: PostNote = await response.json();
- note.body = updated.body;
- note.updated_at = updated.updated_at;
-};
+ sendHttp.body = body;
+ composerInput.value?.markSent();
-const deleteNote = async (note: PostNote) => {
- const response = await request(
- destroyNote.url({ post: props.postId, note: note.id }),
- 'DELETE',
- );
+ const created = await sendHttp
+ .post(storeNote.url(props.postId))
+ .catch(() => null);
+
+ if (!filled(created)) {
+ failed(sendHttp.errors.body ?? trans('notes.errors.not_saved'));
- if (!response.ok) {
return;
}
- notes.value = notes.value.filter((item) => item.id !== note.id);
- total.value = Math.max(0, total.value - 1);
+ composerInput.value?.dropSent();
+ await putNote(created, true);
+ scrollToBottom();
+ focusComposer();
};
-const handleComposerKeydown = (event: KeyboardEvent) => {
- if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
- event.preventDefault();
- void sendNote();
+/** Saves an edit; `done(false)` keeps the editor open with the text. */
+const saveNote = async (
+ note: PostNote,
+ body: string,
+ done: (saved: boolean) => void,
+) => {
+ noteHttp.body = body;
+
+ const updated = await noteHttp
+ .put(updateNote.url({ post: props.postId, note: note.id }))
+ .catch(() => null);
+
+ if (filled(updated)) {
+ await putNote(updated);
+ } else {
+ failed(noteHttp.errors.body ?? trans('notes.errors.not_saved'));
}
+
+ done(filled(updated));
};
-const focusNote = async (noteId: string) => {
- await nextTick();
- const selector = `[data-note-id="${noteId}"]`;
- let element = scrollContainer.value?.querySelector<HTMLElement>(selector);
+const deleteNote = async (note: PostNote) => {
+ const deleted = await deleteHttp
+ .delete(destroyNote.url({ post: props.postId, note: note.id }))
+ .then(() => true)
+ .catch(() => false);
+
+ if (deleted) {
+ dropNote(note.id);
+ } else {
+ failed(trans('notes.errors.not_deleted'));
+ }
+};
+
+/**
+ * Loads the next older page; false when there is none or it fails. It settles
+ * when the next visit finishes, which also covers a load the scroll started.
+ */
+const loadOlderNotes = (): Promise<boolean> =>
+ new Promise((resolve) => {
+ const scroll = infiniteScroll.value;
- while (!element && hasOlderNotes.value) {
- const previousPage = currentPage.value;
- await loadNotes(currentPage.value + 1);
+ if (!scroll?.hasNext()) {
+ resolve(false);
- if (currentPage.value === previousPage) {
- break;
+ return;
}
- await nextTick();
- element = scrollContainer.value?.querySelector<HTMLElement>(selector);
+ const stop = router.on('finish', (event) => {
+ stop();
+ resolve(event.detail.visit.completed);
+ });
+
+ scroll.fetchNext();
+ });
+
+/** The note's element, loading older pages until it shows up or none are left. */
+const findNote = async (noteId: string): Promise<Element | null> => {
+ await nextTick();
+
+ const element = noteElements.get(noteId);
+
+ if (element) {
+ return element;
}
+ return (await loadOlderNotes()) ? findNote(noteId) : null;
+};
+
+/**
+ * Scrolls to a note and highlights it. The scroll waits for the page to settle:
+ * `<InfiniteScroll reverse>` keeps the reader's place after loading an older
+ * page, which would otherwise scroll the note back out of view.
+ */
+const focusNote = async (noteId: string) => {
+ const element = await findNote(noteId);
+
if (!element) {
return;
}
+ await afterPaint();
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
highlightedId.value = noteId;
setTimeout(() => {
@@ -225,31 +373,16 @@ const focusNote = async (noteId: string) => {
}, 4000);
};
-onMounted(async () => {
- await loadNotes(1);
-
- if (props.highlightNoteId) {
- await focusNote(props.highlightNoteId);
+/** Opens on the linked note once the thread has loaded, and again when the link changes. */
+const focusLinkedNote = () => {
+ if (filled(thread.value) && filled(props.highlightNoteId)) {
+ void focusNote(props.highlightNoteId);
}
-});
-
-watch(
- () => props.highlightNoteId,
- (noteId) => {
- if (noteId) {
- void focusNote(noteId);
- }
- },
-);
+};
-watch(
- () => props.postId,
- () => {
- notes.value = [];
- currentPage.value = 1;
- void loadNotes(1);
- },
-);
+watch(() => filled(thread.value), focusLinkedNote);
+watch(() => props.highlightNoteId, focusLinkedNote);
+onMounted(focusLinkedNote);
</script>
<template>
@@ -259,55 +392,63 @@ watch(
class="-mx-2 max-h-80 min-h-0 overflow-x-hidden overflow-y-auto overscroll-contain px-2"
data-testid="notes-list"
>
- <div v-if="hasOlderNotes" class="flex justify-start pb-2">
- <Button
- type="button"
- variant="ghost"
- size="sm"
- class="-ms-2 text-muted-foreground"
- :disabled="loading"
- @click="loadOlderNotes"
- >
- <IconLoader2
- v-if="loading"
- class="size-3.5 animate-spin"
- />
- {{ $t('notes.load_more') }}
- </Button>
- </div>
-
- <div
- v-if="loading && notes.length === 0"
- class="flex items-center gap-3 py-1"
- >
+ <div v-if="blank(thread)" class="flex items-center gap-3 py-1">
<IconLoader2
class="size-4 animate-spin text-muted-foreground"
/>
</div>
<p
- v-else-if="notes.length === 0"
+ v-else-if="blank(notes)"
class="py-1 text-sm text-muted-foreground"
data-testid="notes-empty"
>
{{ $t('notes.empty') }}
</p>
- <ol v-else class="flex flex-col">
- <li
- v-for="note in notes"
- :key="note.id"
- class="relative pb-3 last:pb-0 [&:not(:last-child)]:before:absolute [&:not(:last-child)]:before:start-[13.5px] [&:not(:last-child)]:before:top-9 [&:not(:last-child)]:before:bottom-1 [&:not(:last-child)]:before:w-px [&:not(:last-child)]:before:bg-border-strong"
- >
- <PostNoteItem
- :note="note"
- :current-user-id="currentUserId"
- :highlighted="highlightedId === note.id"
- @save="saveNote(note, $event)"
- @delete="deleteNote(note)"
- />
- </li>
- </ol>
+ <InfiniteScroll
+ v-else
+ ref="infiniteScroll"
+ data="postNotes"
+ reverse
+ preserve-url
+ :items-element="() => notesList"
+ >
+ <template #next="{ loading }">
+ <div
+ v-if="loading"
+ class="flex justify-center pb-2"
+ data-testid="notes-loading-older"
+ >
+ <IconLoader2
+ class="size-4 animate-spin text-muted-foreground"
+ />
+ </div>
+ </template>
+
+ <ol ref="notesList" class="flex flex-col">
+ <li
+ v-for="note in notes"
+ :key="note.id"
+ :ref="(element) => trackNote(note.id, element)"
+ class="relative pb-3 last:pb-0 [&:not(:last-child)]:before:absolute [&:not(:last-child)]:before:start-[13.5px] [&:not(:last-child)]:before:top-9 [&:not(:last-child)]:before:bottom-1 [&:not(:last-child)]:before:w-px [&:not(:last-child)]:before:bg-border-strong"
+ >
+ <PostNoteItem
+ :note="note"
+ :current-user-id="currentUserId"
+ :mentionables="mentionables"
+ :highlighted="highlightedId === note.id"
+ @save="(body, done) => saveNote(note, body, done)"
+ @delete="deleteNote(note)"
+ @react="
+ (emoji, reacted) =>
+ toggleReaction(note, emoji, reacted)
+ "
+ @need-people="loadMentionables"
+ />
+ </li>
+ </ol>
+ </InfiniteScroll>
</div>
<div class="flex shrink-0 items-end gap-3">
@@ -319,18 +460,21 @@ watch(
fallback-class="bg-sidebar-accent text-sidebar-accent-foreground"
/>
<InputGroup
- class="min-w-0 flex-1 items-end rounded-[18px] border-transparent bg-muted shadow-none transition-colors hover:border-border-strong has-[[data-slot=input-group-control]:focus-visible]:bg-card"
+ class="h-auto min-h-9 min-w-0 flex-1 items-end rounded-[18px] border-transparent bg-muted shadow-none transition-colors hover:border-border-strong has-[[data-slot=input-group-control]:focus-visible]:bg-card"
data-testid="note-composer"
>
- <InputGroupTextarea
+ <PostNoteEditor
ref="composerInput"
v-model="newBody"
- rows="1"
+ :people="mentionables"
+ :current-user-id="currentUserId"
:placeholder="$t('notes.placeholder')"
:aria-label="$t('notes.placeholder')"
- class="max-h-28 min-h-0 py-[7px] ps-4 leading-5"
+ data-slot="input-group-control"
+ class="max-h-28 min-h-0 w-full overflow-y-auto bg-transparent py-[7px] ps-4 pe-2 text-sm leading-5"
data-testid="note-input"
- @keydown="handleComposerKeydown"
+ @submit="sendNote"
+ @need-people="loadMentionables"
/>
<InputGroupAddon align="inline-end" class="pb-1.5">
<InputGroupButton
@@ -343,7 +487,7 @@ watch(
@click="sendNote"
>
<IconLoader2
- v-if="sending"
+ v-if="sendHttp.processing"
class="size-3.5 animate-spin"
/>
<IconArrowUp v-else class="size-3.5" />
diff --git a/resources/js/components/publish/PostTimelineCard.vue b/resources/js/components/publish/PostTimelineCard.vue
index 3d59749a4..907e70b09 100644
--- a/resources/js/components/publish/PostTimelineCard.vue
+++ b/resources/js/components/publish/PostTimelineCard.vue
@@ -187,9 +187,26 @@ watch(
);
watch(openPostNotesId, (id) => {
- if (id === props.post.id) notesOpen.value = true;
+ notesOpen.value = id === props.post.id;
});
+/**
+ * Opens or closes this post's notes: the page keeps one thread open (`?notes=`)
+ * and reloads only its props, so opening another post's notes closes this one.
+ */
+const setNotesOpen = (open: boolean): void => {
+ notesOpen.value = open;
+ router.reload({
+ data: {
+ notes: open ? props.post.id : undefined,
+ note: undefined,
+ },
+ only: ['openPostNotesId', 'highlightNoteId', 'postNotes'],
+ reset: ['postNotes'],
+ replace: true,
+ });
+};
+
const setNoteCount = (count: number): void => {
noteCount.value = count;
};
@@ -524,7 +541,7 @@ defineExpose({ openDetails });
</Badge>
</div>
- <Collapsible v-model:open="notesOpen" as-child>
+ <Collapsible :open="notesOpen" as-child @update:open="setNotesOpen">
<article
class="min-w-0 overflow-hidden rounded-xl border border-border-strong bg-card"
>
diff --git a/resources/js/components/tiptap/editor.ts b/resources/js/components/tiptap/editor.ts
new file mode 100644
index 000000000..52fa3de23
--- /dev/null
+++ b/resources/js/components/tiptap/editor.ts
@@ -0,0 +1,22 @@
+/**
+ * What every plain-text TipTap editor of the app is made of: one paragraph of
+ * text with line breaks (Shift+Enter). Editors add their behaviour from
+ * `components/tiptap/plugins`.
+ */
+import type { AnyExtension } from '@tiptap/core';
+import Document from '@tiptap/extension-document';
+import HardBreak from '@tiptap/extension-hard-break';
+import Paragraph from '@tiptap/extension-paragraph';
+import Text from '@tiptap/extension-text';
+import { Placeholder } from '@tiptap/extensions';
+
+/** The plain-text nodes, with a placeholder read each time the editor is empty. */
+export const plainTextExtensions = (
+ placeholder: () => string,
+): AnyExtension[] => [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ Placeholder.configure({ placeholder }),
+];
diff --git a/resources/js/components/tiptap/plugins/noteBody.ts b/resources/js/components/tiptap/plugins/noteBody.ts
new file mode 100644
index 000000000..9ba0586d7
--- /dev/null
+++ b/resources/js/components/tiptap/plugins/noteBody.ts
@@ -0,0 +1,140 @@
+/**
+ * A note in the editor. It opens from the parts the server sends
+ * (`setNoteParts`, see `App\Support\PostNoteMentions::parts`) and reads back
+ * as the body to store (`noteBodyOf`): each mention chip as its markup
+ * (`@[user:{id}]`, `@[everyone]`) and each line break as a new line. A copied
+ * chip reads `@Name`, and Backspace removes a chip whole.
+ */
+import { Extension, type Editor, type JSONContent } from '@tiptap/core';
+import Mention from '@tiptap/extension-mention';
+import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { Plugin } from '@tiptap/pm/state';
+import type { SuggestionOptions } from '@tiptap/suggestion';
+
+import { isEmpty } from '@/lib/helpers';
+import type { PostNotePart } from '@/types/post-note';
+
+/** The id a chip of everyone carries; it is never a user id. */
+export const EVERYONE_ID = 'everyone';
+
+declare module '@tiptap/core' {
+ interface Commands<ReturnType> {
+ noteBody: {
+ /** Replaces the content with a note's parts, without an update event. */
+ setNoteParts: (parts: PostNotePart[]) => ReturnType;
+ };
+ }
+}
+
+interface NoteBodyOptions {
+ /** The word a chip of everyone shows, in the reader's language. */
+ everyoneLabel: () => string;
+ /** What a chip shows for someone no longer there. */
+ unknownLabel: () => string;
+ /** The `@` list shown while typing after `@`. */
+ suggestion: Omit<SuggestionOptions, 'editor'>;
+ /** Attributes of a chip (class, test id). */
+ chipAttributes: Record<string, string>;
+}
+
+/** A copied chip as people read it, and a line break as a new line. */
+const clipboardText = (leaf: ProseMirrorNode): string =>
+ leaf.type.name === 'mention' ? `@${leaf.attrs.label}` : '\n';
+
+/** Text as the editor holds it: a line break is its own node, not a `\n` in the text. */
+const textNodes = (text: string): JSONContent[] =>
+ text
+ .split('\n')
+ .flatMap((line, index): JSONContent[] => [
+ ...(index > 0 ? [{ type: 'hardBreak' }] : []),
+ ...(isEmpty(line) ? [] : [{ type: 'text', text: line }]),
+ ]);
+
+/** A note's parts as the editor's document: one paragraph of text, line breaks and chips. */
+const noteDoc = (
+ parts: PostNotePart[],
+ labels: { everyone: string; unknown: string },
+): JSONContent => ({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: parts.flatMap((part): JSONContent[] => {
+ if (part.type === 'text') {
+ return textNodes(part.text);
+ }
+
+ return [
+ {
+ type: 'mention',
+ attrs:
+ part.type === 'everyone'
+ ? { id: EVERYONE_ID, label: labels.everyone }
+ : { id: part.id, label: part.name ?? labels.unknown },
+ },
+ ];
+ }),
+ },
+ ],
+});
+
+/** A mention as the body stores it. */
+const mentionMarkup = (id: string): string =>
+ id === EVERYONE_ID ? '@[everyone]' : `@[user:${id}]`;
+
+export const NoteBody = Extension.create<NoteBodyOptions>({
+ name: 'noteBody',
+
+ addOptions: () => ({
+ everyoneLabel: () => '',
+ unknownLabel: () => '',
+ suggestion: {},
+ chipAttributes: {},
+ }),
+
+ addExtensions() {
+ return [
+ Mention.configure({
+ HTMLAttributes: this.options.chipAttributes,
+ deleteTriggerWithBackspace: true,
+ renderText: ({ node }) => mentionMarkup(node.attrs.id),
+ suggestion: this.options.suggestion,
+ }),
+ ];
+ },
+
+ addProseMirrorPlugins() {
+ return [
+ new Plugin({
+ props: {
+ clipboardTextSerializer: (slice) =>
+ slice.content.textBetween(
+ 0,
+ slice.content.size,
+ '\n',
+ clipboardText,
+ ),
+ },
+ }),
+ ];
+ },
+
+ addCommands() {
+ return {
+ setNoteParts:
+ (parts) =>
+ ({ commands }) =>
+ commands.setContent(
+ noteDoc(parts, {
+ everyone: this.options.everyoneLabel(),
+ unknown: this.options.unknownLabel(),
+ }),
+ { emitUpdate: false },
+ ),
+ };
+ },
+});
+
+/** The editor's content as the body to store. */
+export const noteBodyOf = (editor: Editor): string =>
+ editor.getText({ blockSeparator: '\n' });
diff --git a/resources/js/components/tiptap/plugins/noteKeys.ts b/resources/js/components/tiptap/plugins/noteKeys.ts
new file mode 100644
index 000000000..b6b5213d5
--- /dev/null
+++ b/resources/js/components/tiptap/plugins/noteKeys.ts
@@ -0,0 +1,47 @@
+/**
+ * Enter sends and Esc cancels, like a chat input; Shift+Enter still breaks
+ * the line. Each key is left to the editor while `submitBlocked` /
+ * `cancelBlocked` say so (an open `@` list picks with Enter and closes on Esc).
+ */
+import { Extension } from '@tiptap/core';
+
+interface NoteKeysOptions {
+ onSubmit: () => void;
+ onCancel: () => void;
+ submitBlocked: () => boolean;
+ cancelBlocked: () => boolean;
+}
+
+export const NoteKeys = Extension.create<NoteKeysOptions>({
+ name: 'noteKeys',
+
+ addOptions: () => ({
+ onSubmit: () => {},
+ onCancel: () => {},
+ submitBlocked: () => false,
+ cancelBlocked: () => false,
+ }),
+
+ addKeyboardShortcuts() {
+ return {
+ Enter: () => {
+ if (this.options.submitBlocked()) {
+ return false;
+ }
+
+ this.options.onSubmit();
+
+ return true;
+ },
+ Escape: () => {
+ if (this.options.cancelBlocked()) {
+ return false;
+ }
+
+ this.options.onCancel();
+
+ return true;
+ },
+ };
+ },
+});
diff --git a/resources/js/lib/utils.ts b/resources/js/lib/utils.ts
index 67d85854f..ec0cf77fa 100644
--- a/resources/js/lib/utils.ts
+++ b/resources/js/lib/utils.ts
@@ -205,3 +205,9 @@ export const htmlToPlainText = (html: string): string => {
return text.replace(/\n{3,}/g, '\n\n').trim();
};
+
+/** Resolves once the browser has laid out and painted the current changes. */
+export const afterPaint = (): Promise<void> =>
+ new Promise((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
diff --git a/resources/js/pages/create/Ideas.vue b/resources/js/pages/create/Ideas.vue
index 88a873960..7318f0466 100644
--- a/resources/js/pages/create/Ideas.vue
+++ b/resources/js/pages/create/Ideas.vue
@@ -232,11 +232,13 @@ const listReload = computed(() => ({
}));
const moving = ref(false);
-const queuedMove = ref<{
- ideaId: string;
- toStageId: string | null;
- orderedIdeaIds: string[];
-} | null>(null);
+
+/**
+ * Moves made while one is saving: shown at once, then sent in order after it,
+ * each with its column's order as the board shows it then (a later drop may
+ * have joined that column since). A card dropped twice keeps its last drop.
+ */
+const queuedMoves: { ideaId: string; toStageId: string | null }[] = [];
const moveIdea = (
ideaId: string,
@@ -251,12 +253,6 @@ const moveIdea = (
);
const card = cards.get(ideaId);
- if (moving.value) {
- queuedMove.value = { ideaId, toStageId, orderedIdeaIds };
-
- return;
- }
-
if (!card) {
return;
}
@@ -275,8 +271,20 @@ const moveIdea = (
.map((id) => cards.get(id))
.filter((candidate): candidate is IdeaCard => candidate !== undefined);
+ if (moving.value) {
+ localColumns.value = next;
+ queuedMoves.splice(
+ 0,
+ queuedMoves.length,
+ ...queuedMoves.filter((queued) => queued.ideaId !== ideaId),
+ { ideaId, toStageId },
+ );
+
+ return;
+ }
+
const rollback = (message: string): void => {
- queuedMove.value = null;
+ queuedMoves.length = 0;
localColumns.value = snapshot;
toast.error(message, { testId: 'ideas-move-error-toast' });
router.reload({ only: BOARD_PROPS, reset: columnPaths() });
@@ -299,14 +307,16 @@ const moveIdea = (
onFinish: () => {
moving.value = false;
- const queued = queuedMove.value;
- queuedMove.value = null;
+ const queued = queuedMoves.shift();
if (queued) {
moveIdea(
queued.ideaId,
queued.toStageId,
- queued.orderedIdeaIds,
+ (
+ localColumns.value[columnKey(queued.toStageId)] ??
+ []
+ ).map((card) => card.id),
);
}
},
@@ -319,6 +329,11 @@ const moveIdea = (
onHttpException: () => {
rollback(trans('create.ideas.errors.move_failed'));
+ return false;
+ },
+ onNetworkError: () => {
+ rollback(trans('create.ideas.errors.move_failed'));
+
return false;
},
},
@@ -355,6 +370,11 @@ const reorderColumns = (orderedStageIds: string[]): void => {
onHttpException: () => {
rollback(trans('create.ideas.errors.move_failed'));
+ return false;
+ },
+ onNetworkError: () => {
+ rollback(trans('create.ideas.errors.move_failed'));
+
return false;
},
},
diff --git a/resources/js/types/post-note.ts b/resources/js/types/post-note.ts
index 6f03ab485..7b44f8218 100644
--- a/resources/js/types/post-note.ts
+++ b/resources/js/types/post-note.ts
@@ -4,11 +4,48 @@ export interface PostNoteAuthor {
photo_url?: string | null;
}
+export interface PostNoteReaction {
+ emoji: string;
+ count: number;
+ users: { id: string; name: string }[];
+}
+
export interface PostNote {
id: string;
body: string;
user_id: string;
created_at: string;
updated_at: string;
+ mentions: MentionedPerson[];
+ parts: PostNotePart[];
+ reactions: PostNoteReaction[];
user: PostNoteAuthor;
}
+
+/** A page of a post's notes, newest first, as the publish page sends it (`postNotes`). */
+export interface PostNotesPage {
+ data: PostNote[];
+ meta: {
+ total: number;
+ };
+}
+
+/** A piece of a note's text, as the server splits it: text, a person (null name when they are gone) or everyone. */
+export type PostNotePart =
+ | { type: 'text'; text: string }
+ | { type: 'mention'; id: string; name: string | null }
+ | { type: 'everyone' };
+
+/** A member a note mentions, with their current name; the body holds only the id. */
+export interface MentionedPerson {
+ id: string;
+ name: string;
+}
+
+/** A member a note may mention, with what the mention card shows. */
+export interface PostNoteMentionable {
+ id: string;
+ name: string;
+ photo_url: string | null;
+ timezone: string;
+}
diff --git a/resources/views/mail/post-note-mentioned.blade.php b/resources/views/mail/post-note-mentioned.blade.php
new file mode 100644
index 000000000..fc68a1f66
--- /dev/null
+++ b/resources/views/mail/post-note-mentioned.blade.php
@@ -0,0 +1,166 @@
+@use('App\Enums\User\Locale')
+@php
+$direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
+@endphp
+<!DOCTYPE html>
+<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" dir="{{ $direction }}" xmlns:v="urn:schemas-microsoft-com:vml">
+<head>
+ <meta charset="utf-8">
+ <meta name="x-apple-disable-message-reformatting">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no">
+ <meta name="color-scheme" content="light">
+ <meta name="supported-color-schemes" content="light">
+ <!--[if mso]>
+ <noscript>
+ <xml>
+ <o:OfficeDocumentSettings xmlns:o="urn:schemas-microsoft-com:office:office">
+ <o:PixelsPerInch>96</o:PixelsPerInch>
+ </o:OfficeDocumentSettings>
+ </xml>
+ </noscript>
+ <style>
+ td,th,div,p,a,h1,h2,h3,h4,h5,h6 {font-family: "Segoe UI", sans-serif; mso-line-height-rule: exactly;}
+ </style>
+ <![endif]-->
+ @if(isset($title))
+ <title>{{ $title }}</title>
+ @endif
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=Outfit:wght@600&display=swap" rel="stylesheet" media="screen">
+ <style>
+ @media (max-width: 600px) {
+ .sm-p-6 {
+ padding: 24px !important
+ }
+ }
+ </style>
+</head>
+<body style="margin: 0; width: 100%; background-color: #f7f6f3; padding: 0; -webkit-font-smoothing: antialiased; word-break: break-word">
+ @if(isset($previewText))
+ <div style="display: none">
+ {{ $previewText }}
+ &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847; &#8199;&#65279;&#847;
+ </div>
+ @endif
+ <div role="article" aria-roledescription="email" aria-label="{{ $title }}" lang="{{ str_replace('_', '-', app()->getLocale()) }}">
+ <table role="presentation" style="width: 100%; background-color: #f7f6f3; font-family: Inter, Arial, Helvetica, sans-serif" cellpadding="0" cellspacing="0">
+ <tr>
+ <td align="center" style="padding-left: 16px; padding-right: 16px">
+ <!--[if mso]>
+ <table role="presentation" width="552" align="center"><tr><td>
+ <![endif]-->
+ <table role="presentation" align="center" style="width: 100%; max-width: 552px" cellpadding="0" cellspacing="0">
+ <tr>
+ <td style="padding-top: 32px; padding-bottom: 32px">
+ <div style="text-align: center">
+ <a href="https://trypost.it" target="_blank">
+ <img src="{{ asset('/images/emails/logo-header.png') }}" width="150" height="auto" alt="TryPost" style="max-width: 100%; vertical-align: middle; width: 150px; height: auto">
+ </a>
+ </div>
+ </td>
+ </tr>
+ <tr>
+ <td align="{{ $direction === 'rtl' ? 'right' : 'left' }}" class="sm-p-6" style="border-radius: 12px; border: 1px solid #eae8e5; background-color: #ffffff; padding: 32px; font-size: 16px; line-height: 24px; color: #292928">
+ <h1 style="margin: 0 0 24px; font-family: Outfit, Inter, Arial, Helvetica, sans-serif; font-size: 24px; font-weight: 600; line-height: 32px; color: #292928"> {{ __('mail.post_note_mentioned.heading') }}</h1>
+ <p style="margin: 0; line-height: 24px">
+ {{ __('mail.post_note_mentioned.body', ['author' => $authorName, 'workspace' => $workspaceName]) }}
+ </p>
+ <div style="margin-top: 16px; border-radius: 8px; background-color: #f7f6f3; padding: 16px">
+ <p style="white-space: pre-line; margin: 0; line-height: 24px; color: #292928">{{ $noteBody }}</p>
+ </div>
+ <div style="margin-top: 16px; border-radius: 8px; background-color: #f7f6f3; padding: 16px">
+ <p style="margin: 0; font-size: 14px; font-weight: 600; color: #292928">
+ {{ __('mail.post_note_mentioned.post_title') }}
+ </p>
+ <p style="white-space: pre-line; margin: 8px 0 0; font-size: 14px; line-height: 24px">{{ $postExcerpt !== '' ? $postExcerpt : __('mail.post_note_mentioned.post_without_text') }}</p>
+ @if($channel)
+ <table role="presentation" style="margin-top: 12px; width: 100%" cellpadding="0" cellspacing="0">
+ <tr>
+ <td style="border-radius: 12px; border: 1px solid #eae8e5; background-color: #ffffff; padding: 16px">@php
+ $emailChannelPlatform = $channel->platform;
+ $emailChannelName = $channel->display_name;
+ @endphp
+ <table role="presentation" style="width: 100%" cellpadding="0" cellspacing="0">
+ <tr>
+ <td style="width: 44px; vertical-align: middle">
+ <img src="{{ asset('images/accounts/'.$emailChannelPlatform->network().'.png') }}" width="32" height="32" alt style="max-width: 100%; vertical-align: middle; display: block; border-radius: 8px">
+ </td>
+ <td style="vertical-align: middle">
+ <p style="margin: 0; font-size: 16px; font-weight: 600; line-height: 20px; color: #292928">{{ $emailChannelName }}</p>
+ @if($emailChannelName !== $emailChannelPlatform->label())
+ <p style="margin: 2px 0 0; font-size: 13px; line-height: 18px; color: #5a5a59">{{ $emailChannelPlatform->label() }}</p>
+ @endif
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
+ @endif
+ </div>
+ <div role="separator" style="line-height: 24px">&zwj;</div>
+ <div style="text-align: center">
+ <a href="{{ $url }}" style="display: inline-block; text-decoration: none; font-weight: 600; border-radius: 8px; border: 1px solid #ddd6fe; background-color: #ddd6fe; padding: 12px 24px; text-align: center; font-size: 16px; line-height: 24px; color: #292928">
+ <!--[if mso]><i style="mso-font-width: 150%; mso-text-raise: 31px" hidden>&emsp;</i><![endif]-->
+ <span style="mso-text-raise: 16px">{{ __('mail.post_note_mentioned.button') }}</span>
+ <!--[if mso]><i hidden style="mso-font-width: 150%">&emsp;&#8203;</i><![endif]-->
+ </a>
+ </div>
+ </td>
+ </tr>
+ <tr>
+ <td align="center" style="padding: 24px; text-align: center; font-size: 12px; line-height: 20px; color: #5a5a59">
+ <p style="margin: 0 0 8px">
+ {!! str_replace(':brand', '<a href="https://trypost.it" target="_blank" style="color: inherit; font-weight: 600; text-decoration: none;">TryPost</a>', e(__('mail.layout.tagline'))) !!}
+ </p>
+ <p style="margin: 8px 0 0">
+ <a href="{{ route('app.notifications.preferences') }}" target="_blank" style="color: #5a5a59; text-decoration: underline">
+ {{ __('mail.layout.manage_notifications') }}
+ </a>
+ </p>
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin-left: auto; margin-right: auto; margin-top: 12px">
+ <tr>
+ <td style="padding-left: 4px; padding-right: 4px">
+ <a href="https://github.com/trypostit/trypost" target="_blank">
+ <img src="{{ asset('/images/emails/social/github.png') }}" width="20" height="20" alt="GitHub" style="max-width: 100%; vertical-align: middle">
+ </a>
+ </td>
+ <td style="padding-left: 4px; padding-right: 4px">
+ <a href="https://x.com/trypostit" target="_blank">
+ <img src="{{ asset('/images/emails/social/x.png') }}" width="20" height="20" alt="X" style="max-width: 100%; vertical-align: middle">
+ </a>
+ </td>
+ <td style="padding-left: 4px; padding-right: 4px">
+ <a href="https://www.youtube.com/@trypostit" target="_blank">
+ <img src="{{ asset('/images/emails/social/youtube.png') }}" width="20" height="20" alt="YouTube" style="max-width: 100%; vertical-align: middle">
+ </a>
+ </td>
+ <td style="padding-left: 4px; padding-right: 4px">
+ <a href="https://trypost.it/discord" target="_blank">
+ <img src="{{ asset('/images/emails/social/discord.png') }}" width="20" height="20" alt="Discord" style="max-width: 100%; vertical-align: middle">
+ </a>
+ </td>
+ <td style="padding-left: 4px; padding-right: 4px">
+ <a href="https://www.instagram.com/trypost.it" target="_blank">
+ <img src="{{ asset('/images/emails/social/instagram.png') }}" width="20" height="20" alt="Instagram" style="max-width: 100%; vertical-align: middle">
+ </a>
+ </td>
+ </tr>
+ </table>
+ <p style="margin: 12px 0 0">
+ &copy; {{ date('Y') }} TryPost.it
+ </p>
+ </td>
+ </tr>
+ </table>
+ <!--[if mso]>
+ </td></tr></table>
+ <![endif]-->
+ </td>
+ </tr>
+ </table>
+ </div>
+</body>
+</html>
\ No newline at end of file
diff --git a/routes/api.php b/routes/api.php
index e7d2ade52..64d6e30b1 100644
--- a/routes/api.php
+++ b/routes/api.php
@@ -17,6 +17,8 @@ use App\Http\Controllers\Api\PlatformController;
use App\Http\Controllers\Api\PostApprovalController;
use App\Http\Controllers\Api\PostController;
use App\Http\Controllers\Api\PostNoteController;
+use App\Http\Controllers\Api\PostNoteMentionableController;
+use App\Http\Controllers\Api\PostNoteReactionController;
use App\Http\Controllers\Api\PostRecurrenceController;
use App\Http\Controllers\Api\RepurposeController;
use App\Http\Controllers\Api\SignatureController;
@@ -53,10 +55,14 @@ Route::middleware(['auth:api', 'workspace.token', 'throttle:api'])->group(functi
Route::post('/posts/{post}/media/from-url', [PostController::class, 'attachMediaFromUrl'])->name('api.posts.attach-media-from-url');
Route::get('/posts/{post}/metrics', [PostController::class, 'metrics'])->name('api.posts.metrics');
Route::get('/posts/{post}/preview', [PostController::class, 'preview'])->name('api.posts.preview');
+ Route::get('/posts/{post}/notes/mentionables', [PostNoteMentionableController::class, 'index'])->name('api.posts.notes.mentionables.index');
Route::get('/posts/{post}/notes', [PostNoteController::class, 'index'])->name('api.posts.notes.index');
Route::post('/posts/{post}/notes', [PostNoteController::class, 'store'])->name('api.posts.notes.store');
+ Route::get('/posts/{post}/notes/{note}', [PostNoteController::class, 'show'])->name('api.posts.notes.show');
Route::put('/posts/{post}/notes/{note}', [PostNoteController::class, 'update'])->name('api.posts.notes.update');
Route::delete('/posts/{post}/notes/{note}', [PostNoteController::class, 'destroy'])->name('api.posts.notes.destroy');
+ Route::put('/posts/{post}/notes/{note}/reactions', [PostNoteReactionController::class, 'update'])->name('api.posts.notes.reactions.update');
+ Route::delete('/posts/{post}/notes/{note}/reactions', [PostNoteReactionController::class, 'destroy'])->name('api.posts.notes.reactions.destroy');
Route::post('/posts/{post}/approve', [PostApprovalController::class, 'approve'])->name('api.posts.approve');
Route::post('/posts/{post}/reject', [PostApprovalController::class, 'reject'])->name('api.posts.reject');
diff --git a/routes/app.php b/routes/app.php
index 9956b257f..33e4671ac 100644
--- a/routes/app.php
+++ b/routes/app.php
@@ -37,6 +37,8 @@ use App\Http\Controllers\App\PostController;
use App\Http\Controllers\App\PostGroupController;
use App\Http\Controllers\App\PostLabelController;
use App\Http\Controllers\App\PostNoteController;
+use App\Http\Controllers\App\PostNoteMentionableController;
+use App\Http\Controllers\App\PostNoteReactionController;
use App\Http\Controllers\App\PostRecurrenceController;
use App\Http\Controllers\App\PostScheduleController;
use App\Http\Controllers\App\PostTemplateController;
@@ -274,10 +276,13 @@ Route::middleware(['auth', EnsureAccountReady::class, EnsureHasWorkspace::class]
->middleware('throttle:10,1')
->name('app.posts.ai.alt-text');
- Route::get('posts/{post}/notes', [PostNoteController::class, 'index'])->name('app.posts.notes.index');
+ Route::get('posts/{post}/notes/mentionables', [PostNoteMentionableController::class, 'index'])->name('app.posts.notes.mentionables.index');
Route::post('posts/{post}/notes', [PostNoteController::class, 'store'])->name('app.posts.notes.store');
+ Route::get('posts/{post}/notes/{note}', [PostNoteController::class, 'show'])->name('app.posts.notes.show');
Route::put('posts/{post}/notes/{note}', [PostNoteController::class, 'update'])->name('app.posts.notes.update');
Route::delete('posts/{post}/notes/{note}', [PostNoteController::class, 'destroy'])->name('app.posts.notes.destroy');
+ Route::put('posts/{post}/notes/{note}/reactions', [PostNoteReactionController::class, 'update'])->name('app.posts.notes.reactions.update');
+ Route::delete('posts/{post}/notes/{note}/reactions', [PostNoteReactionController::class, 'destroy'])->name('app.posts.notes.reactions.destroy');
Route::get('settings/workspace/members', [WorkspaceInviteController::class, 'index'])->name('app.members');
Route::post('settings/workspace/members/invites', [WorkspaceInviteController::class, 'store'])->name('app.invites.store');
diff --git a/tests/Browser/CalendarDragAndDropTest.php b/tests/Browser/CalendarDragAndDropTest.php
index 794b8105e..7d4bd3a0a 100644
--- a/tests/Browser/CalendarDragAndDropTest.php
+++ b/tests/Browser/CalendarDragAndDropTest.php
@@ -1696,6 +1696,7 @@ function calendarDragHoldRequests(mixed $page): void
$page->script(<<<'JS'
(() => {
window.__heldRequests = [];
+ window.__answeredRequests = 0;
const open = XMLHttpRequest.prototype.open;
const send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, ...rest) {
@@ -1708,6 +1709,7 @@ function calendarDragHoldRequests(mixed $page): void
return send.call(this, body);
}
+ this.addEventListener('loadend', () => { window.__answeredRequests++; });
window.__heldRequests.push(() => send.call(this, body));
};
window.__releaseHeldRequests = () => window.__heldRequests.splice(0).forEach((release) => release());
@@ -2684,27 +2686,14 @@ test('an older move answered after a newer one keeps both cards where they were
waitForCondition($page, 'window.__heldRequests.length === 2');
$page->script('window.__heldRequests[1]()');
- waitFor($page, '@calendar-reschedule-success-toast');
- $page->script(<<<'JS'
- (() => {
- window.__heldReloads = [];
- const send = XMLHttpRequest.prototype.send;
- XMLHttpRequest.prototype.send = function (body) {
- if (this.__method !== 'GET') {
- return send.call(this, body);
- }
-
- window.__heldReloads.push(() => send.call(this, body));
- };
- })()
- JS);
- $page->script('window.__heldRequests[0]()');
- waitForCondition($page, 'window.__heldReloads.length === 1');
+ waitForCondition($page, 'window.__answeredRequests === 1');
expect(calendarDragCellOf($page, $first))->toBe("calendar-slot-{$key}-13");
- $page->script('window.__heldReloads.splice(0).forEach((release) => release())');
+ $page->script('window.__heldRequests[0]()');
+ waitForCondition($page, 'window.__answeredRequests === 2');
waitForGone($page, '@calendar-grid[aria-busy]');
+ waitForCount($page, '@calendar-reschedule-success-toast', 2);
waitFor($page, "@calendar-slot-{$key}-13 @calendar-post-{$first->id}");
waitFor($page, "@calendar-slot-{$key}-14 @calendar-post-{$second->id}");
@@ -2827,7 +2816,7 @@ test('an older move refused by the server and answered after a newer one still s
waitForCondition($page, 'window.__heldRequests.length === 2');
$page->script('window.__heldRequests[1]()');
- waitFor($page, '@calendar-reschedule-success-toast');
+ waitForCondition($page, 'window.__answeredRequests === 1');
$first->forceFill(['status' => PostStatus::PendingApproval])->saveQuietly();
$page->script('window.__heldRequests[0]()');
waitFor($page, '@calendar-reschedule-error-toast');
diff --git a/tests/Browser/ChangelogTest.php b/tests/Browser/ChangelogTest.php
index 236d8d706..1a14c7f0a 100644
--- a/tests/Browser/ChangelogTest.php
+++ b/tests/Browser/ChangelogTest.php
@@ -18,7 +18,7 @@ function waitForChangelogViews(mixed $page, User $user, int $count): void
function waitForChangelogReaction(mixed $page, ChangelogEntry $entry, ?Reaction $reaction): void
{
- waitForDatabase($page, fn () => ChangelogEntryView::where('changelog_entry_id', $entry->id)->value('reaction') === $reaction?->value);
+ waitForDatabase($page, fn () => ChangelogEntryView::where('changelog_entry_id', $entry->id)->first()?->reaction === $reaction);
}
function createChangelogUser(array $attributes = []): User
diff --git a/tests/Browser/ChannelMetricsCardTest.php b/tests/Browser/ChannelMetricsCardTest.php
index 82e4f62e1..1f7472398 100644
--- a/tests/Browser/ChannelMetricsCardTest.php
+++ b/tests/Browser/ChannelMetricsCardTest.php
@@ -215,7 +215,7 @@ test('presets swap the chart series and the selected preset and period survive a
$page->click('@insights-post-type-filter');
waitFor($page, '@insights-post-type-option-instagram_reel');
$page->click('@insights-post-type-option-instagram_reel');
- waitForCondition($page, 'new URLSearchParams(location.search).getAll("types[]").includes("instagram_reel")');
+ waitForCondition($page, '[...new URLSearchParams(location.search)].some(([key, value]) => key.startsWith("types[") && value === "instagram_reel")');
waitForState($page, '@insights-metrics-chart', 'true');
waitForState($page, '@insights-preset-audience_growth', "element.getAttribute('aria-pressed') === 'true'");
waitForState($page, '@insights-metrics-mode-both', "element.getAttribute('aria-pressed') === 'true'");
diff --git a/tests/Browser/ComposerAutosaveTest.php b/tests/Browser/ComposerAutosaveTest.php
index 486d1971e..b37b5e0c9 100644
--- a/tests/Browser/ComposerAutosaveTest.php
+++ b/tests/Browser/ComposerAutosaveTest.php
@@ -471,7 +471,7 @@ test('resuming an unfinished post keeps its thread replies', function () {
waitFor($page, '@thread-reply-0');
$page->fill('@thread-reply-0', 'Kept reply');
$draft = composerAutosaveJs($user, $workspace);
- waitForCondition($page, "{$draft}?.overrides?.['{$bluesky->id}']?.meta?.thread_replies?.[0] === 'Kept reply'");
+ waitForCondition($page, "{$draft}?.overrides?.['{$bluesky->id}']?.meta?.thread_replies?.[0]?.text === 'Kept reply'");
closeComposerForAutosave($page);
openComposerForAutosave($page);
diff --git a/tests/Browser/ComposerChannelSettingsTest.php b/tests/Browser/ComposerChannelSettingsTest.php
index 83f7d73fd..2f999369e 100644
--- a/tests/Browser/ComposerChannelSettingsTest.php
+++ b/tests/Browser/ComposerChannelSettingsTest.php
@@ -640,8 +640,9 @@ test('save and link keeps a pending reel pending for a member who needs approval
fakeChannelSettingsApis();
$video = [['id' => (string) Str::uuid(), 'type' => 'video', 'path' => 'medias/clip.mp4', 'url' => 'https://example.com/clip.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'clip.mp4']];
$post = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramReel, $video);
- $post->workspace->members()->updateExistingPivot($post->user_id, membershipPivot('approval'));
- $post->update(['status' => Status::PendingApproval, 'scheduled_at' => now()->addDay()]);
+ $requester = workspaceMember($post->workspace, 'approval');
+ $post->update(['user_id' => $requester->id, 'approval_requested_by' => $requester->id, 'status' => Status::PendingApproval, 'scheduled_at' => now()->addDay()]);
+ $this->actingAs($requester);
$page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitFor($page, '@instagram-music-add');
diff --git a/tests/Browser/ComposerSharedDataTest.php b/tests/Browser/ComposerSharedDataTest.php
index 525f45e96..7d3631715 100644
--- a/tests/Browser/ComposerSharedDataTest.php
+++ b/tests/Browser/ComposerSharedDataTest.php
@@ -227,6 +227,7 @@ test('editing a post shows a server media error on the item it belongs to', func
$page = visit(route('app.posts.index', ['edit' => $post->id]));
waitForCount($page, '[data-testid$="-media-item"]', 2);
+ $post->update(['media' => [$post->media[0]]]);
$media->last()->delete();
$page->click('@composer-save-draft');
diff --git a/tests/Browser/ComposerUnsavedChangesTest.php b/tests/Browser/ComposerUnsavedChangesTest.php
index 68aeb75f7..24d1010ea 100644
--- a/tests/Browser/ComposerUnsavedChangesTest.php
+++ b/tests/Browser/ComposerUnsavedChangesTest.php
@@ -713,8 +713,9 @@ test('saving an edited post after keeping it on back leaves the list page restor
waitForGone($page, '@unsaved-changes-dialog');
$page->click('@composer-save-draft');
waitForGone($page, '@post-composer-dialog');
+ $listUrl = json_encode($page->script('location.href'));
$page->script("document.querySelector('[data-testid=\"sidebar-logo\"]').click()");
- waitForCondition($page, "location.pathname !== '{$listPath}'");
+ waitForCondition($page, "location.href !== {$listUrl}");
$page->back();
waitFor($page, "@post-edit-{$post->id}");
diff --git a/tests/Browser/ComposerXPollTest.php b/tests/Browser/ComposerXPollTest.php
index 1c0c051ed..635af78c6 100644
--- a/tests/Browser/ComposerXPollTest.php
+++ b/tests/Browser/ComposerXPollTest.php
@@ -454,7 +454,7 @@ test('a poll picked while x was the only network turns back into a post when ano
$page->click("@composer-account-option-{$linkedIn->id}")
->click('@composer-header');
waitForGone($page, "@composer-account-option-{$linkedIn->id}");
- waitFor($page, '@composer-file-input');
+ waitForState($page, '@composer-file-input', 'true');
$page->fill('@composer-base-content', 'Tabs or spaces?');
$page->script(<<<JS
(() => {
@@ -513,7 +513,7 @@ test('poll is disabled while a file is still uploading to the card', function ()
$png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$uploadUrl = route('app.media.store-chunked', absolute: false);
$page = openXPollComposer($post);
- waitFor($page, "@composer-{$id}-file-input");
+ waitForState($page, "@composer-{$id}-file-input", 'true');
$page->script(<<<JS
(() => {
diff --git a/tests/Browser/ConnectChannelDialogTest.php b/tests/Browser/ConnectChannelDialogTest.php
index 167d6dee1..2c07515ac 100644
--- a/tests/Browser/ConnectChannelDialogTest.php
+++ b/tests/Browser/ConnectChannelDialogTest.php
@@ -237,7 +237,7 @@ test('the instagram step offers the instagram login and facebook cards side by s
$page->assertSeeIn('@instagram-connect-standalone-requirements', trans('accounts.instagram_connect.convert_hint'))
->assertVisible('@instagram-connect-facebook-requirements')
->click('@instagram-connect-facebook-requirements-toggle');
- waitForGone($page, '@instagram-connect-facebook-requirements');
+ waitForState($page, '@instagram-connect-facebook-requirements', 'element.hidden');
$page->assertMissing('@instagram-connect-facebook-requirements')
->assertVisible('@instagram-connect-standalone-requirements');
diff --git a/tests/Browser/CreateIdeasBoardTest.php b/tests/Browser/CreateIdeasBoardTest.php
index fd4fbb24a..d9c637d17 100644
--- a/tests/Browser/CreateIdeasBoardTest.php
+++ b/tests/Browser/CreateIdeasBoardTest.php
@@ -153,6 +153,31 @@ test('dragging a card onto an empty column moves it there', function () {
$page->assertNoJavaScriptErrors();
});
+test('a move that cannot reach the server says so and puts the card back', function () {
+ [$user, $workspace, $stages] = createIdeasBoardSetup();
+ $a = createIdeasBoardIdea($workspace, $user, $stages['todo'], 0, 'Idea A');
+ $this->actingAs($user);
+
+ $page = visit(route('app.create.ideas.index'));
+ waitFor($page, "@idea-card-{$a->id}");
+ $page->script(<<<'JS'
+ (() => {
+ const send = XMLHttpRequest.prototype.send;
+ XMLHttpRequest.prototype.send = function () {
+ XMLHttpRequest.prototype.send = send;
+ this.dispatchEvent(new ProgressEvent('error'));
+ this.dispatchEvent(new ProgressEvent('loadend'));
+ };
+ })()
+ JS);
+ $page->drag("@idea-card-{$a->id}", "@idea-column-{$stages['done']->id}");
+ waitFor($page, '@ideas-move-error-toast');
+ waitFor($page, "@idea-column-{$stages['todo']->id} @idea-card-{$a->id}");
+
+ $page->assertNoJavaScriptErrors();
+ expect($a->refresh()->idea_stage_id)->toBe($stages['todo']->id);
+});
+
test('a new stage is created on enter and nothing is created on escape', function () {
[$user, $workspace] = createIdeasBoardSetup();
$this->actingAs($user);
@@ -357,6 +382,99 @@ test('a drop made while a move is in flight is applied after the first move comp
$page->assertNoJavaScriptErrors();
});
+test('several drops made while a move is in flight are all saved, in order, after it completes', function () {
+ [$user, $workspace, $stages] = createIdeasBoardSetup();
+ $a = createIdeasBoardIdea($workspace, $user, $stages['todo'], 0, 'Idea A');
+ $b = createIdeasBoardIdea($workspace, $user, $stages['todo'], 1, 'Idea B');
+ $c = createIdeasBoardIdea($workspace, $user, $stages['todo'], 2, 'Idea C');
+ $this->actingAs($user);
+
+ $page = visit(route('app.create.ideas.index'));
+ waitFor($page, "@idea-card-{$c->id}");
+ $page->script(<<<'JS'
+ (() => {
+ const open = XMLHttpRequest.prototype.open;
+ const send = XMLHttpRequest.prototype.send;
+ window.__ideaMoves = [];
+ XMLHttpRequest.prototype.open = function (method, url, ...rest) {
+ this.__ideaMove = method.toUpperCase() === 'PUT' && String(url).endsWith('/move');
+ return open.call(this, method, url, ...rest);
+ };
+ XMLHttpRequest.prototype.send = function (body) {
+ if (!this.__ideaMove) return send.call(this, body);
+ window.__ideaMoves.push(body);
+ if (window.__ideaMoves.length === 1) {
+ window.__releaseIdeaMove = () => send.call(this, body);
+ return;
+ }
+ return send.call(this, body);
+ };
+ })();
+ JS);
+
+ $page->drag("@idea-card-{$a->id}", "@idea-column-{$stages['done']->id}");
+ waitForCondition($page, 'window.__ideaMoves.length === 1');
+ $page->drag("@idea-card-{$b->id}", "@idea-column-{$stages['done']->id}");
+ waitForState($page, "@idea-column-{$stages['done']->id} [data-idea-id=\"{$b->id}\"]", 'true');
+ $page->drag("@idea-card-{$c->id}", "@idea-column-{$stages['done']->id}");
+ waitForState($page, "@idea-column-{$stages['done']->id} [data-idea-id=\"{$c->id}\"]", 'true');
+
+ $page->script('window.__releaseIdeaMove()');
+ waitForDatabase($page, fn (): bool => $c->refresh()->idea_stage_id === $stages['done']->id);
+
+ $order = $page->script("[...document.querySelectorAll('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-idea-id]')].map((el) => el.dataset.ideaId)");
+ expect($page->script('window.__ideaMoves.length'))->toBe(3)
+ ->and(Idea::whereKey([$a->id, $b->id, $c->id])->pluck('idea_stage_id')->unique()->all())->toBe([$stages['done']->id])
+ ->and(Idea::where('idea_stage_id', $stages['done']->id)->orderBy('position')->pluck('id')->all())->toBe($order);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a card dropped twice while a move is in flight is saved where it was dropped last', function () {
+ [$user, $workspace, $stages] = createIdeasBoardSetup();
+ $a = createIdeasBoardIdea($workspace, $user, $stages['todo'], 0, 'Idea A');
+ $b = createIdeasBoardIdea($workspace, $user, $stages['todo'], 1, 'Idea B');
+ $this->actingAs($user);
+
+ $page = visit(route('app.create.ideas.index'));
+ waitFor($page, "@idea-card-{$b->id}");
+ $page->script(<<<'JS'
+ (() => {
+ const open = XMLHttpRequest.prototype.open;
+ const send = XMLHttpRequest.prototype.send;
+ window.__ideaMoves = [];
+ XMLHttpRequest.prototype.open = function (method, url, ...rest) {
+ this.__ideaMove = method.toUpperCase() === 'PUT' && String(url).endsWith('/move');
+ return open.call(this, method, url, ...rest);
+ };
+ XMLHttpRequest.prototype.send = function (body) {
+ if (!this.__ideaMove) return send.call(this, body);
+ window.__ideaMoves.push(body);
+ if (window.__ideaMoves.length === 1) {
+ window.__releaseIdeaMove = () => send.call(this, body);
+ return;
+ }
+ return send.call(this, body);
+ };
+ })();
+ JS);
+
+ $page->drag("@idea-card-{$b->id}", "@idea-column-{$stages['done']->id}");
+ waitForCondition($page, 'window.__ideaMoves.length === 1');
+ $page->drag("@idea-card-{$a->id}", "@idea-column-{$stages['in_progress']->id}");
+ waitForState($page, "@idea-column-{$stages['in_progress']->id} [data-idea-id=\"{$a->id}\"]", 'true');
+ $page->drag("@idea-card-{$a->id}", "@idea-column-{$stages['done']->id}");
+ waitForState($page, "@idea-column-{$stages['done']->id} [data-idea-id=\"{$a->id}\"]", 'true');
+
+ $page->script('window.__releaseIdeaMove()');
+ waitForDatabase($page, fn (): bool => $a->refresh()->idea_stage_id === $stages['done']->id);
+
+ waitForState($page, "@idea-column-{$stages['done']->id} [data-idea-id=\"{$a->id}\"]", 'true');
+
+ expect($page->script('window.__ideaMoves.length'))->toBe(2)
+ ->and($b->refresh()->idea_stage_id)->toBe($stages['done']->id);
+ $page->assertNoJavaScriptErrors();
+});
+
test('move to stage works on a filtered board and appends to the end of the stage', function () {
[$user, $workspace, $stages] = createIdeasBoardSetup();
$label = WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id]);
diff --git a/tests/Browser/InsightsChannelFilterTest.php b/tests/Browser/InsightsChannelFilterTest.php
index 9c5b16235..2b1c9d1c8 100644
--- a/tests/Browser/InsightsChannelFilterTest.php
+++ b/tests/Browser/InsightsChannelFilterTest.php
@@ -155,10 +155,10 @@ test('the follower bar tooltip lists where the channel started and the toolbar f
->assertNoJavaScriptErrors();
$page->resize(390, 844);
- waitFor($page, '@insights-range-custom');
+ waitFor($page, '@insights-range-mobile-trigger');
- $page->assertScript('(() => { const group = document.querySelector("[data-testid=insights-range-presets] [role=group]"); return group.scrollWidth <= group.clientWidth + 1; })()', true)
- ->assertScript('document.querySelector("[data-testid=insights-range-custom]").getBoundingClientRect().right <= window.innerWidth', true)
+ $page->assertMissing('@insights-range-custom')
+ ->assertScript('document.querySelector("[data-testid=insights-range-mobile-trigger]").getBoundingClientRect().right <= window.innerWidth', true)
->assertScript('document.querySelector("[data-testid=analytics-channel-filter]").getBoundingClientRect().right <= window.innerWidth', true)
->assertScript('document.documentElement.scrollWidth <= window.innerWidth + 2', true)
->assertScript('Array.from(document.querySelectorAll("[data-testid=analytics-account-name]")).every((name) => name.offsetParent === null)', true)
diff --git a/tests/Browser/LabelRowMenuTest.php b/tests/Browser/LabelRowMenuTest.php
index a62a720dd..efcc76227 100644
--- a/tests/Browser/LabelRowMenuTest.php
+++ b/tests/Browser/LabelRowMenuTest.php
@@ -148,7 +148,7 @@ test('a long labels list starts at the top and scrolls normally', function () {
$this->actingAs($user);
$page = visit(route('app.labels.index'));
- waitFor($page, "@label-row-{$label->id}");
+ waitFor($page, '[data-testid^="label-row-"]');
expect($page->script(<<<'JS'
(() => {
diff --git a/tests/Browser/LinkedInCommentTest.php b/tests/Browser/LinkedInCommentTest.php
index 4be1b2af2..39a9c090c 100644
--- a/tests/Browser/LinkedInCommentTest.php
+++ b/tests/Browser/LinkedInCommentTest.php
@@ -80,7 +80,7 @@ test('shift enter breaks the line in a linkedin caption and comment instead of o
waitFor($page, $caption);
$page->keys($caption, 'End')->keys($caption, 'Shift+Enter');
- waitForState($page, $caption, "element.innerHTML.includes('<br')");
+ waitForState($page, $caption, "element.value.includes('\\n')");
$page->assertMissing('@thread-reply-0')
->assertPresent('@thread-start')
diff --git a/tests/Browser/PostComposerDialogTest.php b/tests/Browser/PostComposerDialogTest.php
index 6a5c83ec4..c13906bb5 100644
--- a/tests/Browser/PostComposerDialogTest.php
+++ b/tests/Browser/PostComposerDialogTest.php
@@ -584,8 +584,10 @@ test('a label created from the empty label picker of the global composer is list
$label = $workspace->labels()->sole();
- $page->click('@composer-tags-trigger')
- ->assertAttribute("@composer-label-checkbox-{$label->id}", 'data-state', 'checked')
+ waitForGone($page, '@composer-label-new-name');
+ $page->click('@composer-tags-trigger');
+ waitFor($page, "@composer-label-checkbox-{$label->id}");
+ $page->assertAttribute("@composer-label-checkbox-{$label->id}", 'data-state', 'checked')
->assertNoJavaScriptErrors();
});
@@ -1357,7 +1359,7 @@ test('select all picks only the channels the search shows, and the last used sho
->click('@composer-save-draft');
waitForGone($page, '@post-composer-dialog');
- waitForComposerReady($page, 'posts-new-post');
+ waitFor($page, '@posts-new-post');
$page->click('@posts-new-post');
waitForComposerReady($page, 'composer-last-used');
$page->click('@composer-last-used')
diff --git a/tests/Browser/PostNotesTest.php b/tests/Browser/PostNotesTest.php
index ff45d78a6..c681eabf6 100644
--- a/tests/Browser/PostNotesTest.php
+++ b/tests/Browser/PostNotesTest.php
@@ -2,15 +2,20 @@
declare(strict_types=1);
+use App\Enums\User\Locale;
use App\Mail\PostNoteAdded;
+use App\Mail\PostNoteMentioned;
use App\Models\Post;
use App\Models\PostNote;
+use App\Models\PostNoteReaction;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
+use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Mail;
+use Illuminate\Support\Str;
-test('adding a note from the popover shows it and emails the other members', function () {
+test('a note mentions a teammate picked from the list and takes reactions', function () {
Mail::fake();
$user = User::factory()->create();
@@ -18,7 +23,7 @@ test('adding a note from the popover shows it and emails the other members', fun
$workspace->members()->attach($user->id, membershipPivot('admin'));
$user->update(['current_workspace_id' => $workspace->id]);
- $teammate = User::factory()->create();
+ $teammate = User::factory()->create(['name' => 'Bia Lima']);
$workspace->members()->attach($teammate->id, membershipPivot('member'));
$post = Post::factory()->create([
@@ -37,23 +42,260 @@ test('adding a note from the popover shows it and emails the other members', fun
$page->assertScript('(() => { const field = document.querySelector("[data-testid=note-composer]").getBoundingClientRect(); const send = document.querySelector("[data-testid=note-send]").getBoundingClientRect(); return Math.abs((field.top + field.height / 2) - (send.top + send.height / 2)) <= 1 && send.right <= field.right; })()', true);
- $page->fill('@note-input', 'Please check the @image before Friday');
+ $page->fill('@note-input', 'Please check the @image, @bi');
+ waitForOpen($page, '@note-mention-list');
+ waitForText($page, '@note-mention-option', 'Bia Lima');
+ $page->assertScript('(() => { const list = document.querySelector("[data-testid=note-mention-list]").getBoundingClientRect(); return list.top >= 0 && list.bottom <= window.innerHeight; })()', true);
+ $page->click('@note-mention-option');
+ waitForGone($page, '@note-mention-list');
+ waitForEditorText($page, '@note-input', 'Please check the @image, @Bia Lima');
+
$page->click('@note-send');
- waitFor($page, '@note-body');
+ waitFor($page, '@note-mention');
+
+ waitForText($page, '@note-body', 'Please check the @image, @Bia Lima');
+ waitForText($page, '@note-mention', '@Bia Lima');
+
+ expect(PostNote::query()->where('post_id', $post->id)->value('body'))
+ ->toBe("Please check the @image, @[user:{$teammate->id}]");
+
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($teammate->email));
+ Mail::assertNotQueued(PostNoteAdded::class);
+
+ $page->click('@note-react');
+ waitForOpen($page, '[data-slot=popover-content]:has(@emoji-picker-option)');
+ $page->click('@emoji-picker-option');
+ waitFor($page, '[data-testid^=note-reaction-]');
+ waitForState($page, '[data-testid^=note-reaction-]', "element.getAttribute('aria-pressed') === 'true' && element.textContent.includes('1')");
+
+ expect(PostNoteReaction::query()->where('user_id', $user->id)->count())->toBe(1);
+
+ $page->click('[data-testid^=note-reaction-]');
+ waitForGone($page, '[data-testid^=note-reaction-]');
+
+ $page->assertNoJavaScriptErrors();
+
+ expect(PostNoteReaction::query()->count())->toBe(0);
+});
+
+test('the mention list works from the keyboard, says when nobody matches, an edit keeps the mentions and Esc cancels it', function () {
+ Mail::fake();
+
+ $user = User::factory()->create(['name' => 'Paulo Castellano']);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+
+ $ana = User::factory()->create(['name' => 'Ana Souza']);
+ $bia = User::factory()->create(['name' => 'Bia Lima']);
+ $workspace->members()->attach($ana->id, membershipPivot('member'));
+ $workspace->members()->attach($bia->id, membershipPivot('member'));
+
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitFor($page, '@note-input');
+
+ $page->hover('@note-input');
+ $page->fill('@note-input', '@');
+ waitForOpen($page, '@note-mention-list');
+ waitForCount($page, '@note-mention-option', 2);
+ waitForState($page, '@note-input', "element.getAttribute('aria-expanded') === 'true'");
+ $page->keys('@note-input', ['ArrowDown', 'ArrowDown']);
+ waitForState($page, '@note-mention-list [aria-selected=true]', "element.textContent.includes('Bia Lima')");
+ $page->keys('@note-input', 'Enter');
+ waitForGone($page, '@note-mention-list');
+ waitForEditorText($page, '@note-input', '@Bia Lima');
+
+ $page->typeSlowly('@note-input', 'hi @zzz', 10);
+ waitForText($page, '@note-mention-list', 'No teammate matches');
+ $page->keys('@note-input', 'Escape');
+ waitForGone($page, '@note-mention-list');
+ waitForEditorText($page, '@note-input', '@Bia Lima hi @zzz');
+
+ $page->keys('@note-input', 'Enter');
+ waitFor($page, '@note-mention');
+
+ $note = PostNote::query()->where('post_id', $post->id)->sole();
+ expect($note->body)->toBe("@[user:{$bia->id}] hi @zzz");
+
+ $page->click('@note-actions');
+ $page->click('@note-edit');
+ waitFor($page, '@note-edit-input');
+ waitForEditorText($page, '@note-edit-input', '@Bia Lima hi @zzz');
+
+ $page->typeSlowly('@note-edit-input', ' and @an', 10);
+ waitForText($page, '@note-mention-option', 'Ana Souza');
+ $page->keys('@note-edit-input', 'Tab');
+ waitForGone($page, '@note-mention-list');
+ $page->click('@note-edit-save');
+ waitForCount($page, '@note-mention', 2);
- $page->assertScript('(() => { const list = document.querySelector("[data-testid=notes-list]"); return list.scrollWidth <= list.clientWidth; })()', true);
+ $page->click('@note-actions');
+ $page->click('@note-edit');
+ waitFor($page, '@note-edit-input');
+ $page->typeSlowly('@note-edit-input', ' discarded', 10);
+ $page->keys('@note-edit-input', 'Escape');
+ waitForGone($page, '@note-edit-input');
+
+ $page->assertNoJavaScriptErrors();
+
+ expect($note->fresh()->body)->toBe("@[user:{$bia->id}] hi @zzz and @[user:{$ana->id}]");
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($ana->email));
+});
+
+test('hovering a mention shows who it is, yourself included: photo, name and their local time', function () {
+ $user = User::factory()->create(['name' => 'Paulo Castellano', 'time_format' => '24h']);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+
+ $admin = workspaceMember($workspace, 'admin', ['name' => 'Ana Souza', 'timezone' => 'Asia/Tokyo']);
+ $member = workspaceMember($workspace, 'member', ['name' => 'Bia Lima', 'timezone' => 'America/Sao_Paulo']);
+ $formerMember = User::factory()->create(['name' => 'Caio Former']);
+ $admin->addMedia(UploadedFile::fake()->image('avatar.jpg', 64, 64), 'avatar');
+ $user->addMedia(UploadedFile::fake()->image('me.jpg', 64, 64), 'avatar');
+ $photoUrl = json_encode($admin->fresh()->photo_url);
+ $myPhotoUrl = json_encode($user->fresh()->photo_url);
+
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ PostNote::factory()->create([
+ 'post_id' => $post->id,
+ 'user_id' => $user->id,
+ 'body' => "@[user:{$admin->id}] @[user:{$member->id}] @[user:{$formerMember->id}] @[user:{$user->id}]",
+ ])->mentions()->attach([$admin->id, $member->id, $formerMember->id, $user->id]);
- $page->assertSeeIn('@note-body', 'Please check the @image before Friday')
- ->assertVisible('@note-actions')
- ->assertMissing('@note-react')
- ->assertMissing('@note-reply')
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitForOpen($page, "@post-notes-section-{$post->id}");
+ waitForCount($page, '@note-mention', 4);
+ waitForText($page, '@note-body', '@Ana Souza @Bia Lima @Caio Former @Paulo Castellano');
+
+ $tokyoTimes = json_encode([now('Asia/Tokyo')->format('H:i'), now('Asia/Tokyo')->addMinute()->format('H:i')]);
+
+ $page->hover('[data-testid=note-mention]:nth-child(1)');
+ waitForOpen($page, '@note-mention-card');
+ waitFor($page, '@note-mention-card-time');
+ waitForState($page, '@note-mention-card img', "element.getAttribute('src') === {$photoUrl}");
+ waitForText($page, '@note-mention-card-name', 'Ana Souza');
+ waitForState($page, '@note-mention-card-time', "{$tokyoTimes}.some((time) => element.textContent.includes(time + ' local time'))");
+
+ $page->hover('@note-body');
+ waitForGone($page, '@note-mention-card');
+ $page->hover('[data-testid=note-mention]:nth-child(2)');
+ waitForText($page, '@note-mention-card-name', 'Bia Lima');
+ waitFor($page, '@note-mention-card-time');
+ $page->assertMissing('@note-mention-card img');
+
+ $page->hover('@note-body');
+ waitForGone($page, '@note-mention-card');
+ $page->hover('[data-testid=note-mention]:nth-child(3)');
+ waitForText($page, '@note-mention-card-name', 'Caio Former');
+ $page->assertMissing('@note-mention-card-time');
+
+ $page->hover('@note-body');
+ waitForGone($page, '@note-mention-card');
+ $page->hover('[data-testid=note-mention]:nth-child(4)');
+ waitForText($page, '@note-mention-card-name', 'Paulo Castellano');
+ waitForState($page, '@note-mention-card img', "element.getAttribute('src') === {$myPhotoUrl}");
+ $page->assertVisible('@note-mention-card-time')
->assertNoJavaScriptErrors();
+});
- expect(PostNote::query()->where('post_id', $post->id)->value('body'))
- ->toBe('Please check the @image before Friday');
+test('@all is offered first in the mention list, in the reader\'s language, and mentions everyone on the post', function () {
+ Mail::fake();
+
+ $user = User::factory()->create(['name' => 'Paulo Castellano', 'locale' => Locale::PortugueseBrazil]);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $teammate = workspaceMember($workspace, 'member', ['name' => 'Bia Lima']);
+
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+
+ $this->actingAs($user);
- Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($teammate->email));
- Mail::assertNotQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($user->email));
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitForOpen($page, "@post-notes-section-{$post->id}");
+
+ $page->fill('@note-input', '@');
+ waitForOpen($page, '@note-mention-list');
+ waitForState($page, '[data-testid=note-mention-list] [role=option]', "element.dataset.testid === 'note-mention-option-everyone' && element.textContent.includes('@todos')");
+
+ $page->fill('@note-input', 'Revisem @tod');
+ waitForCount($page, '[data-testid=note-mention-list] [role=option]', 1);
+ $page->assertCount('@note-mention-option', 0)
+ ->assertVisible('@note-mention-option-everyone');
+ $page->keys('@note-input', 'Enter');
+ waitForGone($page, '@note-mention-list');
+ waitForEditorText($page, '@note-input', 'Revisem @todos');
+
+ $page->keys('@note-input', 'Enter');
+ waitForText($page, '@note-mention-everyone', '@todos');
+ $page->assertNoJavaScriptErrors();
+
+ expect(PostNote::query()->where('post_id', $post->id)->value('body'))->toBe('Revisem @[everyone]');
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($teammate->email));
+});
+
+test('the mention list follows the caret and the mouse, and narrows to a longer name as you type', function () {
+ $user = User::factory()->create(['name' => 'Paulo Castellano']);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ workspaceMember($workspace, 'member', ['name' => 'Ana']);
+ workspaceMember($workspace, 'member', ['name' => 'Ana Lima']);
+
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitForOpen($page, "@post-notes-section-{$post->id}");
+
+ $page->fill('@note-input', '@Ana');
+ waitForOpen($page, '@note-mention-list');
+ waitForCount($page, '@note-mention-option', 2);
+
+ $page->hover('[data-testid=note-mention-option]:nth-child(1)');
+ $page->hover('[data-testid=note-mention-option]:nth-child(2)');
+ waitForState($page, '@note-mention-list [aria-selected=true]', "element.textContent.includes('Ana Lima')");
+
+ $page->typeSlowly('@note-input', ' L', 10);
+ waitForCount($page, '@note-mention-option', 1);
+ waitForText($page, '@note-mention-option', 'Ana Lima');
+ $page->keys('@note-input', 'Enter');
+ waitForGone($page, '@note-mention-list');
+ waitForEditorText($page, '@note-input', '@Ana Lima');
+
+ $page->fill('@note-input', 'hello @an');
+ waitForOpen($page, '@note-mention-list');
+ $page->keys('@note-input', ['ArrowLeft', 'ArrowLeft', 'ArrowLeft']);
+ waitForGone($page, '@note-mention-list');
+ $page->keys('@note-input', ['ArrowRight', 'ArrowRight', 'ArrowRight']);
+ waitForOpen($page, '@note-mention-list');
+ $page->keys('@note-input', 'Escape');
+ waitForGone($page, '@note-mention-list');
+ waitForEditorText($page, '@note-input', 'hello @an');
+
+ $page->assertNoJavaScriptErrors();
+
+ expect(PostNote::query()->count())->toBe(0);
});
test('the note composer enables send only with text and sends on Enter but not Shift+Enter', function () {
@@ -86,11 +328,13 @@ test('the note composer enables send only with text and sends on Enter but not S
$page->assertDisabled('@note-send');
$page->fill('@note-input', 'First line');
+ waitForEditorText($page, '@note-input', 'First line');
+ waitForState($page, '@note-send', '! element.disabled');
$page->assertEnabled('@note-send');
$page->keys('@note-input', ['Shift+Enter']);
-
- expect($page->script("document.querySelector('[data-testid=\"note-input\"]').value"))->toBe("First line\n");
+ waitFor($page, '@note-input br');
+ waitForEditorText($page, '@note-input', 'First line');
expect(PostNote::query()->where('post_id', $post->id)->exists())->toBeFalse();
$page->keys('@note-input', ['Enter']);
@@ -98,13 +342,65 @@ test('the note composer enables send only with text and sends on Enter but not S
waitForText($page, "@post-notes-count-{$post->id}", '1');
$page->assertSeeIn('@note-body', 'First line')
- ->assertValue('@note-input', '')
->assertDisabled('@note-send')
->assertSeeIn("@post-notes-count-{$post->id}", '1')
->assertVisible("@post-notes-filled-icon-{$post->id}")
->assertNoJavaScriptErrors();
- expect(PostNote::query()->where('post_id', $post->id)->value('body'))->toBe('First line');
+ expect(PostNote::query()->where('post_id', $post->id)->pluck('body')->all())->toBe(['First line']);
+});
+
+test('text typed while a note is sending stays in the composer without the sent text', function () {
+ Mail::fake();
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitFor($page, '@notes-empty');
+
+ $holdRequests = <<<'JS'
+ (() => {
+ const send = XMLHttpRequest.prototype.send;
+ const held = [];
+ XMLHttpRequest.prototype.send = function (body) {
+ held.push(() => send.call(this, body));
+ };
+ window.__release = () => {
+ XMLHttpRequest.prototype.send = send;
+ held.splice(0).forEach((go) => go());
+ };
+ })()
+ JS;
+
+ $page->script($holdRequests);
+ $page->fill('@note-input', 'Sent part');
+ waitForEditorText($page, '@note-input', 'Sent part');
+ $page->keys('@note-input', ['Enter']);
+ $page->typeSlowly('@note-input', ' typed after', 10);
+ waitForEditorText($page, '@note-input', 'Sent part typed after');
+ $page->script('window.__release()');
+ waitForText($page, '@note-body', 'Sent part');
+ waitForEditorText($page, '@note-input', 'typed after');
+
+ $page->keys('@note-input', ['ControlOrMeta+a', 'Backspace']);
+ $page->typeSlowly('@note-input', 'Second note', 10);
+ waitForEditorText($page, '@note-input', 'Second note');
+ $page->script($holdRequests);
+ $page->keys('@note-input', ['Enter', 'Backspace']);
+ $page->typeSlowly('@note-input', 's', 10);
+ waitForEditorText($page, '@note-input', 'Second nots');
+ $page->script('window.__release()');
+ waitForCount($page, '@note-body', 2);
+ waitForEditorText($page, '@note-input', 'Second nots');
+ $page->assertNoJavaScriptErrors();
+
+ expect(PostNote::query()->where('post_id', $post->id)->oldest('id')->pluck('body')->all())->toBe(['Sent part', 'Second note']);
});
test('a note timestamp follows the display zone of the list', function () {
@@ -156,6 +452,329 @@ test('a note created an hour ago reads as past for a user whose zone is not the
$page->assertNoJavaScriptErrors();
});
+test('a mention of someone who no longer exists reads as unknown, opens no card, and stays unknown in its edit', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $goneId = Str::uuid()->toString();
+ $unknown = __('notes.mention_unknown');
+ PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $user->id, 'body' => "ask @[user:{$goneId}]"]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitForText($page, '@note-body', "ask @{$unknown}");
+ waitForText($page, '@note-mention-unknown', "@{$unknown}");
+ $page->assertMissing('@note-mention');
+
+ $page->click('@note-actions');
+ $page->click('@note-edit');
+ waitForEditorText($page, '@note-edit-input', "ask @{$unknown}");
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('scrolling up the thread loads older notes, reacting or sending keeps them, and a link to an older note loads its pages and highlights it', function () {
+ Mail::fake();
+ config(['app.pagination.default' => 8]);
+
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $notes = collect(range(1, 20))->map(fn (int $number): PostNote => PostNote::factory()->create([
+ 'post_id' => $post->id,
+ 'user_id' => $user->id,
+ 'body' => $number === 1 ? 'The very first note' : "Note number {$number}",
+ 'created_at' => now()->subMinutes(30 - $number),
+ 'updated_at' => now()->subMinutes(30 - $number),
+ ]));
+ $olderNote = $notes[5];
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitForCount($page, '@note-item', 8);
+ $page->assertSeeIn('@notes-list', 'Note number 20')
+ ->assertDontSeeIn('@notes-list', 'Note number 6');
+
+ $page->script("document.querySelector('[data-testid=\"notes-list\"]').scrollTop = 0");
+ waitForCount($page, '@note-item', 16, '>=');
+ $page->assertSeeIn('@notes-list', 'Note number 6');
+
+ $olderNoteSelector = "[data-note-id=\"{$olderNote->id}\"]";
+ $page->hover($olderNoteSelector)->click("{$olderNoteSelector} [data-testid=note-react]");
+ waitForOpen($page, '[data-slot=popover-content]:has(@emoji-picker-option)');
+ $page->click('@emoji-picker-option');
+ waitFor($page, "{$olderNoteSelector} [data-testid^=note-reaction-]");
+ $loaded = $page->script("document.querySelectorAll('[data-testid=\"note-item\"]').length");
+ expect($loaded)->toBeGreaterThanOrEqual(16);
+
+ $page->fill('@note-input', 'A brand new note');
+ waitForEditorText($page, '@note-input', 'A brand new note');
+ $page->keys('@note-input', 'Enter');
+ waitForCount($page, '@note-item', $loaded + 1);
+ $page->assertSeeIn('@notes-list', 'A brand new note')
+ ->assertSeeIn('@notes-list', 'Note number 6')
+ ->assertNoJavaScriptErrors();
+
+ $oldest = "[data-note-id=\"{$notes->first()->id}\"]";
+ $linked = visit(route('app.posts.edit', ['post' => $post, 'comment' => $notes->first()->id]));
+ waitForState($linked, $oldest, "element.dataset.highlighted === 'true'");
+ waitForState($linked, $oldest, "(() => { const list = document.querySelector('[data-testid=notes-list]').getBoundingClientRect(); const note = element.getBoundingClientRect(); return note.top >= list.top - 1 && note.bottom <= list.bottom + 1; })()");
+ $linked->assertAttribute($oldest, 'data-highlighted', 'true')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a note repeated by an older page after a new one disappears when deleted, and a refused delete or reaction says so', function () {
+ Mail::fake();
+ config(['app.pagination.default' => 8]);
+
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $notes = collect(range(1, 20))->map(fn (int $number): PostNote => PostNote::factory()->create([
+ 'post_id' => $post->id,
+ 'user_id' => $user->id,
+ 'body' => "Note number {$number}",
+ 'created_at' => now()->subMinutes(30 - $number),
+ 'updated_at' => now()->subMinutes(30 - $number),
+ ]));
+ $boundary = $notes[12];
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitForCount($page, '@note-item', 8);
+ $page->fill('@note-input', 'A brand new note');
+ waitForEditorText($page, '@note-input', 'A brand new note');
+ $page->keys('@note-input', 'Enter');
+ waitForCount($page, '@note-item', 9);
+
+ $page->script("document.querySelector('[data-testid=\"notes-list\"]').scrollTop = 0");
+ waitForText($page, '@notes-list', 'Note number 6');
+ $boundaryNote = "[data-note-id=\"{$boundary->id}\"]";
+ $page->assertCount($boundaryNote, 1);
+
+ $page->hover($boundaryNote)->click("{$boundaryNote} [data-testid=note-actions]");
+ waitFor($page, '@note-delete');
+ $page->click('@note-delete');
+ waitForGone($page, $boundaryNote);
+ $page->assertMissing($boundaryNote);
+ expect($boundary->fresh())->toBeNull();
+
+ $gone = $notes[9];
+ $goneNote = "[data-note-id=\"{$gone->id}\"]";
+ $page->script(<<<'JS'
+ (() => {
+ const send = XMLHttpRequest.prototype.send;
+ XMLHttpRequest.prototype.send = function (body) {
+ this.dispatchEvent(new ProgressEvent('error'));
+ this.dispatchEvent(new ProgressEvent('loadend'));
+ };
+ window.__restoreSend = () => { XMLHttpRequest.prototype.send = send; };
+ })()
+ JS);
+ $page->hover($goneNote)->click("{$goneNote} [data-testid=note-react]");
+ waitForOpen($page, '[data-slot=popover-content]:has(@emoji-picker-option)');
+ $page->click('@emoji-picker-option');
+ waitForText($page, '@note-error-toast', __('notes.errors.not_reacted'));
+ $page->keys('@emoji-picker-option', 'Escape');
+ waitForGone($page, '[data-slot=popover-content]:has(@emoji-picker-option)');
+
+ $page->hover($goneNote)->click("{$goneNote} [data-testid=note-actions]");
+ waitFor($page, '@note-delete');
+ $page->click('@note-delete');
+ waitForText($page, '@note-error-toast', __('notes.errors.not_deleted'));
+ $page->script('window.__restoreSend()');
+ $page->assertPresent($goneNote)->assertNoJavaScriptErrors();
+ expect($gone->fresh())->not->toBeNull();
+});
+
+test('opening another post notes closes the open thread, and closing a thread clears it from the link', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ [$first, $second] = collect(['First post', 'Second post'])->map(function (string $content) use ($workspace, $user): Post {
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => $content]);
+ PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $user->id, 'body' => "A note on {$content}"]);
+
+ return $post;
+ })->all();
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$first->id}");
+ $page->click("@post-notes-trigger-{$first->id}");
+ waitForText($page, "@post-notes-section-{$first->id} @note-body", 'A note on First post');
+ waitForQueryParameter($page, 'notes', $first->id);
+
+ $page->click("@post-notes-trigger-{$second->id}");
+ waitForText($page, "@post-notes-section-{$second->id} @note-body", 'A note on Second post');
+ waitForQueryParameter($page, 'notes', $second->id);
+ waitForState($page, "@post-notes-trigger-{$first->id}", "element.dataset.state === 'closed'");
+ $page->assertAttribute("@post-notes-trigger-{$first->id}", 'data-state', 'closed');
+
+ $page->click("@post-notes-trigger-{$second->id}");
+ waitForCondition($page, "!new URLSearchParams(location.search).has('notes')");
+ waitForState($page, "@post-notes-trigger-{$second->id}", "element.dataset.state === 'closed'");
+ $page->assertAttribute("@post-notes-trigger-{$second->id}", 'data-state', 'closed')
+ ->assertNoJavaScriptErrors();
+});
+
+test('Backspace removes a mention chip whole, leaving no @ behind', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ workspaceMember($workspace, 'member', ['name' => 'Bia Lima']);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitFor($page, '@note-input');
+
+ $page->hover('@note-input');
+ $page->typeSlowly('@note-input', 'Oi @bia', 10);
+ waitForCount($page, '@note-mention-option', 1);
+ $page->keys('@note-input', 'Enter');
+ waitFor($page, '@note-input-mention');
+ $page->keys('@note-input', ['Backspace', 'Backspace']);
+ waitForGone($page, '@note-input-mention');
+ waitForEditorText($page, '@note-input', 'Oi');
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('Enter sends while the mention list finds nobody', function () {
+ Mail::fake();
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ workspaceMember($workspace, 'member', ['name' => 'Bia Lima']);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitFor($page, '@note-input');
+
+ $page->hover('@note-input');
+ $page->typeSlowly('@note-input', 'hi @zzz', 10);
+ waitForText($page, '@note-mention-list', 'No teammate matches');
+ $page->keys('@note-input', 'Enter');
+ waitFor($page, '@note-item');
+ $page->assertSeeIn('@note-body', 'hi @zzz')
+ ->assertNoJavaScriptErrors();
+
+ expect(PostNote::query()->pluck('body')->all())->toBe(['hi @zzz']);
+});
+
+test('a note opened in the editor and saved unchanged keeps every line and mention', function () {
+ Mail::fake();
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $bia = workspaceMember($workspace, 'member', ['name' => 'Bia Lima']);
+ $ana = workspaceMember($workspace, 'member', ['name' => 'Ana Souza']);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $body = "(@[user:{$bia->id}]) and cc:@[user:{$ana->id}]\n\n@[everyone] さん、@[user:{$bia->id}]確認お願いします";
+ $note = PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $user->id, 'body' => $body]);
+ $note->mentions()->attach([$bia->id, $ana->id]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitFor($page, '@note-item');
+ $page->hover('@note-item')->click('@note-actions');
+ waitFor($page, '@note-edit');
+ $page->click('@note-edit');
+ waitForCount($page, '@note-edit-input [data-testid=note-input-mention]', 4);
+ expect($page->script("[...document.querySelectorAll('[data-testid=\"note-edit-input\"] [data-testid=\"note-input-mention\"]')].map((chip) => chip.textContent)"))
+ ->toBe(['@Bia Lima', '@Ana Souza', '@'.__('notes.mention_everyone.word'), '@Bia Lima']);
+
+ $page->click('@note-edit-save');
+ waitForGone($page, '@note-edit-input');
+ $page->assertNoJavaScriptErrors();
+
+ expect($note->fresh()->body)->toBe($body);
+});
+
+test('editing the last note of a long thread scrolls its Save button into view', function () {
+ Mail::fake();
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $notes = collect(range(1, 10))->map(fn (int $number): PostNote => PostNote::factory()->create([
+ 'post_id' => $post->id,
+ 'user_id' => $user->id,
+ 'body' => "Note number {$number}",
+ 'created_at' => now()->subMinutes(20 - $number),
+ 'updated_at' => now()->subMinutes(20 - $number),
+ ]));
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitForCount($page, '@note-item', 10);
+
+ $last = "[data-note-id=\"{$notes->last()->id}\"]";
+ $page->hover($last)->click("{$last} [data-testid=note-actions]");
+ waitFor($page, '@note-edit');
+ $page->click('@note-edit');
+ waitForState($page, '@note-edit-save', "(() => { const list = document.querySelector('[data-testid=notes-list]').getBoundingClientRect(); const save = element.getBoundingClientRect(); return save.top >= list.top - 1 && save.bottom <= list.bottom + 1; })()");
+ $page->assertNoJavaScriptErrors();
+});
+
+test('an edit the server refuses keeps the editor open with the text and says why', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'hello team']);
+ $note = PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $user->id, 'body' => 'Short note']);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-notes-trigger-{$post->id}");
+ $page->click("@post-notes-trigger-{$post->id}");
+ waitFor($page, '@note-item');
+ $page->hover('@note-item')->click('@note-actions');
+ waitFor($page, '@note-edit');
+ $page->click('@note-edit');
+ waitForEditorText($page, '@note-edit-input', 'Short note');
+
+ $page->keys('@note-edit-input', 'ControlOrMeta+a');
+ $page->script("document.execCommand('insertText', false, 'a'.repeat(2001))");
+ waitForState($page, '@note-edit-input', 'element.innerText.trim().length === 2001');
+ $page->click('@note-edit-save');
+ waitFor($page, '@note-error-toast');
+
+ $page->assertSeeIn('@note-error-toast', __('notes.errors.too_long', ['max' => 2000]))
+ ->assertVisible('@note-edit-input')
+ ->assertScript("document.querySelector('[data-testid=\"note-edit-input\"]').innerText.trim().length", 2001)
+ ->assertNoJavaScriptErrors();
+ expect($note->fresh()->body)->toBe('Short note');
+});
+
test('the notes toggle says whether it shows or hides the notes', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
@@ -227,21 +846,33 @@ test('notes open, grow, send, edit and fit the card on every tab, on desktop and
waitFor($page, '@note-input');
$singleLine = $page->script("document.querySelector('[data-testid=\"note-input\"]').getBoundingClientRect().height");
- $page->fill('@note-input', "First line\nSecond line\nThird line");
+ $page->fill('@note-input', 'First line');
+ waitForEditorText($page, '@note-input', 'First line');
+ $page->keys('@note-input', ['Shift+Enter']);
+ $page->typeSlowly('@note-input', 'Second line', 10);
+ waitForEditorText($page, '@note-input', "First line\nSecond line");
+ $page->keys('@note-input', ['Shift+Enter']);
+ $page->typeSlowly('@note-input', 'Third line', 10);
+ waitForEditorText($page, '@note-input', "First line\nSecond line\nThird line");
$grown = $page->script("document.querySelector('[data-testid=\"note-input\"]').getBoundingClientRect().height");
- expect($grown)->toBeGreaterThan($singleLine);
+ expect($grown)->toBeGreaterThan($singleLine)
+ ->and($page->script("document.querySelector('[data-testid=\"note-composer\"]').getBoundingClientRect().height"))->toBeGreaterThanOrEqual($grown);
$page->keys('@note-input', ['Enter']);
waitFor($page, '@note-body');
waitForText($page, "@post-notes-count-{$post->id}", '1');
+ expect(PostNote::query()->where('post_id', $post->id)->sole()->body)->toBe("First line\nSecond line\nThird line");
$page->assertSeeIn("@post-notes-count-{$post->id}", '1')
->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true);
$page->hover('@note-item')->click('@note-actions');
waitFor($page, '@note-edit');
$page->click('@note-edit');
- waitFor($page, '@note-edit-input');
- $page->fill('@note-edit-input', 'Edited note')
+ waitForEditorText($page, '@note-edit-input', "First line\nSecond line\nThird line");
+ $page->keys('@note-edit-input', 'ControlOrMeta+a');
+ $page->typeSlowly('@note-edit-input', 'Edited note', 10);
+ waitForEditorText($page, '@note-edit-input', 'Edited note');
+ $page->assertScript("document.querySelector('[data-testid=\"note-edit-input\"]').innerText.trim()", 'Edited note')
->click('@note-edit-save');
waitForGone($page, '@note-edit-input');
waitForText($page, '@note-body', 'Edited note');
diff --git a/tests/Browser/PublishQueueTest.php b/tests/Browser/PublishQueueTest.php
index b3e22d257..48e4c2638 100644
--- a/tests/Browser/PublishQueueTest.php
+++ b/tests/Browser/PublishQueueTest.php
@@ -214,7 +214,7 @@ test('a stale reorder is rolled back and reported', function () {
test('the posting times toggle hides every slot and survives a reload', function () {
[$user, , $channel] = publishQueueSetup();
$queued = publishQueuePost($user, $channel);
- $slot = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 1)[0];
+ $slot = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2)[1];
$slotKey = publishQueueSlotKey($channel, $slot);
$this->actingAs($user);
diff --git a/tests/Browser/WebhookShowTest.php b/tests/Browser/WebhookShowTest.php
index b9cfd2461..e2bbdda56 100644
--- a/tests/Browser/WebhookShowTest.php
+++ b/tests/Browser/WebhookShowTest.php
@@ -148,10 +148,14 @@ test('the actions menu pauses, edits and deletes the webhook after a plain confi
test('send test event pings the endpoint from the header and from the empty deliveries state', function () {
[$user, $webhook] = webhookShowFixture();
+ $pings = 0;
$this->mock(WebhookService::class)
->shouldReceive('ping')
->twice()
- ->with('https://hooks.example.com/trypost/inbound', Mockery::type('string'));
+ ->with('https://hooks.example.com/trypost/inbound', Mockery::type('string'))
+ ->andReturnUsing(function () use (&$pings): void {
+ $pings++;
+ });
$this->actingAs($user);
$page = visit(route('app.webhooks.show', $webhook));
@@ -174,9 +178,10 @@ test('send test event pings the endpoint from the header and from the empty deli
JS))->toBe([true, true]);
$page->click('@send-test-webhook');
- waitForCount($page, '[data-sonner-toast]', 2, '>=');
+ waitForDatabase($page, fn (): bool => $pings === 2);
- $page->assertNoJavaScriptErrors();
+ $page->assertSee(__('webhooks.flash.tested'))->assertNoJavaScriptErrors();
+ expect($pings)->toBe(2);
});
test('a live delivery update never shows the same delivery twice', function () {
diff --git a/tests/Feature/Mail/MailRenderingTest.php b/tests/Feature/Mail/MailRenderingTest.php
index cc88d1c9e..564101c92 100644
--- a/tests/Feature/Mail/MailRenderingTest.php
+++ b/tests/Feature/Mail/MailRenderingTest.php
@@ -10,6 +10,7 @@ use App\Enums\User\TimeFormat;
use App\Mail\PostApprovalRequested;
use App\Mail\PostApproved;
use App\Mail\PostNoteAdded;
+use App\Mail\PostNoteMentioned;
use App\Mail\PostRejected;
use App\Mail\WorkspaceConnectionsDisconnected;
use App\Mail\WorkspaceInvite;
@@ -132,6 +133,73 @@ test('the post note email renders the note, the post and its channel', function
$mailable->assertSeeInHtml(route('app.posts.edit', ['post' => $post, 'comment' => $note->id]), false);
})->with([Locale::English, Locale::PortugueseBrazil]);
+test('the mention email renders the note with its mentions as names', function (Locale $locale) {
+ $author = User::factory()->create(['name' => 'Ana Author']);
+ $mentioned = User::factory()->create(['name' => 'Bia Lima']);
+ $workspace = Workspace::factory()->create(['account_id' => $author->account_id, 'user_id' => $author->id, 'name' => 'Acme Workspace']);
+ $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $author->id]);
+ $note = PostNote::factory()->create([
+ 'post_id' => $post->id,
+ 'user_id' => $author->id,
+ 'body' => "@[user:{$mentioned->id}] can you check?",
+ ]);
+ $note->mentions()->attach($mentioned);
+
+ $mailable = (new PostNoteMentioned($note, $author))->locale($locale->value);
+
+ $mailable->assertHasSubject(__('mail.post_note_mentioned.subject', ['author' => 'Ana Author'], $locale->value));
+ $mailable->assertSeeInHtml(__('mail.post_note_mentioned.heading', [], $locale->value));
+ $mailable->assertSeeInHtml(e(__('mail.post_note_mentioned.body', ['author' => 'Ana Author', 'workspace' => 'Acme Workspace'], $locale->value)), false);
+ $mailable->assertSeeInHtml('@Bia Lima can you check?');
+ $mailable->assertDontSeeInHtml("user:{$mentioned->id}", false);
+ $mailable->assertSeeInHtml(route('app.posts.edit', ['post' => $post, 'comment' => $note->id]), false);
+})->with([Locale::English, Locale::PortugueseBrazil]);
+
+test('the post note email shows mentions as names', function () {
+ $author = User::factory()->create();
+ $mentioned = User::factory()->create(['name' => 'Bia Lima']);
+ $post = Post::factory()->create(['user_id' => $author->id]);
+ $note = PostNote::factory()->create([
+ 'post_id' => $post->id,
+ 'user_id' => $author->id,
+ 'body' => "Ask @[user:{$mentioned->id}] first",
+ ]);
+ $note->mentions()->attach($mentioned);
+
+ (new PostNoteAdded($note, $author))
+ ->assertSeeInHtml('Ask @Bia Lima first')
+ ->assertDontSeeInHtml("user:{$mentioned->id}", false);
+});
+
+test('the mention email names everyone in the recipient\'s language', function (Locale $locale, string $word) {
+ $author = User::factory()->create();
+ $post = Post::factory()->create(['user_id' => $author->id]);
+ $note = PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $author->id, 'body' => '@[everyone] please review']);
+
+ (new PostNoteMentioned($note, $author))->locale($locale->value)
+ ->assertSeeInHtml("@{$word} please review")
+ ->assertDontSeeInHtml('@[everyone]', false);
+})->with([
+ [Locale::English, 'all'],
+ [Locale::PortugueseBrazil, 'todos'],
+]);
+
+test('a mention of someone no longer there reads as unknown in the email', function () {
+ $author = User::factory()->create();
+ $gone = User::factory()->create();
+ $post = Post::factory()->create(['user_id' => $author->id]);
+ $note = PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $author->id, 'body' => "Ask @[user:{$gone->id}] first"]);
+ $note->mentions()->attach($gone);
+
+ $gone->delete();
+
+ $unknown = __('mail.post_note_added.mention_unknown');
+
+ (new PostNoteAdded($note->fresh(), $author))
+ ->assertSeeInHtml("Ask @{$unknown} first")
+ ->assertDontSeeInHtml("user:{$gone->id}", false);
+});
+
test('the post note email falls back when the post has no text and no channel', function () {
$author = User::factory()->create();
$post = Post::factory()->create(['user_id' => $author->id, 'content' => '']);
diff --git a/tests/Feature/Mcp/ToolAnnotationsTest.php b/tests/Feature/Mcp/ToolAnnotationsTest.php
index 732b8c25d..8c2c8288d 100644
--- a/tests/Feature/Mcp/ToolAnnotationsTest.php
+++ b/tests/Feature/Mcp/ToolAnnotationsTest.php
@@ -42,6 +42,9 @@ function mcpExpectedToolAnnotations(): array
'create-post-note-tool' => [false, true, false],
'update-post-note-tool' => [false, true, false],
'delete-post-note-tool' => [false, true, false],
+ 'list-post-note-mentionables-tool' => [true, false, false],
+ 'add-post-note-reaction-tool' => [false, false, false],
+ 'remove-post-note-reaction-tool' => [false, true, false],
'set-post-recurrence-tool' => [false, true, true],
'clear-post-recurrence-tool' => [false, true, false],
diff --git a/tests/Feature/Parity/McpAuthorizationParityTest.php b/tests/Feature/Parity/McpAuthorizationParityTest.php
index 0ebaeaa9f..8d16f96e0 100644
--- a/tests/Feature/Parity/McpAuthorizationParityTest.php
+++ b/tests/Feature/Parity/McpAuthorizationParityTest.php
@@ -32,6 +32,7 @@ use App\Mcp\Tools\Label\DeleteLabelTool;
use App\Mcp\Tools\Label\ListLabelsTool;
use App\Mcp\Tools\Label\UpdateLabelTool;
use App\Mcp\Tools\Platform\ListContentTypesTool;
+use App\Mcp\Tools\Post\AddPostNoteReactionTool;
use App\Mcp\Tools\Post\ApprovePostTool;
use App\Mcp\Tools\Post\AttachMediaFromUploadTool;
use App\Mcp\Tools\Post\AttachMediaFromUrlTool;
@@ -43,11 +44,13 @@ use App\Mcp\Tools\Post\DeletePostNoteTool;
use App\Mcp\Tools\Post\DeletePostTool;
use App\Mcp\Tools\Post\GetPostMetricsTool;
use App\Mcp\Tools\Post\GetPostTool;
+use App\Mcp\Tools\Post\ListPostNoteMentionablesTool;
use App\Mcp\Tools\Post\ListPostNotesTool;
use App\Mcp\Tools\Post\ListPostsTool;
use App\Mcp\Tools\Post\PreviewPostTool;
use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\RejectPostTool;
+use App\Mcp\Tools\Post\RemovePostNoteReactionTool;
use App\Mcp\Tools\Post\RequestMediaUploadTool;
use App\Mcp\Tools\Post\SetPostRecurrenceTool;
use App\Mcp\Tools\Post\UpdatePostNoteTool;
@@ -269,10 +272,13 @@ function mcpAuthParityTools(): array
'delete-post-tool' => [DeletePostTool::class, $publishers, fn (TestCase $t, array $f) => $t->delete(route('app.posts.destroy', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
'get-post-metrics-tool' => [GetPostMetricsTool::class, [], fn (TestCase $t, array $f) => $t->get(route('app.posts.edit', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
'get-post-tool' => [GetPostTool::class, [], fn (TestCase $t, array $f) => $t->get(route('app.posts.edit', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
- 'list-post-notes-tool' => [ListPostNotesTool::class, $everyMember, fn (TestCase $t, array $f) => $t->getJson(route('app.posts.notes.index', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
+ 'list-post-notes-tool' => [ListPostNotesTool::class, $everyMember, fn (TestCase $t, array $f) => $t->get(route('app.posts.index', ['notes' => $f['post']->id])), fn (array $f) => ['post_id' => $f['post']->id]],
'create-post-note-tool' => [CreatePostNoteTool::class, $everyMember, fn (TestCase $t, array $f) => $t->postJson(route('app.posts.notes.store', $f['post']), ['body' => 'Looks good']), fn (array $f) => ['post_id' => $f['post']->id, 'body' => 'Looks good']],
'update-post-note-tool' => [UpdatePostNoteTool::class, ['admin', 'member', 'approval', 'outsider'], fn (TestCase $t, array $f) => $t->putJson(route('app.posts.notes.update', [$f['post'], $f['note']]), ['body' => 'Edited']), fn (array $f) => ['post_id' => $f['post']->id, 'note_id' => $f['note']->id, 'body' => 'Edited']],
'delete-post-note-tool' => [DeletePostNoteTool::class, ['admin', 'member', 'approval', 'outsider'], fn (TestCase $t, array $f) => $t->deleteJson(route('app.posts.notes.destroy', [$f['post'], $f['note']])), fn (array $f) => ['post_id' => $f['post']->id, 'note_id' => $f['note']->id]],
+ 'list-post-note-mentionables-tool' => [ListPostNoteMentionablesTool::class, $everyMember, fn (TestCase $t, array $f) => $t->getJson(route('app.posts.notes.mentionables.index', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
+ 'add-post-note-reaction-tool' => [AddPostNoteReactionTool::class, $everyMember, fn (TestCase $t, array $f) => $t->putJson(route('app.posts.notes.reactions.update', [$f['post'], $f['note']]), ['emoji' => '👍']), fn (array $f) => ['post_id' => $f['post']->id, 'note_id' => $f['note']->id, 'emoji' => '👍']],
+ 'remove-post-note-reaction-tool' => [RemovePostNoteReactionTool::class, $everyMember, fn (TestCase $t, array $f) => $t->deleteJson(route('app.posts.notes.reactions.destroy', [$f['post'], $f['note']]), ['emoji' => '👍']), fn (array $f) => ['post_id' => $f['post']->id, 'note_id' => $f['note']->id, 'emoji' => '👍']],
'get-tiktok-creator-info-tool' => [GetTikTokCreatorInfoTool::class, $everyMember, fn (TestCase $t, array $f) => $t->getJson(route('app.posts.composer.account', $f['tiktok'])), fn (array $f) => ['account_id' => $f['tiktok']->id]],
'list-posts-tool' => [ListPostsTool::class, $everyMember, fn (TestCase $t, array $f) => $t->get(route('app.posts.index')), fn (array $f) => []],
'preview-post-tool' => [PreviewPostTool::class, [], fn (TestCase $t, array $f) => $t->get(route('app.posts.edit', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
diff --git a/tests/Feature/Parity/PostNotesParityTest.php b/tests/Feature/Parity/PostNotesParityTest.php
index f2f5675d6..286e7ad1d 100644
--- a/tests/Feature/Parity/PostNotesParityTest.php
+++ b/tests/Feature/Parity/PostNotesParityTest.php
@@ -3,15 +3,24 @@
declare(strict_types=1);
use App\Enums\Post\Status;
+use App\Events\PostNoteChanged;
use App\Mail\PostNoteAdded;
+use App\Mail\PostNoteMentioned;
use App\Mcp\Servers\TryPostServer;
+use App\Mcp\Tools\Post\AddPostNoteReactionTool;
use App\Mcp\Tools\Post\CreatePostNoteTool;
use App\Mcp\Tools\Post\DeletePostNoteTool;
+use App\Mcp\Tools\Post\ListPostNoteMentionablesTool;
use App\Mcp\Tools\Post\ListPostNotesTool;
+use App\Mcp\Tools\Post\RemovePostNoteReactionTool;
use App\Mcp\Tools\Post\UpdatePostNoteTool;
use App\Models\Post;
use App\Models\PostNote;
+use App\Models\PostNoteReaction;
+use App\Models\User;
use Illuminate\Auth\Access\AuthorizationException;
+use Illuminate\Mail\Mailable;
+use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Testing\Fluent\AssertableJson;
@@ -45,6 +54,30 @@ test('a note added on the web, the api and mcp is stored the same way with the a
]);
});
+test('the api and mcp store a mention by its id in lower case, drop one of someone outside and return the names', function () {
+ $teammate = workspaceMember($this->workspace, 'member', ['name' => 'Bia Lima']);
+ $outsider = workspaceOutsider($this->workspace);
+ $upperId = Str::upper($teammate->id);
+ $body = "@[user:{$upperId}] and @[user:{$outsider->id}]";
+ $mentions = [['id' => $teammate->id, 'name' => 'Bia Lima']];
+
+ $this->withHeaders(parityApi($this->token))
+ ->postJson(route('api.posts.notes.store', $this->post), ['body' => $body])
+ ->assertCreated()
+ ->assertJsonPath('body', "@[user:{$upperId}] and ")
+ ->assertJsonPath('mentions', $mentions);
+ auth()->forgetGuards();
+
+ TryPostServer::actingAs($this->user)->tool(CreatePostNoteTool::class, ['post_id' => $this->post->id, 'body' => $body])
+ ->assertOk()
+ ->assertStructuredContent(fn (AssertableJson $json) => $json->where('body', "@[user:{$upperId}] and ")->where('mentions', $mentions)->etc());
+
+ $notes = PostNote::query()->where('post_id', $this->post->id)->get();
+
+ expect($notes)->toHaveCount(2)
+ ->and($notes->map(fn (PostNote $note): array => $note->mentions()->pluck('users.id')->all())->all())->toBe([[$teammate->id], [$teammate->id]]);
+});
+
test('the api and mcp note lists paginate newest first with the app page size and expose only safe author fields', function () {
config(['app.pagination.default' => 2]);
$notes = collect(range(1, 3))->map(fn (int $minutes): PostNote => PostNote::factory()->create([
@@ -67,10 +100,28 @@ test('the api and mcp note lists paginate newest first with the app page size an
TryPostServer::actingAs($this->user)->tool(ListPostNotesTool::class, ['post_id' => $this->post->id, 'page' => 2])->assertOk()->assertStructuredContent(parityMcpPage('notes', $second));
expect([...collect($first->json('data'))->pluck('id'), ...collect($second->json('data'))->pluck('id')])->toBe($notes->pluck('id')->all())
- ->and(array_keys($first->json('data.0')))->toBe(['id', 'post_id', 'body', 'author', 'created_at', 'updated_at'])
+ ->and(array_keys($first->json('data.0')))->toBe(['id', 'post_id', 'body', 'mentions', 'reactions', 'author', 'created_at', 'updated_at'])
->and(array_keys($first->json('data.0.author')))->toBe(['id', 'name', 'photo_url']);
});
+test('the web and the api show one note the same way, with its mentions and reactions', function () {
+ $teammate = workspaceMember($this->workspace, 'member', ['name' => 'Bia Lima']);
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id, 'body' => "Ask @[user:{$teammate->id}]"]);
+ $note->mentions()->attach($teammate);
+ PostNoteReaction::factory()->create(['post_note_id' => $note->id, 'user_id' => $teammate->id, 'emoji' => '👍']);
+
+ $web = $this->actingAs($this->user)->getJson(route('app.posts.notes.show', [$this->post, $note]))->assertOk();
+ auth()->forgetGuards();
+ $api = $this->withHeaders(parityApi($this->token))->getJson(route('api.posts.notes.show', [$this->post, $note]))->assertOk();
+
+ foreach ([$web, $api] as $response) {
+ expect($response->json('id'))->toBe($note->id)
+ ->and($response->json('mentions'))->toBe([['id' => $teammate->id, 'name' => 'Bia Lima']])
+ ->and($response->json('reactions.0.emoji'))->toBe('👍')
+ ->and($response->json('reactions.0.count'))->toBe(1);
+ }
+});
+
test('the author edits and deletes their own note through the api and mcp', function () {
$apiNote = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id]);
$mcpNote = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id]);
@@ -121,6 +172,10 @@ test('a note of another post is not found on the web, the api and mcp', function
auth()->forgetGuards();
$this->withHeaders(parityApi($this->token))->deleteJson(route('api.posts.notes.destroy', [$this->post, $note]))->assertNotFound();
auth()->forgetGuards();
+ $this->withHeaders(parityApi($this->token))->getJson(route('api.posts.notes.show', [$this->post, $note]))->assertNotFound();
+ auth()->forgetGuards();
+ $this->actingAs($this->user)->getJson(route('app.posts.notes.show', [$this->post, $note]))->assertNotFound();
+ auth()->forgetGuards();
TryPostServer::actingAs($this->user)->tool(UpdatePostNoteTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id, 'body' => 'Moved'])->assertHasErrors(['Note not found.']);
TryPostServer::actingAs($this->user)->tool(DeletePostNoteTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id])->assertHasErrors(['Note not found.']);
@@ -133,15 +188,31 @@ test('a post of another workspace is not found on the web, the api and mcp', fun
$foreignPost = Post::factory()->draft()->create(['workspace_id' => $other['workspace']->id, 'user_id' => $other['user']->id]);
$foreignNote = PostNote::factory()->create(['post_id' => $foreignPost->id, 'user_id' => $other['user']->id, 'body' => 'Original']);
- $this->actingAs($this->user)->getJson(route('app.posts.notes.index', $foreignPost))->assertNotFound();
- $this->actingAs($this->user)->postJson(route('app.posts.notes.store', $foreignPost), ['body' => 'Hijacked'])->assertNotFound();
+ expect($this->actingAs($this->user)->get(route('app.posts.index', ['notes' => $foreignPost->id]))->inertiaProps('postNotes'))->toBeNull();
auth()->forgetGuards();
+ $webCalls = [
+ ['POST', route('app.posts.notes.store', $foreignPost), ['body' => 'Hijacked']],
+ ['GET', route('app.posts.notes.show', [$foreignPost, $foreignNote]), []],
+ ['GET', route('app.posts.notes.mentionables.index', $foreignPost), []],
+ ['PUT', route('app.posts.notes.reactions.update', [$foreignPost, $foreignNote]), ['emoji' => '👍']],
+ ['DELETE', route('app.posts.notes.reactions.destroy', [$foreignPost, $foreignNote]), ['emoji' => '👍']],
+ ];
+
+ foreach ($webCalls as [$method, $url, $body]) {
+ $this->actingAs($this->user)->json($method, $url, $body)->assertNotFound();
+ auth()->forgetGuards();
+ }
+
$calls = [
['GET', route('api.posts.notes.index', $foreignPost), []],
+ ['GET', route('api.posts.notes.show', [$foreignPost, $foreignNote]), []],
['POST', route('api.posts.notes.store', $foreignPost), ['body' => 'Hijacked']],
['PUT', route('api.posts.notes.update', [$foreignPost, $foreignNote]), ['body' => 'Hijacked']],
['DELETE', route('api.posts.notes.destroy', [$foreignPost, $foreignNote]), []],
+ ['GET', route('api.posts.notes.mentionables.index', $foreignPost), []],
+ ['PUT', route('api.posts.notes.reactions.update', [$foreignPost, $foreignNote]), ['emoji' => '👍']],
+ ['DELETE', route('api.posts.notes.reactions.destroy', [$foreignPost, $foreignNote]), ['emoji' => '👍']],
];
foreach ($calls as [$method, $url, $body]) {
@@ -153,8 +224,11 @@ test('a post of another workspace is not found on the web, the api and mcp', fun
TryPostServer::actingAs($this->user)->tool(CreatePostNoteTool::class, ['post_id' => $foreignPost->id, 'body' => 'Hijacked'])->assertHasErrors(['Post not found.']);
TryPostServer::actingAs($this->user)->tool(UpdatePostNoteTool::class, ['post_id' => $foreignPost->id, 'note_id' => $foreignNote->id, 'body' => 'Hijacked'])->assertHasErrors(['Post not found.']);
TryPostServer::actingAs($this->user)->tool(DeletePostNoteTool::class, ['post_id' => $foreignPost->id, 'note_id' => $foreignNote->id])->assertHasErrors(['Post not found.']);
+ TryPostServer::actingAs($this->user)->tool(ListPostNoteMentionablesTool::class, ['post_id' => $foreignPost->id])->assertHasErrors(['Post not found.']);
+ TryPostServer::actingAs($this->user)->tool(AddPostNoteReactionTool::class, ['post_id' => $foreignPost->id, 'note_id' => $foreignNote->id, 'emoji' => '👍'])->assertHasErrors(['Post not found.']);
- expect(PostNote::query()->where('post_id', $foreignPost->id)->pluck('body')->all())->toBe(['Original']);
+ expect(PostNote::query()->where('post_id', $foreignPost->id)->pluck('body')->all())->toBe(['Original'])
+ ->and(PostNoteReaction::query()->count())->toBe(0);
});
test('a member who cannot see another member pending request gets not found on the web and mcp, while the requester reads it', function () {
@@ -168,7 +242,7 @@ test('a member who cannot see another member pending request gets not found on t
]);
PostNote::factory()->create(['post_id' => $pending->id, 'user_id' => $this->user->id]);
- $this->actingAs($bystander)->getJson(route('app.posts.notes.index', $pending))->assertNotFound();
+ expect($this->actingAs($bystander)->get(route('app.posts.index', ['notes' => $pending->id]))->inertiaProps('postNotes'))->toBeNull();
$this->actingAs($bystander)->postJson(route('app.posts.notes.store', $pending), ['body' => 'Peek'])->assertNotFound();
auth()->forgetGuards();
@@ -212,7 +286,7 @@ test('the mcp note tools refuse ids that are not uuids with a validation error',
test('a user outside the workspace cannot read or add notes on the web or mcp', function () {
$outsider = workspaceOutsider($this->workspace);
- $this->actingAs($outsider)->getJson(route('app.posts.notes.index', $this->post))->assertForbidden();
+ $this->actingAs($outsider)->get(route('app.posts.index', ['notes' => $this->post->id]))->assertForbidden();
auth()->forgetGuards();
TryPostServer::actingAs($outsider)->tool(ListPostNotesTool::class, ['post_id' => $this->post->id])->assertHasErrors([$this->unauthorized]);
@@ -221,7 +295,7 @@ test('a user outside the workspace cannot read or add notes on the web or mcp',
expect(PostNote::query()->count())->toBe(0);
});
-test('a note added through the api on a pending request emails only the approvers and the requester', function () {
+test('a note added through the api on a pending request emails the requester and mentions only those who see it', function () {
Mail::fake();
$requester = workspaceMember($this->workspace, 'approval');
$bystander = workspaceMember($this->workspace, 'approval');
@@ -233,13 +307,15 @@ test('a note added through the api on a pending request emails only the approver
'approval_requested_by' => $requester->id,
]);
- $this->withHeaders(parityApi($this->token))->postJson(route('api.posts.notes.store', $pending), ['body' => 'Pricing changes Friday'])->assertCreated();
+ $this->withHeaders(parityApi($this->token))->postJson(route('api.posts.notes.store', $pending), [
+ 'body' => "Pricing changes Friday @[user:{$approver->id}] @[user:{$bystander->id}]",
+ ])->assertCreated();
- expect(pendingNoteRecipients())->toEqualCanonicalizing([$requester->email, $approver->email])
- ->and(pendingNoteRecipients())->not->toContain($bystander->email, $this->user->email);
+ expect(pendingNoteRecipients())->toBe([$requester->email])
+ ->and(noteRecipients(PostNoteMentioned::class))->toBe([$approver->email]);
});
-test('a note added through mcp by the requester on their pending request emails only the approvers', function () {
+test('a note added through mcp by the requester on their pending request mentions only the approvers', function () {
Mail::fake();
$requester = workspaceMember($this->workspace, 'approval');
$bystander = workspaceMember($this->workspace, 'approval');
@@ -251,21 +327,219 @@ test('a note added through mcp by the requester on their pending request emails
'approval_requested_by' => $requester->id,
]);
- TryPostServer::actingAs($requester)->tool(CreatePostNoteTool::class, ['post_id' => $pending->id, 'body' => 'Ready for review'])->assertOk();
+ TryPostServer::actingAs($requester)->tool(CreatePostNoteTool::class, [
+ 'post_id' => $pending->id,
+ 'body' => "Ready for review @[user:{$approver->id}] @[user:{$bystander->id}]",
+ ])->assertOk();
- expect(pendingNoteRecipients())->toEqualCanonicalizing([$this->user->email, $approver->email])
- ->and(pendingNoteRecipients())->not->toContain($bystander->email, $requester->email);
+ expect(pendingNoteRecipients())->toBe([])
+ ->and(noteRecipients(PostNoteMentioned::class))->toBe([$approver->email]);
});
-test('a note added through mcp on a draft emails every other member', function () {
+test('a note added through mcp on a draft emails its participants', function () {
Mail::fake();
$member = workspaceMember($this->workspace, 'approval');
+ workspaceMember($this->workspace);
+ PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $member->id]);
TryPostServer::actingAs($this->user)->tool(CreatePostNoteTool::class, ['post_id' => $this->post->id, 'body' => 'Heads up'])->assertOk();
expect(pendingNoteRecipients())->toBe([$member->email]);
});
+test('reactions added and removed on the web, the api and mcp are stored once per member and emoji', function () {
+ Event::fake([PostNoteChanged::class]);
+ $teammate = workspaceMember($this->workspace, 'admin');
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $teammate->id]);
+
+ $this->actingAs($this->user)->putJson(route('app.posts.notes.reactions.update', [$this->post, $note]), ['emoji' => '👍'])->assertOk();
+ $this->actingAs($this->user)->putJson(route('app.posts.notes.reactions.update', [$this->post, $note]), ['emoji' => '👍'])->assertOk();
+ auth()->forgetGuards();
+
+ $this->withHeaders(parityApi(passportToken($teammate, $this->workspace)))
+ ->putJson(route('api.posts.notes.reactions.update', [$this->post, $note]), ['emoji' => '👍'])
+ ->assertOk()
+ ->assertJsonPath('reactions', [['emoji' => '👍', 'count' => 2, 'users' => [
+ ['id' => $this->user->id, 'name' => $this->user->name],
+ ['id' => $teammate->id, 'name' => $teammate->name],
+ ]]]);
+ auth()->forgetGuards();
+
+ TryPostServer::actingAs($this->user)->tool(AddPostNoteReactionTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id, 'emoji' => '🎉'])
+ ->assertOk()
+ ->assertStructuredContent(fn (AssertableJson $json) => $json->where('reactions.0.count', 2)->where('reactions.1.emoji', '🎉')->etc());
+
+ expect(PostNoteReaction::query()->count())->toBe(3);
+ Event::assertDispatchedTimes(PostNoteChanged::class, 3);
+
+ $this->actingAs($this->user)->deleteJson(route('app.posts.notes.reactions.destroy', [$this->post, $note]), ['emoji' => '👍'])
+ ->assertOk()
+ ->assertJsonPath('reactions.0.count', 1);
+ auth()->forgetGuards();
+ $this->withHeaders(parityApi($this->token))->deleteJson(route('api.posts.notes.reactions.destroy', [$this->post, $note]), ['emoji' => '🎉'])->assertOk();
+ auth()->forgetGuards();
+ TryPostServer::actingAs($teammate)->tool(RemovePostNoteReactionTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id, 'emoji' => '👍'])
+ ->assertOk()
+ ->assertStructuredContent(fn (AssertableJson $json) => $json->where('reactions', [])->etc());
+
+ expect(PostNoteReaction::query()->count())->toBe(0);
+});
+
+test('the web, the api and mcp refuse a reaction that is not exactly one emoji', function () {
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id]);
+
+ $invalid = [
+ [],
+ ['emoji' => ''],
+ ['emoji' => 'a'],
+ ['emoji' => '👍👍'],
+ ['emoji' => ['👍']],
+ ['emoji' => "a\u{20E3}"],
+ ['emoji' => "\u{1F1E7}"],
+ ['emoji' => '👍'.str_repeat("\u{0301}", 80)],
+ ];
+
+ foreach ($invalid as $payload) {
+ $this->actingAs($this->user)->putJson(route('app.posts.notes.reactions.update', [$this->post, $note]), $payload)->assertUnprocessable()->assertJsonValidationErrors('emoji');
+ auth()->forgetGuards();
+ $this->withHeaders(parityApi($this->token))->putJson(route('api.posts.notes.reactions.update', [$this->post, $note]), $payload)->assertUnprocessable()->assertJsonValidationErrors('emoji');
+ auth()->forgetGuards();
+ TryPostServer::actingAs($this->user)->tool(AddPostNoteReactionTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id, ...$payload])->assertHasErrors();
+ }
+
+ expect(PostNoteReaction::query()->count())->toBe(0);
+});
+
+test('every kind of emoji is a reaction on the web, the api and mcp', function (string $emoji) {
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id]);
+ $admin = workspaceMember($this->workspace, 'admin');
+ $member = workspaceMember($this->workspace);
+
+ $this->actingAs($this->user)->putJson(route('app.posts.notes.reactions.update', [$this->post, $note]), ['emoji' => $emoji])->assertOk();
+ auth()->forgetGuards();
+ $this->withHeaders(parityApi(passportToken($admin, $this->workspace)))->putJson(route('api.posts.notes.reactions.update', [$this->post, $note]), ['emoji' => $emoji])->assertOk();
+ auth()->forgetGuards();
+ TryPostServer::actingAs($member)->tool(AddPostNoteReactionTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id, 'emoji' => $emoji])->assertOk();
+
+ expect(PostNoteReaction::query()->pluck('emoji')->all())->toBe([$emoji, $emoji, $emoji]);
+})->with([
+ 'pictograph' => '👍',
+ 'variation selector' => '❤️',
+ 'skin tone' => '👍🏽',
+ 'joined pictographs' => '👨‍👩‍👧‍👦',
+ 'flag' => '🇧🇷',
+ 'subdivision flag' => '🏴󠁧󠁢󠁳󠁣󠁴󠁿',
+ 'keycap' => '1️⃣',
+]);
+
+test('taking back a reaction you do not have changes nothing on the web, the api and mcp', function () {
+ Event::fake([PostNoteChanged::class]);
+ $teammate = workspaceMember($this->workspace);
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $teammate->id]);
+ PostNoteReaction::factory()->create(['post_note_id' => $note->id, 'user_id' => $teammate->id, 'emoji' => '👍']);
+
+ $this->actingAs($this->user)->deleteJson(route('app.posts.notes.reactions.destroy', [$this->post, $note]), ['emoji' => '👍'])
+ ->assertOk()
+ ->assertJsonPath('reactions.0.count', 1);
+ auth()->forgetGuards();
+ $this->withHeaders(parityApi($this->token))->deleteJson(route('api.posts.notes.reactions.destroy', [$this->post, $note]), ['emoji' => '👍'])->assertOk();
+ auth()->forgetGuards();
+ TryPostServer::actingAs($this->user)->tool(RemovePostNoteReactionTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id, 'emoji' => '👍'])->assertOk();
+
+ expect(PostNoteReaction::query()->sole()->user_id)->toBe($teammate->id);
+ Event::assertNotDispatched(PostNoteChanged::class);
+});
+
+test('reactions on a note of another post are not found on the web, the api and mcp', function () {
+ $otherPost = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
+ $note = PostNote::factory()->create(['post_id' => $otherPost->id, 'user_id' => $this->user->id]);
+
+ $this->actingAs($this->user)->putJson(route('app.posts.notes.reactions.update', [$this->post, $note]), ['emoji' => '👍'])->assertNotFound();
+ $this->actingAs($this->user)->deleteJson(route('app.posts.notes.reactions.destroy', [$this->post, $note]), ['emoji' => '👍'])->assertNotFound();
+ auth()->forgetGuards();
+ $this->withHeaders(parityApi($this->token))->putJson(route('api.posts.notes.reactions.update', [$this->post, $note]), ['emoji' => '👍'])->assertNotFound();
+ auth()->forgetGuards();
+ $this->withHeaders(parityApi($this->token))->deleteJson(route('api.posts.notes.reactions.destroy', [$this->post, $note]), ['emoji' => '👍'])->assertNotFound();
+ auth()->forgetGuards();
+ TryPostServer::actingAs($this->user)->tool(AddPostNoteReactionTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id, 'emoji' => '👍'])->assertHasErrors(['Note not found.']);
+ TryPostServer::actingAs($this->user)->tool(RemovePostNoteReactionTool::class, ['post_id' => $this->post->id, 'note_id' => $note->id, 'emoji' => '👍'])->assertHasErrors(['Note not found.']);
+
+ expect(PostNoteReaction::query()->count())->toBe(0);
+});
+
+test('a member who cannot see a pending request cannot read, react to its notes or list who to mention, on the web and mcp', function () {
+ $requester = workspaceMember($this->workspace, 'approval');
+ $bystander = workspaceMember($this->workspace, 'approval');
+ $pending = Post::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $requester->id,
+ 'status' => Status::PendingApproval,
+ 'approval_requested_by' => $requester->id,
+ ]);
+ $note = PostNote::factory()->create(['post_id' => $pending->id, 'user_id' => $this->user->id]);
+
+ $this->actingAs($bystander)->getJson(route('app.posts.notes.mentionables.index', $pending))->assertNotFound();
+ $this->actingAs($bystander)->getJson(route('app.posts.notes.show', [$pending, $note]))->assertNotFound();
+ $this->actingAs($bystander)->putJson(route('app.posts.notes.reactions.update', [$pending, $note]), ['emoji' => '👍'])->assertNotFound();
+ $this->actingAs($bystander)->deleteJson(route('app.posts.notes.reactions.destroy', [$pending, $note]), ['emoji' => '👍'])->assertNotFound();
+ auth()->forgetGuards();
+
+ TryPostServer::actingAs($bystander)->tool(ListPostNoteMentionablesTool::class, ['post_id' => $pending->id])->assertHasErrors(['Post not found.']);
+ TryPostServer::actingAs($bystander)->tool(AddPostNoteReactionTool::class, ['post_id' => $pending->id, 'note_id' => $note->id, 'emoji' => '👍'])->assertHasErrors(['Post not found.']);
+ TryPostServer::actingAs($bystander)->tool(RemovePostNoteReactionTool::class, ['post_id' => $pending->id, 'note_id' => $note->id, 'emoji' => '👍'])->assertHasErrors(['Post not found.']);
+
+ expect(PostNoteReaction::query()->count())->toBe(0);
+});
+
+test('an edit through the api and mcp emails only the teammates it mentions for the first time', function () {
+ Mail::fake();
+ $alreadyMentioned = workspaceMember($this->workspace);
+ $apiMention = workspaceMember($this->workspace);
+ $mcpMention = workspaceMember($this->workspace);
+ $mention = fn (User $user): string => "@[user:{$user->id}]";
+ $apiNote = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id, 'body' => "{$mention($alreadyMentioned)} ping"]);
+ $mcpNote = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id, 'body' => "{$mention($alreadyMentioned)} ping"]);
+
+ $this->withHeaders(parityApi($this->token))->putJson(route('api.posts.notes.update', [$this->post, $apiNote]), [
+ 'body' => "{$mention($alreadyMentioned)} {$mention($apiMention)} ping",
+ ])->assertOk();
+ auth()->forgetGuards();
+ TryPostServer::actingAs($this->user)->tool(UpdatePostNoteTool::class, [
+ 'post_id' => $this->post->id,
+ 'note_id' => $mcpNote->id,
+ 'body' => "{$mention($alreadyMentioned)} {$mention($mcpMention)} ping",
+ ])->assertOk();
+
+ expect(noteRecipients(PostNoteMentioned::class))->toBe([$apiMention->email, $mcpMention->email])
+ ->and(pendingNoteRecipients())->toBe([]);
+});
+
+test('the web, the api and mcp list the same people to mention: who sees the post, the viewer included', function () {
+ $this->user->update(['name' => 'Diego Owner']);
+ $requester = workspaceMember($this->workspace, 'approval', ['name' => 'Bia Requester']);
+ workspaceMember($this->workspace, 'approval', ['name' => 'Caio Bystander']);
+ $approver = workspaceMember($this->workspace, 'member', ['name' => 'Ana Approver']);
+ $pending = Post::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $requester->id,
+ 'status' => Status::PendingApproval,
+ 'approval_requested_by' => $requester->id,
+ ]);
+
+ $web = $this->actingAs($requester)->getJson(route('app.posts.notes.mentionables.index', $pending))->assertOk();
+ auth()->forgetGuards();
+ $api = $this->withHeaders(parityApi($this->token))->getJson(route('api.posts.notes.mentionables.index', $pending))->assertOk();
+ auth()->forgetGuards();
+
+ expect(collect($web->json())->pluck('id')->all())->toBe([$approver->id, $requester->id, $this->user->id])
+ ->and($api->json())->toBe($web->json())
+ ->and(array_keys($web->json('0')))->toBe(['id', 'name', 'photo_url', 'timezone']);
+
+ TryPostServer::actingAs($requester)->tool(ListPostNoteMentionablesTool::class, ['post_id' => $pending->id])
+ ->assertOk()
+ ->assertStructuredContent(['mentionables' => $web->json()]);
+});
+
/**
* Emails of every user a PostNoteAdded mail was queued to.
*
@@ -273,8 +547,19 @@ test('a note added through mcp on a draft emails every other member', function (
*/
function pendingNoteRecipients(): array
{
- return Mail::queued(PostNoteAdded::class)
- ->flatMap(fn (PostNoteAdded $mail): array => collect($mail->to)->pluck('address')->all())
+ return noteRecipients(PostNoteAdded::class);
+}
+
+/**
+ * Emails of every user a mail of that class was queued to.
+ *
+ * @param class-string<Mailable> $mailable
+ * @return list<string>
+ */
+function noteRecipients(string $mailable): array
+{
+ return Mail::queued($mailable)
+ ->flatMap(fn (Mailable $mail): array => collect($mail->to)->pluck('address')->all())
->values()
->all();
}
diff --git a/tests/Feature/PostNoteControllerTest.php b/tests/Feature/PostNoteControllerTest.php
index 2afd7652b..7b70b38d1 100644
--- a/tests/Feature/PostNoteControllerTest.php
+++ b/tests/Feature/PostNoteControllerTest.php
@@ -2,17 +2,23 @@
declare(strict_types=1);
+use App\Actions\PostNote\BuildPostNotesProps;
use App\Enums\Post\Status as PostStatus;
use App\Events\PostNoteChanged;
use App\Jobs\SendNotification;
use App\Mail\PostNoteAdded;
+use App\Mail\PostNoteMentioned;
use App\Models\Post;
use App\Models\PostNote;
+use App\Models\PostNoteReaction;
use App\Models\User;
use App\Models\Workspace;
+use Illuminate\Queue\Events\JobFailed;
+use Illuminate\Queue\WorkerOptions;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Str;
beforeEach(function () {
$this->user = User::factory()->create([]);
@@ -26,25 +32,37 @@ beforeEach(function () {
]);
});
-test('index returns every note of the post, newest first', function () {
- $older = PostNote::factory()->create([
+test('the publish page sends the notes of the post it has open, newest first and a page at a time by cursor', function () {
+ [$oldest, $middle, $newest] = collect([3, 2, 1])->map(fn (int $hours): PostNote => PostNote::factory()->create([
'post_id' => $this->post->id,
'user_id' => $this->user->id,
- 'created_at' => now()->subHour(),
- ]);
- $newer = PostNote::factory()->create([
- 'post_id' => $this->post->id,
- 'user_id' => $this->user->id,
- ]);
+ 'created_at' => now()->subHours($hours),
+ ]))->all();
- $response = $this->actingAs($this->user)
- ->getJson(route('app.posts.notes.index', $this->post));
+ $notes = $this->actingAs($this->user)
+ ->get(route('app.posts.index', ['notes' => $this->post->id]))
+ ->assertOk()
+ ->inertiaProps('postNotes');
- $response->assertOk();
- $response->assertJsonCount(2, 'data');
- $response->assertJsonPath('data.0.id', $newer->id);
- $response->assertJsonPath('data.1.id', $older->id);
- $response->assertJsonPath('data.0.user.id', $this->user->id);
+ expect(collect(data_get($notes, 'data'))->pluck('id')->all())->toBe([$newest->id, $middle->id, $oldest->id])
+ ->and(data_get($notes, 'data.0.user.id'))->toBe($this->user->id)
+ ->and(data_get($notes, 'meta.total'))->toBe(3)
+ ->and($this->actingAs($this->user)->get(route('app.posts.index'))->inertiaProps('postNotes'))->toBeNull();
+
+ config(['app.pagination.default' => 1]);
+
+ $firstPage = $this->actingAs($this->user)->get(route('app.posts.index', ['notes' => $this->post->id]));
+ $scroll = data_get($firstPage->viewData('page'), 'scrollProps.postNotes');
+ $newest->delete();
+
+ $olderPage = $this->actingAs($this->user)
+ ->get(route('app.posts.index', ['notes' => $this->post->id, data_get($scroll, 'pageName') => data_get($scroll, 'nextPage')]))
+ ->inertiaProps('postNotes');
+
+ expect(collect(data_get($firstPage->inertiaProps('postNotes'), 'data'))->pluck('id')->all())->toBe([$newest->id])
+ ->and(data_get($scroll, 'pageName'))->toBe(BuildPostNotesProps::CURSOR_NAME)
+ ->and(collect(data_get($olderPage, 'data'))->pluck('id')->all())->toBe([$middle->id])
+ ->and(data_get($olderPage, 'meta.total'))->toBe(2);
});
test('store creates a comment', function () {
@@ -70,44 +88,255 @@ test('store creates a comment', function () {
);
});
-test('note changes broadcast to the post and its workspace', function () {
- $event = new PostNoteChanged($this->post->id, $this->workspace->id, 'updated');
+test('every note change broadcasts to the post and its workspace, naming the note', function () {
+ Event::fake([PostNoteChanged::class]);
+ $this->actingAs($this->user);
- expect($event->broadcastAs())->toBe('post.note.changed')
- ->and($event->broadcastWith())->toBe([
- 'post_id' => $this->post->id,
- 'change' => 'updated',
- ])
- ->and(array_map(strval(...), $event->broadcastOn()))->toBe([
+ $note = PostNote::query()->findOrFail($this->postJson(route('app.posts.notes.store', $this->post), ['body' => 'First'])->json('id'));
+ $this->putJson(route('app.posts.notes.update', [$this->post, $note]), ['body' => 'Edited'])->assertOk();
+ $this->putJson(route('app.posts.notes.reactions.update', [$this->post, $note]), ['emoji' => '👍'])->assertOk();
+ $this->deleteJson(route('app.posts.notes.reactions.destroy', [$this->post, $note]), ['emoji' => '👍'])->assertOk();
+ $this->deleteJson(route('app.posts.notes.destroy', [$this->post, $note]))->assertNoContent();
+
+ $changes = [];
+ Event::assertDispatched(PostNoteChanged::class, function (PostNoteChanged $event) use (&$changes, $note): bool {
+ $changes[] = $event->broadcastWith();
+
+ return $event->noteId === $note->id;
+ });
+
+ expect($changes)->toBe(array_map(fn (string $change): array => ['post_id' => $this->post->id, 'note_id' => $note->id, 'change' => $change], ['created', 'updated', 'updated', 'updated', 'deleted']))
+ ->and(array_map(strval(...), (new PostNoteChanged($this->post->id, $this->workspace->id, 'updated', $note->id))->broadcastOn()))->toBe([
"private-post.{$this->post->id}",
"private-workspace.{$this->workspace->id}",
]);
});
-test('store emails every workspace member except the author', function () {
+test('store emails the post participants, not the rest of the workspace', function () {
Mail::fake();
- $admin = User::factory()->create();
- $member = User::factory()->create();
- $this->workspace->members()->attach($admin->id, membershipPivot('admin'));
- $this->workspace->members()->attach($member->id, membershipPivot('member'));
-
- $outsider = User::factory()->create();
- Workspace::factory()->create(['user_id' => $outsider->id])->members()->attach($outsider->id, membershipPivot('admin'));
+ $writer = workspaceMember($this->workspace);
+ $earlierNoteAuthor = workspaceMember($this->workspace);
+ $bystander = workspaceMember($this->workspace);
+ PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $earlierNoteAuthor->id]);
- $this->actingAs($this->user)
+ $this->actingAs($writer)
->postJson(route('app.posts.notes.store', $this->post), ['body' => "Can someone review?\nThanks"])
->assertCreated();
- $note = PostNote::query()->sole();
+ $note = PostNote::query()->where('user_id', $writer->id)->sole();
Mail::assertQueuedCount(2);
- Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($admin->email)
+ Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($this->user->email)
&& $mail->note->is($note)
- && $mail->author->is($this->user));
- Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($member->email));
- Mail::assertNotQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($this->user->email));
- Mail::assertNotQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($outsider->email));
+ && $mail->author->is($writer));
+ Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($earlierNoteAuthor->email));
+ Mail::assertNotQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($bystander->email));
+});
+
+test('a mentioned member gets the mention email instead of the note email', function () {
+ Mail::fake();
+
+ $writer = workspaceMember($this->workspace);
+ $mentioned = workspaceMember($this->workspace);
+ $outsider = workspaceOutsider($this->workspace);
+
+ $this->actingAs($writer)
+ ->postJson(route('app.posts.notes.store', $this->post), [
+ 'body' => "@[user:{$mentioned->id}] and @[user:{$outsider->id}] and @[user:{$writer->id}] take a look",
+ ])
+ ->assertCreated();
+
+ Mail::assertQueuedCount(2);
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($mentioned->email) && $mail->author->is($writer));
+ Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($this->user->email));
+ Mail::assertNotQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($mentioned->email));
+});
+
+test('editing a note emails only the people it mentions for the first time', function () {
+ Mail::fake();
+
+ $alreadyMentioned = workspaceMember($this->workspace);
+ $newlyMentioned = workspaceMember($this->workspace);
+ $note = PostNote::factory()->create([
+ 'post_id' => $this->post->id,
+ 'user_id' => $this->user->id,
+ 'body' => "@[user:{$alreadyMentioned->id}] ping",
+ ]);
+
+ $this->actingAs($this->user)
+ ->putJson(route('app.posts.notes.update', [$this->post, $note]), [
+ 'body' => "@[user:{$alreadyMentioned->id}] and @[user:{$newlyMentioned->id}] ping",
+ ])
+ ->assertOk();
+
+ Mail::assertQueuedCount(1);
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($newlyMentioned->email));
+});
+
+test('an edit that mentions yourself or someone outside the workspace emails nobody', function () {
+ Mail::fake();
+
+ $outsider = workspaceOutsider($this->workspace);
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id, 'body' => 'ping']);
+
+ $this->actingAs($this->user)
+ ->putJson(route('app.posts.notes.update', [$this->post, $note]), [
+ 'body' => "@[user:{$this->user->id}] @[user:{$outsider->id}] ping",
+ ])
+ ->assertOk();
+
+ Mail::assertNothingQueued();
+});
+
+test('the member who asked for approval of someone else post is a participant of its notes', function () {
+ Mail::fake();
+
+ $requester = workspaceMember($this->workspace, 'approval');
+ $approver = workspaceMember($this->workspace);
+ $pending = Post::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $this->user->id,
+ 'status' => PostStatus::PendingApproval,
+ 'approval_requested_by' => $requester->id,
+ ]);
+
+ $this->actingAs($approver)
+ ->postJson(route('app.posts.notes.store', $pending), ['body' => 'Swap the image first'])
+ ->assertCreated();
+
+ Mail::assertQueuedCount(2);
+ Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($requester->email));
+ Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($this->user->email));
+});
+
+test('everyone in the workspace is listed on a draft, the viewer included, sorted by name ignoring case and accents (names without a Latin form first, by their own text), with their time zone', function () {
+ $this->user->update(['name' => 'Diego', 'timezone' => 'Europe/Lisbon']);
+ $carla = workspaceMember($this->workspace, 'approval', ['name' => 'Carla']);
+ $bruno = workspaceMember($this->workspace, 'member', ['name' => 'bruno', 'timezone' => 'Asia/Tokyo']);
+ $alvaro = workspaceMember($this->workspace, 'admin', ['name' => 'Álvaro', 'timezone' => 'America/Sao_Paulo']);
+ $yamada = workspaceMember($this->workspace, 'member', ['name' => '山田']);
+ $zenin = workspaceMember($this->workspace, 'member', ['name' => '全員']);
+ workspaceOutsider($this->workspace);
+
+ $this->actingAs($carla)
+ ->getJson(route('app.posts.notes.mentionables.index', $this->post))
+ ->assertOk()
+ ->assertExactJson([
+ ['id' => $zenin->id, 'name' => '全員', 'photo_url' => $zenin->photo_url, 'timezone' => $zenin->timezone],
+ ['id' => $yamada->id, 'name' => '山田', 'photo_url' => $yamada->photo_url, 'timezone' => $yamada->timezone],
+ ['id' => $alvaro->id, 'name' => 'Álvaro', 'photo_url' => $alvaro->photo_url, 'timezone' => 'America/Sao_Paulo'],
+ ['id' => $bruno->id, 'name' => 'bruno', 'photo_url' => $bruno->photo_url, 'timezone' => 'Asia/Tokyo'],
+ ['id' => $carla->id, 'name' => 'Carla', 'photo_url' => $carla->photo_url, 'timezone' => $carla->timezone],
+ ['id' => $this->user->id, 'name' => 'Diego', 'photo_url' => $this->user->photo_url, 'timezone' => 'Europe/Lisbon'],
+ ]);
+});
+
+test('reactions go with their note and with the member who reacted', function () {
+ $teammate = workspaceMember($this->workspace);
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id]);
+ PostNoteReaction::factory()->create(['post_note_id' => $note->id, 'user_id' => $this->user->id]);
+ PostNoteReaction::factory()->create(['post_note_id' => $note->id, 'user_id' => $teammate->id]);
+
+ $teammate->delete();
+
+ expect($this->actingAs($this->user)
+ ->get(route('app.posts.index', ['notes' => $this->post->id]))
+ ->inertiaProps('postNotes.data.0.reactions.0.count'))->toBe(1);
+
+ $this->actingAs($this->user)
+ ->deleteJson(route('app.posts.notes.destroy', [$this->post, $note]))
+ ->assertNoContent();
+
+ expect(PostNoteReaction::query()->count())->toBe(0);
+});
+
+test('@all emails a mention to everyone who sees the post but the author, and no note email', function () {
+ Mail::fake();
+
+ $writer = workspaceMember($this->workspace);
+ $teammate = workspaceMember($this->workspace);
+ workspaceOutsider($this->workspace);
+
+ $this->actingAs($writer)
+ ->postJson(route('app.posts.notes.store', $this->post), ['body' => '@[everyone] take a look'])
+ ->assertCreated();
+
+ Mail::assertQueuedCount(2);
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($this->user->email));
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($teammate->email));
+ Mail::assertNotQueued(PostNoteAdded::class);
+});
+
+test('@all on a pending request reaches only the approvers and the member who asked', function () {
+ Mail::fake();
+
+ $requester = workspaceMember($this->workspace, 'approval');
+ $bystander = workspaceMember($this->workspace, 'approval');
+ $approver = workspaceMember($this->workspace);
+ $pending = Post::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $requester->id,
+ 'status' => PostStatus::PendingApproval,
+ 'approval_requested_by' => $requester->id,
+ ]);
+
+ $this->actingAs($approver)
+ ->postJson(route('app.posts.notes.store', $pending), ['body' => '@[everyone] ready?'])
+ ->assertCreated();
+
+ Mail::assertQueuedCount(2);
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($this->user->email));
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($requester->email));
+ Mail::assertNotQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($bystander->email));
+});
+
+test('an edit that adds @all emails only the people it had not mentioned yet', function () {
+ Mail::fake();
+
+ $alreadyMentioned = workspaceMember($this->workspace);
+ $newlyMentioned = workspaceMember($this->workspace);
+ $note = PostNote::factory()->create([
+ 'post_id' => $this->post->id,
+ 'user_id' => $this->user->id,
+ 'body' => "@[user:{$alreadyMentioned->id}] ping",
+ ]);
+
+ $this->actingAs($this->user)
+ ->putJson(route('app.posts.notes.update', [$this->post, $note]), ['body' => '@[everyone] ping'])
+ ->assertOk();
+
+ Mail::assertQueuedCount(1);
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($newlyMentioned->email));
+});
+
+test('a note keeps only the mentions of people who see the post, and shows them with their current name', function () {
+ $teammate = workspaceMember($this->workspace, 'member', ['name' => 'Bia Lima']);
+ $outsider = workspaceOutsider($this->workspace);
+
+ $created = $this->actingAs($this->user)
+ ->postJson(route('app.posts.notes.store', $this->post), [
+ 'body' => "@[user:{$teammate->id}] and @[user:{$outsider->id}] @[everyone]",
+ ])
+ ->assertCreated()
+ ->assertJsonPath('mentions', [['id' => $teammate->id, 'name' => 'Bia Lima']]);
+
+ $note = PostNote::query()->sole();
+ expect($note->body)->toBe("@[user:{$teammate->id}] and @[everyone]")
+ ->and($note->mentions()->pluck('users.id')->all())->toBe([$teammate->id]);
+
+ $teammate->update(['name' => 'Bia Souza']);
+
+ expect($this->actingAs($this->user)
+ ->get(route('app.posts.index', ['notes' => $this->post->id]))
+ ->inertiaProps('postNotes.data.0.mentions'))->toBe([['id' => $teammate->id, 'name' => 'Bia Souza']]);
+
+ $this->actingAs($this->user)
+ ->putJson(route('app.posts.notes.update', [$this->post, $created->json('id')]), ['body' => 'no mention now'])
+ ->assertOk()
+ ->assertJsonPath('mentions', []);
+
+ expect($note->mentions()->count())->toBe(0);
});
test('store emails the workspace owner when a member adds a note', function () {
@@ -123,7 +352,7 @@ test('store emails the workspace owner when a member adds a note', function () {
Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($this->user->email));
});
-test('a note on a pending request emails only the approvers and the requester', function () {
+test('a note on a pending request emails and mentions only the approvers and the requester', function () {
Mail::fake();
$requester = workspaceMember($this->workspace, 'approval');
@@ -137,24 +366,26 @@ test('a note on a pending request emails only the approvers and the requester',
]);
$this->actingAs($approver)
- ->postJson(route('app.posts.notes.store', $pending), ['body' => 'Pricing changes Friday'])
+ ->postJson(route('app.posts.notes.store', $pending), [
+ 'body' => "Pricing changes Friday, @[user:{$bystander->id}] @[user:{$this->user->id}]",
+ ])
->assertCreated();
Mail::assertQueuedCount(2);
- Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($this->user->email));
+ Mail::assertQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($this->user->email));
Mail::assertQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($requester->email));
- Mail::assertNotQueued(PostNoteAdded::class, fn (PostNoteAdded $mail) => $mail->hasTo($bystander->email));
+ Mail::assertNotQueued(PostNoteMentioned::class, fn (PostNoteMentioned $mail) => $mail->hasTo($bystander->email));
});
test('store respects a member who turned note emails off', function () {
Mail::fake();
- $member = User::factory()->create();
- $this->workspace->members()->attach($member->id, membershipPivot('member'));
+ $member = workspaceMember($this->workspace);
$member->notificationPreference()->create(['post_note_added' => false]);
+ PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $member->id]);
$this->actingAs($this->user)
- ->postJson(route('app.posts.notes.store', $this->post), ['body' => 'Hello'])
+ ->postJson(route('app.posts.notes.store', $this->post), ['body' => "Hello @[user:{$member->id}]"])
->assertCreated();
Mail::assertNothingQueued();
@@ -232,6 +463,95 @@ test('cannot update other user comment', function () {
$response->assertForbidden();
});
+test('an email about a note deleted before it goes out is dropped instead of failing', function (int $jobsBeforeDeleting) {
+ config()->set('queue.default', 'database');
+ Queue::swap(Queue::getFacadeRoot()->queue);
+ $worker = app('queue.worker');
+ $options = new WorkerOptions(sleep: 0, maxTries: 1);
+ $failed = [];
+ Queue::failing(function (JobFailed $event) use (&$failed): void {
+ $failed[] = $event->job->resolveName();
+ });
+
+ $this->actingAs(workspaceMember($this->workspace))
+ ->postJson(route('app.posts.notes.store', $this->post), ['body' => 'Tpyo'])
+ ->assertCreated();
+
+ for ($job = 0; $job < $jobsBeforeDeleting; $job++) {
+ $worker->runNextJob('database', 'default', $options);
+ }
+
+ PostNote::query()->sole()->delete();
+ $worker->runNextJob('database', 'default', $options);
+
+ expect(Queue::connection('database')->size('default'))->toBe(0)
+ ->and($failed)->toBe([]);
+})->with([
+ 'before the notification job runs' => [0],
+ 'between the notification job and the email it queues' => [1],
+]);
+
+test('a link with a malformed note or post id opens the page without a thread', function (mixed $notes, mixed $note) {
+ $page = $this->actingAs($this->user)
+ ->get(route('app.posts.index', ['notes' => $notes, 'note' => $note]))
+ ->assertOk();
+
+ expect($page->inertiaProps('openPostNotesId'))->toBeNull()
+ ->and($page->inertiaProps('highlightNoteId'))->toBeNull()
+ ->and($page->inertiaProps('postNotes'))->toBeNull();
+})->with([
+ 'not a uuid' => ['abc', 'abc'],
+ 'an array' => [['x'], ['y']],
+ 'a uuid of nothing' => [fn (): string => Str::uuid()->toString(), null],
+]);
+
+test('a link to a note that is gone or on another post opens the thread without a highlight', function (Closure $noteId) {
+ $page = $this->actingAs($this->user)
+ ->get(route('app.posts.index', ['notes' => $this->post->id, 'note' => $noteId($this)]))
+ ->assertOk();
+
+ expect($page->inertiaProps('openPostNotesId'))->toBe($this->post->id)
+ ->and($page->inertiaProps('highlightNoteId'))->toBeNull();
+})->with([
+ 'a deleted note' => [function ($test): string {
+ $note = PostNote::factory()->create(['post_id' => $test->post->id, 'user_id' => $test->user->id]);
+ $note->delete();
+
+ return $note->id;
+ }],
+ 'a note of another post' => [fn ($test): string => PostNote::factory()->create([
+ 'post_id' => Post::factory()->create(['workspace_id' => $test->workspace->id, 'user_id' => $test->user->id])->id,
+ 'user_id' => $test->user->id,
+ ])->id],
+]);
+
+test('an edit drops the mention of someone who no longer sees the post', function () {
+ $teammate = workspaceMember($this->workspace);
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id, 'body' => "Ask @[user:{$teammate->id}]"]);
+ $note->mentions()->attach($teammate);
+ $this->workspace->members()->detach($teammate);
+
+ $this->actingAs($this->user)
+ ->putJson(route('app.posts.notes.update', [$this->post, $note]), ['body' => "Ask @[user:{$teammate->id}] again"])
+ ->assertOk()
+ ->assertJsonPath('mentions', []);
+
+ expect($note->fresh()->body)->toBe('Ask again')
+ ->and($note->mentions()->count())->toBe(0);
+});
+
+test('deleting a note takes its reactions and mentions with it', function () {
+ $teammate = workspaceMember($this->workspace);
+ $note = PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id, 'body' => "Ask @[user:{$teammate->id}]"]);
+ $note->mentions()->attach($teammate);
+ PostNoteReaction::factory()->create(['post_note_id' => $note->id, 'user_id' => $teammate->id, 'emoji' => '👍']);
+
+ $this->actingAs($this->user)->deleteJson(route('app.posts.notes.destroy', [$this->post, $note]))->assertNoContent();
+
+ expect(PostNoteReaction::query()->count())->toBe(0);
+ $this->assertDatabaseCount('post_note_mentions', 0);
+});
+
test('delete own comment', function () {
$comment = PostNote::factory()->create([
'post_id' => $this->post->id,
@@ -286,9 +606,9 @@ test('notes expose only the author id, name and photo', function () {
]);
PostNote::factory()->create(['post_id' => $this->post->id, 'user_id' => $this->user->id]);
- $index = $this->actingAs($this->user)
- ->getJson(route('app.posts.notes.index', $this->post))
- ->assertOk();
+ $listed = $this->actingAs($this->user)
+ ->get(route('app.posts.index', ['notes' => $this->post->id]))
+ ->inertiaProps('postNotes.data');
$store = $this->actingAs($this->user)
->postJson(route('app.posts.notes.store', $this->post), ['body' => 'Hi'])
->assertCreated();
@@ -296,19 +616,17 @@ test('notes expose only the author id, name and photo', function () {
->putJson(route('app.posts.notes.update', [$this->post, $store->json('id')]), ['body' => 'Edited'])
->assertOk();
- foreach ([$index->json('data.0.user'), $store->json('user'), $update->json('user')] as $author) {
+ foreach ([data_get($listed, '0.user'), $store->json('user'), $update->json('user')] as $author) {
expect(array_keys($author))->toEqualCanonicalizing(['id', 'name', 'photo_url'])
->and($author['id'])->toBe($this->user->id);
}
- foreach ([$index, $store, $update] as $response) {
+ foreach ([json_encode($listed), $store->getContent(), $update->getContent()] as $content) {
foreach (['email', 'registration_ip', 'google_id', 'github_id', 'utm_source', 'persona', '203.0.113.7', $this->user->email] as $leak) {
- expect($response->getContent())->not->toContain($leak);
+ expect($content)->not->toContain($leak);
}
}
- expect($index->json('meta.current_page'))->toBe(1)
- ->and($index->json('meta.last_page'))->toBe(1);
});
test('a member who needs approval cannot see notes of another member pending request', function () {
@@ -322,7 +640,7 @@ test('a member who needs approval cannot see notes of another member pending req
]);
$note = PostNote::factory()->create(['post_id' => $pending->id, 'user_id' => $other->id]);
- $this->actingAs($other)->getJson(route('app.posts.notes.index', $pending))->assertNotFound();
+ expect($this->actingAs($other)->get(route('app.posts.index', ['notes' => $pending->id]))->inertiaProps('postNotes'))->toBeNull();
$this->actingAs($other)->postJson(route('app.posts.notes.store', $pending), ['body' => 'Hi'])->assertNotFound();
$this->actingAs($other)->putJson(route('app.posts.notes.update', [$pending, $note]), ['body' => 'Hi'])->assertNotFound();
$this->actingAs($other)->deleteJson(route('app.posts.notes.destroy', [$pending, $note]))->assertNotFound();
@@ -333,6 +651,6 @@ test('a member who needs approval cannot see notes of another member pending req
test('a user outside the workspace cannot read or add notes', function () {
$outsider = workspaceOutsider($this->workspace);
- $this->actingAs($outsider)->getJson(route('app.posts.notes.index', $this->post))->assertForbidden();
+ $this->actingAs($outsider)->get(route('app.posts.index', ['notes' => $this->post->id]))->assertForbidden();
$this->actingAs($outsider)->postJson(route('app.posts.notes.store', $this->post), ['body' => 'Hi'])->assertForbidden();
});
diff --git a/tests/Feature/Rules/SingleEmojiTest.php b/tests/Feature/Rules/SingleEmojiTest.php
new file mode 100644
index 000000000..3c4fab74e
--- /dev/null
+++ b/tests/Feature/Rules/SingleEmojiTest.php
@@ -0,0 +1,27 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Rules\SingleEmoji;
+use Illuminate\Support\Facades\Validator;
+use Symfony\Component\Process\ExecutableFinder;
+use Symfony\Component\Process\Process;
+
+test('every emoji the picker offers is a valid reaction', function () {
+ $node = (new ExecutableFinder)->find('node');
+
+ if ($node === null) {
+ test()->markTestSkipped('node is unavailable');
+ }
+
+ $process = (new Process([$node, base_path('tests/fixtures/emoji-picker-harness.ts'), resource_path('js')]))->mustRun();
+ $emojis = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
+
+ $refused = collect($emojis)
+ ->reject(fn (string $emoji): bool => Validator::make(['emoji' => $emoji], ['emoji' => [new SingleEmoji]])->passes())
+ ->values()
+ ->all();
+
+ expect($emojis)->not->toBeEmpty()
+ ->and($refused)->toBe([]);
+});
diff --git a/tests/Pest.php b/tests/Pest.php
index f942b1469..089fc082e 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -728,7 +728,8 @@ function waitForWebFonts(mixed $page): void
/**
* Wait until a JavaScript expression is true in the page, for up to 30
- * seconds (longer for a slow import or a fallback that polls the server).
+ * seconds (longer for a slow import or a fallback that polls the server),
+ * and fail the test when it never is: every wait is also an assertion.
* Assertions do not wait for the SPA to paint, and a blocking sleep() would
* starve the server that serves the page, so the page polls.
*/
@@ -736,25 +737,32 @@ function waitForCondition(mixed $page, string $condition, int $seconds = 30): vo
{
$attempts = $seconds * 20;
- $page->script(<<<JS
+ $met = $page->script(<<<JS
(async () => {
for (let i = 0; i < {$attempts}; i++) {
- if ({$condition}) return;
+ if ({$condition}) return true;
await new Promise((resolve) => setTimeout(resolve, 50));
}
+
+ return false;
})();
JS);
+
+ expect($met)->toBeTrue("Waited {$seconds}s for: {$condition}");
}
/**
* Wait until a condition the test reads on the server (a row in the database)
- * holds, letting the page's own requests land between tries.
+ * holds, letting the page's own requests land between tries, and fail the
+ * test when it never does.
*/
function waitForDatabase(mixed $page, Closure $condition): void
{
for ($attempt = 0; $attempt < 50 && ! $condition(); $attempt++) {
$page->script('new Promise((resolve) => setTimeout(resolve, 100))');
}
+
+ expect($condition())->toBeTrue('Waited 5s for a condition on the server.');
}
/**
@@ -778,6 +786,17 @@ function jsSelector(string $selector): string
return json_encode(preg_replace('/@([\w-]+)/', '[data-testid="$1"]', $selector));
}
+/**
+ * Wait until the note editor matching the selector shows that text, trimmed.
+ * The editor is a contenteditable, so it has no value to assert.
+ */
+function waitForEditorText(mixed $page, string $selector, string $text): void
+{
+ $text = json_encode($text, JSON_THROW_ON_ERROR);
+
+ waitForState($page, $selector, "element.innerText.trim() === {$text}");
+}
+
/**
* Wait until an element matching the selector exists and the expression,
* written about `element`, is true: "element.getAttribute('aria-checked') === 'true'".
diff --git a/tests/Unit/PostNoteMentionsTest.php b/tests/Unit/PostNoteMentionsTest.php
new file mode 100644
index 000000000..663749d36
--- /dev/null
+++ b/tests/Unit/PostNoteMentionsTest.php
@@ -0,0 +1,41 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Models\User;
+use App\Support\PostNoteMentions;
+use Illuminate\Support\Facades\File;
+use Illuminate\Support\Str;
+
+/**
+ * The server is the one place that reads mention markup: it splits a note into
+ * parts for the app, and the note editor (TipTap) writes the markup back
+ * (`PostNotesTest` saves a note through the editor unchanged).
+ */
+test('a note splits into its text, its people and everyone, in order and with nothing lost', function () {
+ $corpus = File::json(base_path('tests/fixtures/note-mentions-corpus.json'), JSON_THROW_ON_ERROR);
+
+ foreach ($corpus as $body) {
+ $parts = PostNoteMentions::parts($body, collect());
+ $rebuilt = collect($parts)->map(fn (array $part): string => match (data_get($part, 'type')) {
+ 'text' => data_get($part, 'text'),
+ 'mention' => "@[user:{$part['id']}]",
+ 'everyone' => '@[everyone]',
+ })->implode('');
+
+ expect(Str::lower($rebuilt))->toBe(Str::lower($body))
+ ->and(collect($parts)->where('type', 'mention')->pluck('id')->unique()->values()->all())->toBe(PostNoteMentions::extract($body)->all())
+ ->and(collect($parts)->contains('type', 'everyone'))->toBe(PostNoteMentions::mentionsEveryone($body));
+ }
+});
+
+test('a mention part carries the name of the person it names, or null once they are gone', function () {
+ $people = collect([User::factory()->make(['name' => 'Bia Lima'])->forceFill(['id' => '0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f'])]);
+
+ expect(PostNoteMentions::parts('Ask @[user:0198D0AA-1B2C-7D3E-8F40-5A6B7C8D9E0F] and @[user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e1f]', $people))->toBe([
+ ['type' => 'text', 'text' => 'Ask '],
+ ['type' => 'mention', 'id' => '0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f', 'name' => 'Bia Lima'],
+ ['type' => 'text', 'text' => ' and '],
+ ['type' => 'mention', 'id' => '0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e1f', 'name' => null],
+ ]);
+});
diff --git a/tests/fixtures/emoji-picker-harness.ts b/tests/fixtures/emoji-picker-harness.ts
new file mode 100644
index 000000000..6114483f3
--- /dev/null
+++ b/tests/fixtures/emoji-picker-harness.ts
@@ -0,0 +1,12 @@
+/**
+ * Prints every emoji the picker offers (`data/emojis.ts`), so
+ * `SingleEmojiTest.php` can check the server takes each one as a reaction.
+ */
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const [resourcesDir] = process.argv.slice(2);
+
+const { EMOJIS } = await import(pathToFileURL(path.join(path.resolve(resourcesDir), 'data/emojis.ts')).href);
+
+console.log(JSON.stringify(EMOJIS.map((emoji: { c: string }) => emoji.c)));
diff --git a/tests/fixtures/note-mentions-corpus.json b/tests/fixtures/note-mentions-corpus.json
new file mode 100644
index 000000000..26e8337fe
--- /dev/null
+++ b/tests/fixtures/note-mentions-corpus.json
@@ -0,0 +1,13 @@
+[
+ "No mention here",
+ "@[user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f] can you check?",
+ "@[user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f] and @[user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f] once",
+ "Uppercase id @[user:0198D0AA-1B2C-7D3E-8F40-5A6B7C8D9E1F]",
+ "Not hex @[user:0198d0aa-1b2c-7d3e-8f40-zzzzzzzzzzzz]",
+ "Not a uuid @[user:------------------------------------]",
+ "Broken @[user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f",
+ "Line\n@[user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e1f], and emoji 🎉 @[user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f]",
+ "@[everyone] please review",
+ "Heads up @[everyone] and @[user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f]",
+ "Old format @[Ana](user:0198d0aa-1b2c-7d3e-8f40-5a6b7c8d9e0f) is text"
+]
diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.php
index 656faa27a..7c8f4be74 100644
--- a/tests/fixtures/single-line-copy.php
+++ b/tests/fixtures/single-line-copy.php
@@ -89,6 +89,8 @@ return [
'mcp.authorize.cancel' => 9,
'mcp.authorize.select_workspace' => 28,
'mcp.subtitle' => 45,
+ 'notes.mention_everyone.description' => 35,
+ 'notes.mention_everyone.word' => 8,
'notes.title' => 10,
'posts.approvals.approve' => 10,
'posts.approvals.reject' => 9,