feat: add CommentsTab component with replies, reactions, and real-time

This commit is contained in:
Paulo Castellano 2026-04-15 20:15:29 -03:00
parent 0f6ae9a4e6
commit ced8bc818b
23 changed files with 1688 additions and 528 deletions

View file

@ -8,16 +8,6 @@
# Cashier Stripe Development
## When to Apply
Activate this skill when:
- Installing or configuring Laravel Cashier Stripe
- Setting up subscriptions, trials, quantities, or plan swapping
- Handling webhooks or SCA/3DS payment failures
- Working with Stripe Checkout, invoices, or charges
- Testing billing scenarios with Stripe test cards or tokens
## Documentation
Use `search-docs` for detailed Cashier patterns and documentation covering subscriptions, webhooks, Stripe Checkout, invoices, payment methods, and testing.

View file

@ -0,0 +1,404 @@
---
name: configure-nightwatch
description: Configures Laravel Nightwatch data collection, sampling rates, filtering rules, and redaction policies. Use when setting up Nightwatch, managing data volume, protecting sensitive data (PII), or optimizing event collection for production workloads.
license: MIT
metadata:
author: laravel
---
# Nightwatch Configuration Guide
This skill helps configure Laravel Nightwatch data collection to balance observability, performance, and privacy. Covers sampling strategies, filtering rules, and redaction methods across all event types.
## Documentation Reference
The [Nightwatch Documentation](https://nightwatch.laravel.com/docs) is the definitive and up-to-date source of information for all Nightwatch configuration options. This skill provides practical guidance and common patterns, but always consult the official documentation as the primary source of truth for specific details, environment variables, and API behavior. The documentation includes comprehensive coverage of:
- [Filtering and Configuration](https://nightwatch.laravel.com/docs/filtering) - Core concepts for sampling, filtering, and redaction
- Individual event type pages with specific configuration options:
- [Requests](https://nightwatch.laravel.com/docs/requests) - Request sampling, header handling, payload capture
- [Commands](https://nightwatch.laravel.com/docs/commands) - Command sampling and redaction
- [Queries](https://nightwatch.laravel.com/docs/queries) - Query filtering and redaction
- [Cache](https://nightwatch.laravel.com/docs/cache) - Cache event filtering by key or pattern
- [Jobs](https://nightwatch.laravel.com/docs/jobs) - Job filtering and sampling decoupling
- [Mail](https://nightwatch.laravel.com/docs/mail) - Mail event filtering
- [Notifications](https://nightwatch.laravel.com/docs/notifications) - Notification filtering by channel
- [Exceptions](https://nightwatch.laravel.com/docs/exceptions) - Exception sampling and throttling
- [Outgoing Requests](https://nightwatch.laravel.com/docs/outgoing-requests) - HTTP request filtering
- [reference.md](reference.md) - Quick lookup table by event type, production presets, and verification checklist
## Data Collection Flow
Nightwatch processes events through three stages:
1. **Sampling** - Controls which entry points are captured (requests, commands, scheduled tasks)
2. **Filtering** - Excludes specific events after sampling (queries, cache, mail, etc.)
3. **Redaction** - Modifies captured data to remove/obfuscate sensitive information
```
Request/Command/Scheduled Task
|
v
[Sampling?] ----NO----> Drop entire trace
| YES
v
Events generated
|
v
[Filtering?] ----YES---> Drop specific event
| NO
v
[Redaction] ----------> Store modified data
```
---
## Sampling Configuration
Sampling determines which entry points (requests, commands, scheduled tasks) trigger full trace collection. When an entry point is sampled, all related events are captured.
### Global Sample Rates
Configure via environment variables:
```bash
# Default: 100% sampling (all requests/commands captured)
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1 # Recommended: 10% of requests
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0 # Capture all commands
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
```
**Recommendation**: Start with `0.1` (10%) for requests in production, adjust based on volume and needs.
### Route-Based Sampling
Apply different rates to specific routes using the `Sample` middleware:
```php routes/web.php
use Illuminate\Support\Facades\Route;
use Laravel\Nightwatch\Http\Middleware\Sample;
// Sample admin routes at 100%
Route::middleware(Sample::rate(1.0))->prefix('admin')->group(function () {
// All admin routes sampled fully
});
// Sample API routes at 5%
Route::middleware(Sample::rate(0.05))->prefix('api')->group(function () {
// API routes sampled sparingly
});
// Always sample critical endpoints
Route::post('/checkout', [CheckoutController::class, 'process'])
->middleware(Sample::always());
// Never sample health checks
Route::get('/health', [HealthController::class, 'check'])
->middleware(Sample::never());
```
### Unmatched Route Sampling
Handle 404/bot traffic with reduced sampling:
```php routes/web.php
Route::fallback(fn () => abort(404))
->middleware(Sample::rate(0.01)); // 1% sampling for unmatched routes
```
### Dynamic Sampling
Sample based on runtime conditions (user role, request attributes):
```php app/Http/Middleware/SampleAdminRequests.php
use Closure;
use Illuminate\Http\Request;
use Laravel\Nightwatch\Facades\Nightwatch;
class SampleAdminRequests
{
public function handle(Request $request, Closure $next)
{
if ($request->user()?->isAdmin()) {
Nightwatch::sample(); // Always sample admin requests
}
return $next($request);
}
}
```
### Command Sampling
Exclude specific commands from sampling:
```php AppServiceProvider.php
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Support\Facades\Event;
use Laravel\Nightwatch\Facades\Nightwatch;
public function boot(): void
{
Event::listen(function (CommandStarting $event) {
if (in_array($event->command, ['schedule:finish', 'horizon:snapshot'])) {
Nightwatch::dontSample();
}
});
}
```
### Vendor Commands
Nightwatch automatically ignores framework/internal commands. Opt-in to capture them:
```php
Nightwatch::captureDefaultVendorCommands();
```
---
## Filtering Configuration
Filtering excludes specific events from collection after sampling. Use filtering to reduce noise and quota usage.
### Database Queries
**Filter all queries** (disable query collection):
```bash
NIGHTWATCH_IGNORE_QUERIES=true
```
**Filter specific queries** by SQL pattern:
```php AppServiceProvider.php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Query;
public function boot(): void
{
// Filter job table queries (PostgreSQL)
Nightwatch::rejectQueries(function (Query $query) {
return str_contains($query->sql, 'into "jobs"');
});
// Filter cache table queries (MySQL)
Nightwatch::rejectQueries(function (Query $query) {
return str_contains($query->sql, 'from `cache`')
|| str_contains($query->sql, 'into `cache`');
});
}
```
### Cache Events
**Filter all cache events**:
```bash
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
```
**Filter by cache key patterns**:
```php
Nightwatch::rejectCacheKeys([
'my-app:users', // Exact match
'/^my-app:posts:/', // Regex: starts with my-app:posts:
'/^[a-zA-Z0-9]{40}$/', // Regex: session IDs
]);
```
**Filter with callback**:
```php
use Laravel\Nightwatch\Records\CacheEvent;
Nightwatch::rejectCacheEvents(function (CacheEvent $cacheEvent) {
return str_starts_with($cacheEvent->key, 'temp:');
});
```
### Mail Events
**Filter all mail**:
```bash
NIGHTWATCH_IGNORE_MAIL=true
```
**Filter specific mail**:
```php
use Laravel\Nightwatch\Records\Mail;
Nightwatch::rejectMail(function (Mail $mail) {
return str_contains($mail->subject, 'Newsletter');
});
```
### Notification Events
**Filter all notifications**:
```bash
NIGHTWATCH_IGNORE_NOTIFICATIONS=true
```
**Filter by channel**:
```php
use Laravel\Nightwatch\Records\Notification;
Nightwatch::rejectNotifications(function (Notification $notification) {
return $notification->channel === 'database';
});
```
### Outgoing HTTP Requests
**Filter all outgoing requests**:
```bash
NIGHTWATCH_IGNORE_OUTGOING_REQUESTS=true
```
**Filter by URL**:
```php
use Laravel\Nightwatch\Records\OutgoingRequest;
Nightwatch::rejectOutgoingRequests(function (OutgoingRequest $request) {
return str_contains($request->url, 'analytics.example.com');
});
```
### Queued Jobs
**Filter specific jobs**:
```php
use Laravel\Nightwatch\Records\QueuedJob;
Nightwatch::rejectQueuedJobs(function (QueuedJob $job) {
return $job->name === 'App\Jobs\LowPriorityJob';
});
```
### Decoupling Job Sampling
Sample jobs independently from parent contexts:
```php
use Illuminate\Support\Facades\Queue;
public function boot(): void
{
Queue::before(fn () => Nightwatch::sample(rate: 0.5));
}
```
---
## Redaction Configuration
Redaction modifies captured data to remove or obfuscate sensitive information. Unlike filtering, redaction keeps the event but sanitizes its content.
### Request Redaction
**Redact sensitive headers** (automatically redacts: Authorization, Cookie, X-XSRF-TOKEN):
```bash
# Customize redacted headers
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-API-Key
```
**Redact request payloads** (disabled by default):
```bash
# Enable payload capture
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=true
# Customize redacted fields
NIGHTWATCH_REDACT_PAYLOAD_FIELDS=password,password_confirmation,ssn,credit_card
```
**Programmatic redaction**:
```php
use Laravel\Nightwatch\Facades\Nightwatch;
use Laravel\Nightwatch\Records\Request;
Nightwatch::redactRequests(function (Request $request) {
$request->url = str_replace('secret', '***', $request->url);
$request->ip = preg_replace('/\d+$/', '***', $request->ip);
});
```
### Query Redaction
```php
use Laravel\Nightwatch\Records\Query;
Nightwatch::redactQueries(function (Query $query) {
$query->sql = str_replace('secret_token', '***', $query->sql);
});
```
### Cache Redaction
```php
use Laravel\Nightwatch\Records\CacheEvent;
Nightwatch::redactCacheEvents(function (CacheEvent $cacheEvent) {
$cacheEvent->key = str_replace('user:', 'user:***:', $cacheEvent->key);
});
```
### Command Redaction
```php
use Laravel\Nightwatch\Records\Command;
Nightwatch::redactCommands(function (Command $command) {
$command->command = preg_replace('/--password=\S+/', '--password=***', $command->command);
});
```
### Exception Redaction
```php
use Laravel\Nightwatch\Records\Exception;
Nightwatch::redactExceptions(function (Exception $exception) {
$exception->message = str_replace('secret', '***', $exception->message);
});
```
### Mail Redaction
```php
use Laravel\Nightwatch\Records\Mail;
Nightwatch::redactMail(function (Mail $mail) {
$mail->subject = str_replace('Invoice #', 'Invoice ***', $mail->subject);
});
```
### Outgoing Request Redaction
```php
use Laravel\Nightwatch\Records\OutgoingRequest;
Nightwatch::redactOutgoingRequests(function (OutgoingRequest $outgoingRequest) {
$outgoingRequest->url = preg_replace('/api_key=\w+/', 'api_key=***', $outgoingRequest->url);
});
```

View file

@ -0,0 +1,108 @@
# Nightwatch Configuration Reference
## Configuration Summary by Event Type
| Event Type | Sampling | Filtering | Redaction |
| --------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------- |
| **Requests** | `NIGHTWATCH_REQUEST_SAMPLE_RATE`, Route middleware | Not applicable | Headers, payload, URL, IP |
| **Commands** | `NIGHTWATCH_COMMAND_SAMPLE_RATE`, Event listener | Not applicable | Command arguments |
| **Queries** | Parent context | `rejectQueries()`, `NIGHTWATCH_IGNORE_QUERIES` | SQL statement |
| **Cache** | Parent context | `rejectCacheKeys()`, `rejectCacheEvents()`, `NIGHTWATCH_IGNORE_CACHE_EVENTS` | Cache key |
| **Jobs** | Parent context, Queue::before | `rejectQueuedJobs()` | Not applicable |
| **Mail** | Parent context | `rejectMail()`, `NIGHTWATCH_IGNORE_MAIL` | Subject |
| **Notifications** | Parent context | `rejectNotifications()`, `NIGHTWATCH_IGNORE_NOTIFICATIONS` | Not applicable |
| **Outgoing Requests** | Parent context | `rejectOutgoingRequests()`, `NIGHTWATCH_IGNORE_OUTGOING_REQUESTS` | URL |
| **Exceptions** | `NIGHTWATCH_EXCEPTION_SAMPLE_RATE` | Not applicable | Exception message |
---
## Production Recommendations
### High-Traffic Applications
```bash
# Conservative sampling
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.01 # 1% of requests
NIGHTWATCH_COMMAND_SAMPLE_RATE=0.1 # 10% of commands
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0 # Always capture exceptions
# Filter noisy events
NIGHTWATCH_IGNORE_CACHE_EVENTS=true
NIGHTWATCH_IGNORE_QUERIES=true # Or filter specific queries programmatically
```
### Privacy-Conscious Applications
```bash
# Disable sensitive data collection
NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD=false
NIGHTWATCH_REDACT_HEADERS=Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN
# Or use redaction in AppServiceProvider
```
### Balanced Configuration (Recommended Start)
```bash
# Sample rates
NIGHTWATCH_REQUEST_SAMPLE_RATE=0.1
NIGHTWATCH_COMMAND_SAMPLE_RATE=1.0
NIGHTWATCH_EXCEPTION_SAMPLE_RATE=1.0
# Filter obvious noise programmatically
# Redact PII as needed
```
---
## Verification Checklist
After configuration:
- [ ] Sampling rates appropriate for traffic volume
- [ ] Noisy events filtered (cache, certain queries)
- [ ] Sensitive data redacted (PII, tokens, credentials)
- [ ] Exceptions always captured for debugging
- [ ] Test in development with `NIGHTWATCH_REQUEST_SAMPLE_RATE=1.0`
- [ ] Monitor event quota usage in Nightwatch dashboard
---
## Common Patterns
### Filter Health Checks + Reduce Sampling
```php
Route::get('/health', fn() => ['status' => 'ok'])
->middleware(Sample::never());
```
### Exclude Internal/Vendor Queries
```php
Nightwatch::rejectQueries(fn($q) =>
str_contains($q->sql, 'telescope') ||
str_contains($q->sql, 'pulse')
);
```
### Protect User Data in Cache Keys
```php
Nightwatch::redactCacheEvents(fn($e) =>
$e->key = preg_replace('/user:\d+/', 'user:***', $e->key)
);
```

View file

@ -94,7 +94,7 @@ ### 8. Testing Patterns → `rules/testing.md`
### 9. Queue & Job Patterns → `rules/queue-jobs.md`
- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`
- `ShouldBeUnique` to prevent duplicates; `WithoutOverlapping::untilProcessing()` for concurrency
- `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release
- Always implement `failed()`; with `retryUntil()`, set `$tries = 0`
- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs
- Horizon for complex multi-queue scenarios

View file

@ -82,7 +82,7 @@ ## Code to Interfaces
## Default Sort by Descending
When no explicit order is specified, sort by `id` or `created_at` descending. Explicit ordering prevents cross-database inconsistencies between MySQL and Postgres.
When no explicit order is specified, sort by `id` or `created_at` descending. Without an explicit `ORDER BY`, row order is undefined.
Incorrect:
```php

View file

@ -2,7 +2,7 @@ # Caching Best Practices
## Use `Cache::remember()` Instead of Manual Get/Put
Atomic pattern prevents race conditions and removes boilerplate.
Cleaner cache-aside pattern that removes boilerplate. use `Cache::lock()` for race conditions.
Incorrect:
```php

View file

@ -2,7 +2,7 @@ # Configuration Best Practices
## `env()` Only in Config Files
Direct `env()` calls return `null` when config is cached.
Direct `env()` calls may return `null` when config is cached.
Incorrect:
```php

View file

@ -29,7 +29,11 @@ ## Always Queue Notifications
## Use `afterCommit()` on Notifications in Transactions
Same race condition as events — the queued notification job may run before the transaction commits.
Same race condition as events — call `afterCommit()` to delay dispatch until the transaction commits.
```php
$user->notify((new InvoicePaid($invoice))->afterCommit());
```
## Route Notification Channels to Dedicated Queues

View file

@ -52,7 +52,7 @@ ## Use Retry with Backoff for External APIs
Only retry on specific errors:
```php
$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) {
$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
return $exception instanceof ConnectionException
|| ($exception instanceof RequestException && $exception->response->serverError());
})->post('https://api.example.com/data');

View file

@ -10,7 +10,7 @@ ## Use `afterCommit()` on Mailables Inside Transactions
## Use `assertQueued()` Not `assertSent()` for Queued Mailables
`Mail::assertSent()` only catches synchronous mail. Queued mailables silently pass `assertSent`, giving false confidence.
`Mail::assertSent()` only catches synchronous mail. Queued mailables fail `assertSent` with a "Did you mean to use assertQueued()?" hint.
Incorrect: `Mail::assertSent(OrderShipped::class);` when mailable implements `ShouldQueue`.

View file

@ -106,25 +106,23 @@ ## `retryUntil()` Needs `$tries = 0`
```php
public $tries = 0;
public function retryUntil(): DateTime
public function retryUntil(): \DateTimeInterface
{
return now()->addHours(4);
}
```
## Use `WithoutOverlapping::untilProcessing()`
## Use `ShouldBeUniqueUntilProcessing` for Early Lock Release
Prevents concurrent execution while allowing new instances to queue.
`ShouldBeUnique` holds the lock until the job completes. `ShouldBeUniqueUntilProcessing` releases it when processing starts, allowing new instances to queue.
```php
public function middleware(): array
class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing
{
return [new WithoutOverlapping($this->product->id)->untilProcessing()];
// Lock releases when processing begins, not when it finishes
}
```
Without `untilProcessing()`, the lock extends through queue wait time. With it, the lock releases when processing starts.
## Use Horizon for Complex Queue Scenarios
Use Laravel Horizon when you need monitoring, auto-scaling, failure tracking, or multiple queues with different priorities.

View file

@ -36,7 +36,8 @@ ## Use Resource Controllers
```php
Route::resource('posts', PostController::class);
Route::apiResource('api/posts', Api\PostController::class);
// In routes/api.php — the /api prefix is applied automatically
Route::apiResource('posts', Api\PostController::class);
```
## Keep Controllers Thin

View file

@ -32,7 +32,7 @@ ## Authorize Every Action
Incorrect:
```php
public function update(Request $request, Post $post)
public function update(UpdatePostRequest $request, Post $post)
{
$post->update($request->validated());
}
@ -90,7 +90,7 @@ ## Escape Output to Prevent XSS
## CSRF Protection
Include `@csrf` in all POST/PUT/DELETE Blade forms. Not needed in Inertia.
Include `@csrf` in all POST/PUT/DELETE Blade forms. In Inertia apps, the `@csrf` directive is automatically applied.
Incorrect:
```blade
@ -121,7 +121,7 @@ ## Rate Limit Auth and API Routes
## Validate File Uploads
Validate MIME type, extension, and size. Never trust client-provided filenames.
Validate extension, MIME type, and size. The `mimes` rule checks extensions; use `mimetypes` for actual MIME type validation. Never trust client-provided filenames.
```php
public function rules(): array

View file

@ -2,7 +2,7 @@ # Testing Best Practices
## Use `LazilyRefreshDatabase` Over `RefreshDatabase`
`RefreshDatabase` runs all migrations every test run even when the schema hasn't changed. `LazilyRefreshDatabase` only migrates when needed, significantly speeding up large suites.
`RefreshDatabase` migrates once per process and wraps each test in a rolled-back transaction. `LazilyRefreshDatabase` skips even that first migration if the schema is already up to date.
## Use Model Assertions Over Raw Database Assertions

View file

@ -92,4 +92,5 @@ ## Common Pitfalls
- Using HTTPS locally with Node-based MCP clients
- Not using `search-docs` for the latest MCP documentation
- Not registering MCP server routes in `routes/ai.php`
- Do not register `ai.php` in `bootstrap.php`; it is registered automatically.
- Do not register `ai.php` in `bootstrap.php`; it is registered automatically.
- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` config

View file

@ -1,6 +1,6 @@
---
name: pest-testing
description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
license: MIT
metadata:
author: laravel
@ -26,6 +26,8 @@ ### Test Organization
### Basic Test Structure
Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.
<!-- Basic Pest Test Example -->
```php
it('is true', function () {

View file

@ -12,6 +12,7 @@ ## Foundational Context
- php - 8.4
- inertiajs/inertia-laravel (INERTIA_LARAVEL) - v3
- laravel/ai (AI) - v0
- laravel/boost (BOOST) - v2
- laravel/cashier (CASHIER) - v16
- laravel/framework (LARAVEL) - v13
- laravel/horizon (HORIZON) - v5
@ -22,7 +23,6 @@ ## Foundational Context
- laravel/reverb (REVERB) - v1
- laravel/socialite (SOCIALITE) - v5
- laravel/wayfinder (WAYFINDER) - v0
- laravel/boost (BOOST) - v2
- laravel/pail (PAIL) - v1
- laravel/pint (PINT) - v1
- laravel/sail (SAIL) - v1
@ -42,18 +42,18 @@ ## Skills Activation
This project has domain-specific skills available. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
- `ai-sdk-development` — TRIGGER when working with ai-sdk which is Laravel official first-party AI SDK. Activate when building, editing AI agents, chatbots, text generation, image generation, audio/TTS, transcription/STT, embeddings, RAG, vector stores, reranking, structured output, streaming, conversation memory, tools, queueing, broadcasting, and provider failover across OpenAI, Anthropic, Gemini, Azure, Groq, xAI, DeepSeek, Mistral, Ollama, ElevenLabs, Cohere, Jina, and VoyageAI. Invoke when the user references ai-sdk, the `Laravel\Ai\` namespace, or this project's AI features — not for Prism PHP or other AI packages used directly.
- `cashier-stripe-development` — Handles Laravel Cashier Stripe integration including subscriptions, webhooks, Stripe Checkout, invoices, charges, refunds, trials, coupons, metered billing, and payment failure handling. Triggered when a user mentions Cashier, Billable, IncompletePayment, stripe_id, newSubscription, Stripe subscriptions, or billing. Also applies when setting up webhooks, handling SCA/3DS payment failures, testing with Stripe test cards, or troubleshooting incomplete subscriptions, CSRF webhook errors, or migration publish issues.
- `laravel-best-practices` — Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns.
- `configuring-horizon` — Use this skill whenever the user mentions Horizon by name in a Laravel context. Covers the full Horizon lifecycle: installing Horizon (horizon:install, Sail setup), configuring config/horizon.php (supervisor blocks, queue assignments, balancing strategies, minProcesses/maxProcesses), fixing the dashboard (authorization via Gate::define viewHorizon, blank metrics, horizon:snapshot scheduling), and troubleshooting production issues (worker crashes, timeout chain ordering, LongWaitDetected notifications, waits config). Also covers job tagging and silencing. Do not use for generic Laravel queues without Horizon, SQS or database drivers, standalone Redis setup, Linux supervisord, Telescope, or job batching.
- `mcp-development` — Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-\* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP.
- `mcp-development` — Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP.
- `configure-nightwatch` — Configures Laravel Nightwatch data collection, sampling rates, filtering rules, and redaction policies. Use when setting up Nightwatch, managing data volume, protecting sensitive data (PII), or optimizing event collection for production workloads.
- `pennant-development` — Use when working with Laravel Pennant the official Laravel feature flag package. Trigger whenever the query mentions Pennant by name or involves feature flags or feature toggles in a Laravel project. Tasks include defining feature flags checking whether features are active creating class based features in `app/Features` using Blade `@feature` directives scoping flags to users or teams building custom Pennant storage drivers protecting routes with feature flags testing feature flags with Pest or PHPUnit and implementing A B testing or gradual rollouts with feature flags. Do not trigger for generic Laravel configuration authorization policies authentication or non Pennant feature management systems.
- `socialite-development` — Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication.
- `wayfinder-development` — Use this skill for Laravel Wayfinder which auto-generates typed functions for Laravel controllers and routes. ALWAYS use this skill when frontend code needs to call backend routes or controller actions. Trigger when: connecting any React/Vue/Svelte/Inertia frontend to Laravel controllers, routes, building end-to-end features with both frontend and backend, wiring up forms or links to backend endpoints, fixing route-related TypeScript errors, importing from @/actions or @/routes, or running wayfinder:generate. Use Wayfinder route functions instead of hardcoded URLs. Covers: wayfinder() vite plugin, .url()/.get()/.post()/.form(), query params, route model binding, tree-shaking. Do not use for backend-only task
- `pest-testing` — Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code.
- `pest-testing` — Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code.
- `inertia-vue-development` — Develops Inertia.js v3 Vue client-side applications. Activates when creating Vue pages, forms, or navigation; using <Link>, <Form>, useForm, useHttp, setLayoutProps, or router; working with deferred props, prefetching, optimistic updates, instant visits, or polling; or when user mentions Vue with Inertia, Vue pages, Vue forms, or Vue navigation.
- `tailwindcss-development` — Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS.
- `ai-sdk-development` — Builds AI agents, generates text and chat responses, produces images, synthesizes audio, transcribes speech, generates vector embeddings, reranks documents, and manages files and vector stores using the Laravel AI SDK (laravel/ai). Supports structured output, streaming, tools, conversation memory, middleware, queueing, broadcasting, and provider failover. Use when building, editing, updating, debugging, or testing any AI functionality, including agents, LLMs, chatbots, text generation, image generation, audio, transcription, embeddings, RAG, similarity search, vector stores, prompting, structured output, or any AI provider (OpenAI, Anthropic, Gemini, Cohere, Groq, xAI, ElevenLabs, Jina, OpenRouter).
- `medialibrary-development` — Build and work with spatie/laravel-medialibrary features including associating files with Eloquent models, defining media collections and conversions, generating responsive images, and retrieving media URLs and paths.
## Conventions
@ -119,13 +119,12 @@ ## Tinker
- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code.
- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'`
- Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'`
- Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'`
=== php rules ===
# PHP
- Always declare `declare(strict_types=1);` at the top of every `.php` file.
- Always use curly braces for control structures, even for single-line bodies.
- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private.
- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool`
@ -200,6 +199,10 @@ ## Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
## Deployment
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
=== wayfinder/core rules ===
# Laravel Wayfinder
@ -219,7 +222,6 @@ ## Pest
- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`.
- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`.
- When running locally, always pass `--parallel` to speed up the suite (e.g. `php artisan test --parallel --compact`). Combine with `--filter` or specific paths when iterating on a small set of tests.
- Do NOT delete tests without approval.
=== inertia-vue/core rules ===
@ -227,23 +229,8 @@ ## Pest
# Inertia + Vue
Vue components must have a single root element.
- IMPORTANT: Activate `inertia-vue-development` when working with Inertia Vue client-side patterns.
=== laravel/ai rules ===
## Laravel AI SDK
- This application uses the Laravel AI SDK (`laravel/ai`) for all AI functionality.
- Activate the `developing-with-ai-sdk` skill when building, editing, updating, debugging, or testing AI agents, text generation, chat, streaming, structured output, tools, image generation, audio, transcription, embeddings, reranking, vector stores, files, conversation memory, or any AI provider integration (OpenAI, Anthropic, Gemini, Cohere, Groq, xAI, ElevenLabs, Jina, OpenRouter).
=== spatie/laravel-medialibrary rules ===
## Media Library
- `spatie/laravel-medialibrary` associates files with Eloquent models, with support for collections, conversions, and responsive images.
- Always activate the `medialibrary-development` skill when working with media uploads, conversions, collections, responsive images, or any code that uses the `HasMedia` interface or `InteractsWithMedia` trait.
</laravel-boost-guidelines>
# Project-Specific Rules

View file

@ -187,6 +187,7 @@ public function edit(Request $request, Post $post): Response|RedirectResponse
'pinterestBoards' => $pinterestBoards,
'labels' => $labels,
'hashtags' => $hashtags,
'authUserId' => $request->user()->id,
]);
}

View file

@ -5,21 +5,19 @@
"guidelines": true,
"mcp": true,
"nightwatch_mcp": true,
"packages": [
"laravel/ai"
],
"sail": false,
"skills": [
"ai-sdk-development",
"cashier-stripe-development",
"laravel-best-practices",
"configuring-horizon",
"mcp-development",
"configure-nightwatch",
"pennant-development",
"socialite-development",
"wayfinder-development",
"pest-testing",
"inertia-vue-development",
"tailwindcss-development",
"ai-sdk-development"
"tailwindcss-development"
]
}

892
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,705 @@
<script setup lang="ts">
import {
IconEdit,
IconMoodSmile,
IconSend,
IconTrash,
IconCornerDownRight,
IconLoader2,
IconX,
} from '@tabler/icons-vue';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import date from '@/date';
import {
index as fetchComments,
store as storeComment,
update as updateComment,
destroy as destroyComment,
react as reactComment,
} from '@/routes/app/posts/comments';
interface User {
id: string;
name: string;
avatar_url?: string | null;
profile_photo_url?: string | null;
}
interface Reaction {
user_id: string;
emoji: string;
}
interface Comment {
id: string;
body: string;
user_id: string;
parent_id: string | null;
reactions: Reaction[];
created_at: string;
updated_at: string;
user: User;
replies?: Comment[];
}
interface PaginatedResponse {
data: Comment[];
current_page: number;
last_page: number;
next_page_url: string | null;
}
const props = defineProps<{
postId: string;
currentUserId: string;
}>();
const EMOJIS = ['👍', '❤️', '😂', '🎉', '🔥', '👏', '😍', '🤔', '👀', '💯'];
const csrfToken = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content ?? '';
const comments = ref<Comment[]>([]);
const currentPage = ref(1);
const lastPage = ref(1);
const loading = ref(false);
const sending = ref(false);
const newBody = ref('');
const replyingTo = ref<Comment | null>(null);
const editingComment = ref<Comment | null>(null);
const editBody = ref('');
const hoveredCommentId = ref<string | null>(null);
const emojiPickerCommentId = ref<string | null>(null);
const scrollContainer = ref<HTMLDivElement | null>(null);
const textareaRef = ref<InstanceType<typeof Textarea> | null>(null);
const hasOlderComments = computed(() => currentPage.value < lastPage.value);
const getInitials = (name: string): string => {
return name
.split(' ')
.map((n) => n[0])
.join('')
.toUpperCase()
.slice(0, 2);
};
const getAvatarUrl = (user: User): string | null => {
return user.avatar_url || user.profile_photo_url || null;
};
const groupedReactions = (reactions: Reaction[]): { emoji: string; count: number; hasReacted: boolean }[] => {
if (!reactions || reactions.length === 0) return [];
const map = new Map<string, { count: number; hasReacted: boolean }>();
for (const r of reactions) {
const existing = map.get(r.emoji) || { count: 0, hasReacted: false };
existing.count++;
if (r.user_id === props.currentUserId) existing.hasReacted = true;
map.set(r.emoji, existing);
}
return Array.from(map.entries()).map(([emoji, data]) => ({ emoji, ...data }));
};
const loadComments = async (page = 1) => {
loading.value = true;
try {
const url = fetchComments.url(props.postId, { query: { page } });
const response = await fetch(url, {
headers: {
Accept: 'application/json',
'X-CSRF-TOKEN': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
},
});
if (!response.ok) return;
const data: PaginatedResponse = await response.json();
currentPage.value = data.current_page;
lastPage.value = data.last_page;
if (page === 1) {
// Reverse so newest is at bottom
comments.value = [...data.data].reverse();
await nextTick();
scrollToBottom();
} else {
// Prepend older comments at top (also reversed)
const older = [...data.data].reverse();
comments.value = [...older, ...comments.value];
}
} finally {
loading.value = false;
}
};
const loadOlderComments = () => {
if (hasOlderComments.value && !loading.value) {
loadComments(currentPage.value + 1);
}
};
const scrollToBottom = () => {
if (scrollContainer.value) {
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
}
};
const sendComment = async () => {
const body = newBody.value.trim();
if (!body || sending.value) return;
sending.value = true;
try {
const payload: Record<string, string> = { body };
if (replyingTo.value) {
payload.parent_id = replyingTo.value.id;
}
const response = await fetch(storeComment.url(props.postId), {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify(payload),
});
if (!response.ok) return;
const created: Comment = await response.json();
if (created.parent_id) {
// Add reply to parent
const parent = comments.value.find((c) => c.id === created.parent_id);
if (parent) {
if (!parent.replies) parent.replies = [];
parent.replies.push(created);
}
} else {
// Add to bottom (newest)
created.replies = [];
comments.value.push(created);
}
newBody.value = '';
replyingTo.value = null;
await nextTick();
scrollToBottom();
} finally {
sending.value = false;
}
};
const startReply = (comment: Comment) => {
replyingTo.value = comment;
editingComment.value = null;
nextTick(() => {
const el = textareaRef.value?.$el as HTMLTextAreaElement | undefined;
el?.focus();
});
};
const cancelReply = () => {
replyingTo.value = null;
};
const startEdit = (comment: Comment) => {
editingComment.value = comment;
editBody.value = comment.body;
replyingTo.value = null;
};
const cancelEdit = () => {
editingComment.value = null;
editBody.value = '';
};
const saveEdit = async () => {
if (!editingComment.value || !editBody.value.trim()) return;
const comment = editingComment.value;
try {
const response = await fetch(
updateComment.url({ post: props.postId, comment: comment.id }),
{
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({ body: editBody.value.trim() }),
},
);
if (!response.ok) return;
const updated: Comment = await response.json();
// Update in top-level or in replies
const topIndex = comments.value.findIndex((c) => c.id === comment.id);
if (topIndex !== -1) {
comments.value[topIndex].body = updated.body;
comments.value[topIndex].updated_at = updated.updated_at;
} else {
for (const parent of comments.value) {
const replyIndex = parent.replies?.findIndex((r) => r.id === comment.id) ?? -1;
if (replyIndex !== -1 && parent.replies) {
parent.replies[replyIndex].body = updated.body;
parent.replies[replyIndex].updated_at = updated.updated_at;
break;
}
}
}
cancelEdit();
} catch {
// ignore
}
};
const deleteComment = async (comment: Comment) => {
try {
const response = await fetch(
destroyComment.url({ post: props.postId, comment: comment.id }),
{
method: 'DELETE',
headers: {
Accept: 'application/json',
'X-CSRF-TOKEN': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
},
},
);
if (!response.ok) return;
// Remove from top-level
const topIndex = comments.value.findIndex((c) => c.id === comment.id);
if (topIndex !== -1) {
comments.value.splice(topIndex, 1);
} else {
// Remove from replies
for (const parent of comments.value) {
const replyIndex = parent.replies?.findIndex((r) => r.id === comment.id) ?? -1;
if (replyIndex !== -1 && parent.replies) {
parent.replies.splice(replyIndex, 1);
break;
}
}
}
} catch {
// ignore
}
};
const toggleReaction = async (comment: Comment, emoji: string) => {
emojiPickerCommentId.value = null;
try {
const response = await fetch(
reactComment.url({ post: props.postId, comment: comment.id }),
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({ emoji }),
},
);
if (!response.ok) return;
const updated: Comment = await response.json();
// Update reactions in the right place
const topIndex = comments.value.findIndex((c) => c.id === comment.id);
if (topIndex !== -1) {
comments.value[topIndex].reactions = updated.reactions;
} else {
for (const parent of comments.value) {
const replyIndex = parent.replies?.findIndex((r) => r.id === comment.id) ?? -1;
if (replyIndex !== -1 && parent.replies) {
parent.replies[replyIndex].reactions = updated.reactions;
break;
}
}
}
} catch {
// ignore
}
};
const toggleEmojiPicker = (commentId: string) => {
emojiPickerCommentId.value = emojiPickerCommentId.value === commentId ? null : commentId;
};
const handleKeydown = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
event.preventDefault();
sendComment();
}
};
const handleEditKeydown = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
event.preventDefault();
saveEdit();
}
if (event.key === 'Escape') {
cancelEdit();
}
};
const addCommentFromBroadcast = (comment: Comment) => {
// Avoid duplicates
if (comment.user_id === props.currentUserId) return;
if (comment.parent_id) {
const parent = comments.value.find((c) => c.id === comment.parent_id);
if (parent) {
const exists = parent.replies?.some((r) => r.id === comment.id);
if (!exists) {
if (!parent.replies) parent.replies = [];
parent.replies.push(comment);
}
}
} else {
const exists = comments.value.some((c) => c.id === comment.id);
if (!exists) {
comment.replies = comment.replies || [];
comments.value.push(comment);
nextTick(() => scrollToBottom());
}
}
};
defineExpose({ addCommentFromBroadcast });
onMounted(() => {
loadComments(1);
});
watch(() => props.postId, () => {
comments.value = [];
currentPage.value = 1;
loadComments(1);
});
</script>
<template>
<div class="flex flex-col items-center justify-center py-12 text-center">
<p class="text-sm text-muted-foreground">{{ $t('posts.edit.tabs.comments_empty') }}</p>
<div class="flex h-full flex-col">
<!-- Comment list (inverted scroll: newest at bottom) -->
<div ref="scrollContainer" class="flex-1 overflow-y-auto">
<!-- Load older button -->
<div v-if="hasOlderComments" class="flex justify-center py-2">
<Button variant="ghost" size="sm" :disabled="loading" @click="loadOlderComments">
<IconLoader2 v-if="loading" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
{{ $t('comments.load_more') }}
</Button>
</div>
<!-- Empty state -->
<div v-if="!loading && comments.length === 0" class="flex flex-col items-center justify-center py-12 text-center">
<p class="text-sm text-muted-foreground">{{ $t('comments.empty') }}</p>
</div>
<!-- Comments -->
<div class="space-y-1 p-2">
<template v-for="comment in comments" :key="comment.id">
<!-- Top-level comment -->
<div
class="group relative rounded-lg p-2 hover:bg-muted/50"
@mouseenter="hoveredCommentId = comment.id"
@mouseleave="hoveredCommentId = null"
>
<!-- Editing mode -->
<div v-if="editingComment?.id === comment.id" class="space-y-2">
<Textarea
v-model="editBody"
class="min-h-[60px] resize-none text-sm"
@keydown="handleEditKeydown"
/>
<div class="flex items-center gap-1.5">
<Button size="sm" variant="default" @click="saveEdit">{{ $t('comments.save') }}</Button>
<Button size="sm" variant="ghost" @click="cancelEdit">{{ $t('comments.cancel') }}</Button>
</div>
</div>
<!-- Display mode -->
<template v-else>
<div class="flex items-start gap-2">
<Avatar class="h-6 w-6 shrink-0">
<AvatarImage v-if="getAvatarUrl(comment.user)" :src="getAvatarUrl(comment.user)!" />
<AvatarFallback class="text-[10px]">{{ getInitials(comment.user.name) }}</AvatarFallback>
</Avatar>
<div class="min-w-0 flex-1">
<div class="flex items-baseline gap-1.5">
<span class="text-xs font-medium">{{ comment.user.name }}</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<span class="text-[10px] text-muted-foreground">{{ date.diffForHumans(comment.created_at) }}</span>
</TooltipTrigger>
<TooltipContent side="top">
<span class="text-xs">{{ date.formatDateTime(comment.created_at) }}</span>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<span v-if="comment.updated_at !== comment.created_at" class="text-[10px] text-muted-foreground italic">({{ $t('comments.edited') }})</span>
</div>
<p class="mt-0.5 whitespace-pre-wrap text-sm">{{ comment.body }}</p>
<!-- Reactions -->
<div v-if="groupedReactions(comment.reactions).length > 0" class="mt-1 flex flex-wrap gap-1">
<button
v-for="r in groupedReactions(comment.reactions)"
:key="r.emoji"
class="inline-flex items-center gap-0.5 rounded-full border px-1.5 py-0.5 text-xs transition-colors"
:class="r.hasReacted ? 'border-primary/40 bg-primary/10' : 'border-border hover:border-primary/30'"
@click="toggleReaction(comment, r.emoji)"
>
<span>{{ r.emoji }}</span>
<span class="text-[10px] text-muted-foreground">{{ r.count }}</span>
</button>
</div>
</div>
<!-- Hover actions -->
<div
v-if="hoveredCommentId === comment.id && editingComment?.id !== comment.id"
class="absolute -top-2 right-1 flex items-center gap-0.5 rounded-md border bg-background px-1 py-0.5 shadow-sm"
>
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<button class="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground" @click="toggleEmojiPicker(comment.id)">
<IconMoodSmile class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top"><span class="text-xs">React</span></TooltipContent>
</Tooltip>
</TooltipProvider>
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<button class="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground" @click="startReply(comment)">
<IconCornerDownRight class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top"><span class="text-xs">{{ $t('comments.reply') }}</span></TooltipContent>
</Tooltip>
</TooltipProvider>
<template v-if="comment.user_id === currentUserId">
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<button class="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground" @click="startEdit(comment)">
<IconEdit class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top"><span class="text-xs">{{ $t('comments.edit') }}</span></TooltipContent>
</Tooltip>
</TooltipProvider>
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<button class="rounded p-1 text-muted-foreground hover:bg-muted hover:text-destructive" @click="deleteComment(comment)">
<IconTrash class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top"><span class="text-xs">{{ $t('comments.delete') }}</span></TooltipContent>
</Tooltip>
</TooltipProvider>
</template>
</div>
<!-- Emoji picker dropdown -->
<div
v-if="emojiPickerCommentId === comment.id"
class="absolute -top-10 right-1 z-10 flex items-center gap-0.5 rounded-lg border bg-background p-1.5 shadow-md"
>
<button
v-for="emoji in EMOJIS"
:key="emoji"
class="rounded p-0.5 text-sm transition-transform hover:scale-125 hover:bg-muted"
@click="toggleReaction(comment, emoji)"
>
{{ emoji }}
</button>
</div>
</div>
</template>
</div>
<!-- Replies (1 level) -->
<template v-if="comment.replies && comment.replies.length > 0">
<div
v-for="reply in comment.replies"
:key="reply.id"
class="group relative ml-6 rounded-lg border-l-2 border-border p-2 pl-3 hover:bg-muted/50"
@mouseenter="hoveredCommentId = reply.id"
@mouseleave="hoveredCommentId = null"
>
<!-- Editing reply -->
<div v-if="editingComment?.id === reply.id" class="space-y-2">
<Textarea
v-model="editBody"
class="min-h-[60px] resize-none text-sm"
@keydown="handleEditKeydown"
/>
<div class="flex items-center gap-1.5">
<Button size="sm" variant="default" @click="saveEdit">{{ $t('comments.save') }}</Button>
<Button size="sm" variant="ghost" @click="cancelEdit">{{ $t('comments.cancel') }}</Button>
</div>
</div>
<!-- Display reply -->
<template v-else>
<div class="flex items-start gap-2">
<Avatar class="h-5 w-5 shrink-0">
<AvatarImage v-if="getAvatarUrl(reply.user)" :src="getAvatarUrl(reply.user)!" />
<AvatarFallback class="text-[9px]">{{ getInitials(reply.user.name) }}</AvatarFallback>
</Avatar>
<div class="min-w-0 flex-1">
<div class="flex items-baseline gap-1.5">
<span class="text-xs font-medium">{{ reply.user.name }}</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<span class="text-[10px] text-muted-foreground">{{ date.diffForHumans(reply.created_at) }}</span>
</TooltipTrigger>
<TooltipContent side="top">
<span class="text-xs">{{ date.formatDateTime(reply.created_at) }}</span>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<span v-if="reply.updated_at !== reply.created_at" class="text-[10px] text-muted-foreground italic">({{ $t('comments.edited') }})</span>
</div>
<p class="mt-0.5 whitespace-pre-wrap text-sm">{{ reply.body }}</p>
<!-- Reply reactions -->
<div v-if="groupedReactions(reply.reactions).length > 0" class="mt-1 flex flex-wrap gap-1">
<button
v-for="r in groupedReactions(reply.reactions)"
:key="r.emoji"
class="inline-flex items-center gap-0.5 rounded-full border px-1.5 py-0.5 text-xs transition-colors"
:class="r.hasReacted ? 'border-primary/40 bg-primary/10' : 'border-border hover:border-primary/30'"
@click="toggleReaction(reply, r.emoji)"
>
<span>{{ r.emoji }}</span>
<span class="text-[10px] text-muted-foreground">{{ r.count }}</span>
</button>
</div>
</div>
<!-- Reply hover actions -->
<div
v-if="hoveredCommentId === reply.id && editingComment?.id !== reply.id"
class="absolute -top-2 right-1 flex items-center gap-0.5 rounded-md border bg-background px-1 py-0.5 shadow-sm"
>
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<button class="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground" @click="toggleEmojiPicker(reply.id)">
<IconMoodSmile class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top"><span class="text-xs">React</span></TooltipContent>
</Tooltip>
</TooltipProvider>
<template v-if="reply.user_id === currentUserId">
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<button class="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground" @click="startEdit(reply)">
<IconEdit class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top"><span class="text-xs">{{ $t('comments.edit') }}</span></TooltipContent>
</Tooltip>
</TooltipProvider>
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<button class="rounded p-1 text-muted-foreground hover:bg-muted hover:text-destructive" @click="deleteComment(reply)">
<IconTrash class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent side="top"><span class="text-xs">{{ $t('comments.delete') }}</span></TooltipContent>
</Tooltip>
</TooltipProvider>
</template>
</div>
<!-- Reply emoji picker -->
<div
v-if="emojiPickerCommentId === reply.id"
class="absolute -top-10 right-1 z-10 flex items-center gap-0.5 rounded-lg border bg-background p-1.5 shadow-md"
>
<button
v-for="emoji in EMOJIS"
:key="emoji"
class="rounded p-0.5 text-sm transition-transform hover:scale-125 hover:bg-muted"
@click="toggleReaction(reply, emoji)"
>
{{ emoji }}
</button>
</div>
</div>
</template>
</div>
</template>
</template>
</div>
<!-- Loading spinner for initial load -->
<div v-if="loading && comments.length === 0" class="flex items-center justify-center py-8">
<IconLoader2 class="h-5 w-5 animate-spin text-muted-foreground" />
</div>
</div>
<!-- Input area -->
<div class="shrink-0 border-t p-2">
<!-- Replying to indicator -->
<div v-if="replyingTo" class="mb-1.5 flex items-center gap-1.5 text-xs text-muted-foreground">
<IconCornerDownRight class="h-3 w-3" />
<span>{{ $t('comments.replying_to', { name: replyingTo.user.name }) }}</span>
<button class="ml-auto rounded p-0.5 hover:bg-muted" @click="cancelReply">
<IconX class="h-3 w-3" />
</button>
</div>
<div class="flex items-end gap-1.5">
<Textarea
ref="textareaRef"
v-model="newBody"
:placeholder="replyingTo ? $t('comments.reply_placeholder') : $t('comments.placeholder')"
class="min-h-[36px] max-h-[120px] flex-1 resize-none text-sm"
rows="1"
@keydown="handleKeydown"
/>
<Button
size="icon"
variant="ghost"
class="h-9 w-9 shrink-0"
:disabled="!newBody.trim() || sending"
@click="sendComment"
>
<IconLoader2 v-if="sending" class="h-4 w-4 animate-spin" />
<IconSend v-else class="h-4 w-4" />
</Button>
</div>
</div>
</div>
</template>

View file

@ -90,6 +90,7 @@ const props = defineProps<{
pinterestBoards: any[];
labels: { id: string; name: string; color: string }[];
hashtags: { id: string; name: string; hashtags: string }[];
authUserId: string;
}>();
const post = computed(() => props.post);
@ -120,6 +121,7 @@ const isSaving = ref(false);
const showSaved = ref(false);
const deleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
const hashtagsModal = ref<InstanceType<typeof HashtagsModal> | null>(null);
const commentsTabRef = ref<InstanceType<typeof CommentsTab> | null>(null);
const timezoneAbbr = computed(() => dayjs().tz(props.workspace.timezone).format('z'));
const fileInput = ref<HTMLInputElement | null>(null);
@ -306,6 +308,11 @@ useEcho(`post.${post.value.id}`, '.PostPlatformStatusUpdated', () => {
router.reload({ only: ['post'], preserveScroll: true });
});
// Echo: listen for real-time comments
useEcho(`post.${post.value.id}`, '.PostCommentCreated', (e: any) => {
commentsTabRef.value?.addCommentFromBroadcast(e.comment);
});
const formatFileSize = (bytes: number): string => {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
@ -433,8 +440,8 @@ const formatFileSize = (bytes: number): string => {
<ScheduleTab :post-platforms="post.post_platforms" :selected-platform-ids="selectedPlatformIds" @toggle-platform="togglePlatform" />
</TabsContent>
<TabsContent value="comments" class="flex-1 overflow-y-auto p-4">
<CommentsTab />
<TabsContent value="comments" class="flex-1 overflow-hidden">
<CommentsTab ref="commentsTabRef" :post-id="post.id" :current-user-id="authUserId" />
</TabsContent>
<TabsContent value="assistant" class="flex-1 overflow-y-auto p-4">