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.

35.3 KB
Raw Blame
<?php

declare(strict_types=1);

use App\Actions\Post\CreatePosts;
use App\Enums\Post\PublishStatus;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\User\Locale;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
use App\Support\PostingSchedule;
use Illuminate\Support\Str;

/**
 * @return array{0: User, 1: Workspace, 2: SocialAccount}
 */
function publishPageSetup(): array
{
    $user = User::factory()->create(['timezone' => 'UTC']);
    $workspace = Workspace::factory()->create([
        'user_id' => $user->id,
        'account_id' => $user->account_id,
    ]);
    $workspace->members()->attach($user->id, membershipPivot('admin'));
    $user->update(['current_workspace_id' => $workspace->id]);
    subscribeAccount($user->account);

    $time = now()->utc()->addHours(6)->format('H:00');
    $schedule = PostingSchedule::empty();

    foreach (range(0, 6) as $day) {
        $schedule = $schedule->withTime($day, $time);
    }

    $channel = SocialAccount::factory()->linkedin()->create([
        'workspace_id' => $workspace->id,
        'timezone' => 'UTC',
        'posting_schedule' => $schedule,
        'posting_goal' => 3,
    ]);

    return [$user, $workspace, $channel];
}

/**
 * @param  array<string, mixed>  $overrides
 */
function publishPagePost(User $user, Workspace $workspace, SocialAccount $channel, array $overrides = []): Post
{
    return CreatePosts::execute($workspace, $user, [
        'status' => 'scheduled',
        'queue' => 'next',
        'content' => 'Publish page post',
        'media' => [],
        'label_ids' => [],
        'destinations' => [[
            'social_account_id' => $channel->id,
            'content_type' => ContentType::LinkedInPost->value,
            'meta' => [],
        ]],
        ...$overrides,
    ])->first();
}

test('the weekly goal shows its progress, fills the pie and opens a popover with sent, scheduled and to do', function () {
    [$user, $workspace, $channel] = publishPageSetup();
    $sent = publishPagePost($user, $workspace, $channel);
    $sent->forceFill(['status' => PostStatus::Published, 'publish_status' => PublishStatus::Published, 'published_at' => now()])->save();
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', $channel));
    waitFor($page, '@publish-goal-progress');

    expect($page->script('new URL(document.querySelector(\'[data-testid="schedule-view-calendar"]\').href).search'))->toBe('')
        ->and($page->script('new URL(document.querySelector(\'[data-testid="schedule-view-calendar"]\').href).pathname'))->toBe(route('app.channels.calendar', ['account' => $channel->id, 'view' => 'week'], false));
    $page->assertSeeIn('@publish-goal-progress', trans('posts.publish.goal', ['sent' => 1, 'goal' => 3]))
        ->assertAttribute('@publish-goal-pie', 'data-percent', '33');
    expect($page->script("document.querySelectorAll('[data-testid=\"publish-goal-pie\"] circle').length"))->toBe(2);

    $page->click('@publish-goal-progress');
    waitFor($page, '@publish-goal-popover');

    $page->assertSeeIn('@publish-goal-popover', trans_choice('posts.publish.goal_popover.per_week', 3, ['count' => 3]))
        ->assertVisible('@publish-goal-edit')
        ->assertNoJavaScriptErrors();

    expect($page->script("document.querySelector('[data-testid=\"publish-goal-summary\"]').textContent.replace(/\\s+/g, ' ').trim()"))
        ->toBe('1 '.__('posts.publish.goal_popover.sent').'·0 '.__('posts.publish.goal_popover.scheduled').'·2 '.__('posts.publish.goal_popover.to_do'));
});

test('a draft is added to the queue from the drafts tab, which stays open', function () {
    [$user, $workspace, $channel] = publishPageSetup();
    $draft = publishPagePost($user, $workspace, $channel, ['status' => 'draft', 'queue' => null]);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', $channel));
    waitFor($page, '@publish-tab-drafts');
    $page->click('@publish-tab-drafts');
    waitFor($page, "@post-add-to-queue-{$draft->id}");

    $page->assertVisible("@post-card-{$draft->id}")
        ->click("@post-add-to-queue-{$draft->id}");
    waitForDatabase($page, fn (): bool => $draft->refresh()->status === PostStatus::Scheduled);

    expect($draft->refresh()->status)->toBe(PostStatus::Scheduled)
        ->and($draft->schedule_mode)->toBe(ScheduleMode::Queue);

    waitForGone($page, "@post-card-{$draft->id}");
    $page->assertPathIs(route('app.channels.publish', $channel, false))
        ->assertScript("new URLSearchParams(location.search).get('tab')", 'drafts')
        ->assertNoJavaScriptErrors();
});

test('add to queue explains how to set up the queue when the channel has no posting times', function () {
    [$user, $workspace] = publishPageSetup();
    $channel = SocialAccount::factory()->linkedin()->create([
        'workspace_id' => $workspace->id,
        'timezone' => 'UTC',
        'posting_schedule' => null,
    ]);
    $draft = publishPagePost($user, $workspace, $channel, ['status' => 'draft', 'queue' => null]);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'drafts']));
    waitFor($page, "@post-add-to-queue-{$draft->id}");

    $page->assertEnabled("@post-add-to-queue-{$draft->id}")
        ->click("@post-add-to-queue-{$draft->id}");
    waitFor($page, "@post-queue-setup-{$draft->id}");

    $page->assertVisible("@post-queue-setup-illustration-{$draft->id}")
        ->assertSeeIn("@post-queue-setup-{$draft->id}", __('posts.publish.actions.queue_setup.title'))
        ->assertSeeIn("@post-queue-setup-{$draft->id}", __('posts.publish.actions.queue_setup.body'))
        ->assertNoJavaScriptErrors();
    expect($draft->refresh()->status)->toBe(PostStatus::Draft);

    $page->click("@post-queue-setup-action-{$draft->id}");
    waitFor($page, '@channel-settings-page');

    $page->assertPathIs(route('app.channels.settings', $channel, absolute: false))
        ->assertNoJavaScriptErrors();
});

test('a member who cannot manage channels is told to ask an admin for posting times', function () {
    [$owner, $workspace] = publishPageSetup();
    $member = User::factory()->create(['account_id' => $owner->account_id, 'current_workspace_id' => $workspace->id]);
    $workspace->members()->attach($member->id, membershipPivot('member'));
    $channel = SocialAccount::factory()->linkedin()->create([
        'workspace_id' => $workspace->id,
        'timezone' => 'UTC',
        'posting_schedule' => null,
    ]);
    $draft = publishPagePost($owner, $workspace, $channel, ['status' => 'draft', 'queue' => null]);
    $this->actingAs($member);

    $page = visit(route('app.posts.index', ['tab' => 'drafts']));
    waitFor($page, "@post-add-to-queue-{$draft->id}");
    $page->click("@post-add-to-queue-{$draft->id}");
    waitFor($page, "@post-queue-setup-{$draft->id}");

    $page->assertSeeIn("@post-queue-setup-{$draft->id}", __('posts.publish.actions.queue_setup.body_member'))
        ->assertMissing("@post-queue-setup-action-{$draft->id}")
        ->click("@post-queue-setup-not-now-{$draft->id}");

    $page->assertMissing("@post-queue-setup-{$draft->id}")
        ->assertNoJavaScriptErrors();
});

test('add to queue explains where the post goes when the channel has posting times', function () {
    [$user, $workspace, $channel] = publishPageSetup();
    $draft = publishPagePost($user, $workspace, $channel, ['status' => 'draft', 'queue' => null]);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'drafts']));
    waitFor($page, "@post-add-to-queue-{$draft->id}");
    $page->hover("@post-add-to-queue-{$draft->id}");
    waitFor($page, "@post-add-to-queue-tooltip-{$draft->id}");

    $page->assertSeeIn("@post-add-to-queue-tooltip-{$draft->id}", __('posts.publish.actions.add_to_queue_hint'))
        ->assertNoJavaScriptErrors();
});

test('editing a draft from a channel page keeps the channel page and tab', function () {
    [$user, $workspace, $channel] = publishPageSetup();
    $draft = publishPagePost($user, $workspace, $channel, ['status' => 'draft', 'queue' => null]);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'drafts']));
    waitFor($page, "@post-edit-{$draft->id}");
    $page->click("@post-edit-{$draft->id}");
    waitFor($page, '@post-composer-dialog');

    expect($page->script('location.pathname'))->toBe(route('app.channels.publish', $channel, absolute: false))
        ->and($page->script('new URLSearchParams(location.search).get("tab")'))->toBe('drafts')
        ->and($page->script('new URLSearchParams(location.search).get("edit")'))->toBe($draft->id);
    $page->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();
});

test('saving a queued post edited on a channel page returns to that page and tab', function () {
    [$user, $workspace, $channel] = publishPageSetup();
    $queued = publishPagePost($user, $workspace, $channel);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'queue']));
    waitFor($page, "@post-edit-{$queued->id}");
    $page->click("@post-edit-{$queued->id}");
    waitFor($page, '@composer-submit');
    $page->click('@composer-submit');

    waitForCondition($page, "!new URLSearchParams(location.search).has('edit')");
    waitForGone($page, '@post-composer-dialog');
    waitFor($page, "@post-card-{$queued->id}");

    expect($page->script('location.pathname'))->toBe(route('app.channels.publish', $channel, absolute: false))
        ->and($page->script('new URLSearchParams(location.search).get("tab")'))->toBe('queue')
        ->and($page->script('new URLSearchParams(location.search).has("edit")'))->toBeFalse();
    $page->assertVisible("@post-card-{$queued->id}")->assertNoJavaScriptErrors();
});

test('a sent card shows the metrics band in order and links to the publication insights', function () {
    [$user, $workspace] = publishPageSetup();
    $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
    $post = Post::factory()->forAccount($account, ContentType::XPost)->published()->create([
        'user_id' => $user->id,
        'scheduled_at' => now()->subHour(),
        'published_at' => now()->subHour(),
    ]);
    $publication = AnalyticsPublication::factory()->create([
        'workspace_id' => $workspace->id,
        'social_account_id' => $account->id,
        'social_account_key' => $account->id,
        'post_id' => $post->id,
        'platform' => Platform::X,
        'network' => Platform::X->network(),
        'remote_id' => $post->platform_post_id,
    ]);
    $metric = fn (float $value, string $unit = 'count'): array => ['value' => $value, 'unit' => $unit, 'availability' => 'available'];
    AnalyticsPublicationDailySnapshot::factory()->create([
        'publication_id' => $publication->id,
        'metrics' => [
            'reactions' => $metric(40),
            'impressions' => $metric(900),
            'engagement_rate' => $metric(5.5, 'percent'),
            'comments' => $metric(7),
            'shares' => $metric(3),
        ],
    ]);

    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => 'sent']));
    waitFor($page, "@post-metrics-{$post->id}");

    expect($page->script("[...document.querySelectorAll('[data-testid=\"post-metrics-{$post->id}\"] dd')].map((value) => value.textContent.trim())"))
        ->toBe(['40', '7', '5.5%', '900', '3'])
        ->and($page->script("new URL(document.querySelector('[data-testid=\"post-insights-{$post->id}\"]').href).pathname"))
        ->toBe(route('app.channels.insights', $account, absolute: false));

    $page->assertNoJavaScriptErrors();
});

test('the approvals tab groups pending posts by day with unscheduled requests last', function () {
    [$user, $workspace, $channel] = publishPageSetup();
    $timed = Post::factory()->forAccount($channel)->pendingApproval()->create([
        'user_id' => $user->id,
        'scheduled_at' => now()->utc()->addDays(2)->setTime(12, 0),
    ]);
    $queued = Post::factory()->forAccount($channel)->pendingApproval()->create([
        'user_id' => $user->id,
        'scheduled_at' => null,
        'schedule_mode' => ScheduleMode::Queue,
    ]);

    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => 'approvals']));
    waitFor($page, "@post-card-{$queued->id}");

    $timedDay = $timed->scheduled_at->utc()->format('Y-m-d');

    expect($page->script('[...document.querySelectorAll(\'[data-testid^="publish-tab-count-"]\')].map((el) => el.dataset.testid)'))
        ->toBe(['publish-tab-count-queue', 'publish-tab-count-approvals', 'publish-tab-count-drafts', 'publish-tab-count-sent'])
        ->and($page->script('[...document.querySelectorAll(\'[data-testid^="publish-day-"]\')].map((el) => el.dataset.testid)'))
        ->toBe(["publish-day-{$timedDay}", 'publish-day-no-time']);

    $page->assertSeeIn('@publish-tab-count-approvals', '2')
        ->assertVisible("@post-card-{$timed->id}")
        ->assertSeeIn('@publish-day-no-time', 'Unscheduled')
        ->assertNoJavaScriptErrors();
});

test('an empty tab shows its illustration, copy and a new post button that opens the composer', function (string $tab) {
    [$user] = publishPageSetup();
    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => $tab]));
    waitFor($page, '@publish-empty-illustration');

    $page->assertSeeIn('@empty-state', __("posts.publish.empty.{$tab}.title"))
        ->assertSeeIn('@empty-state', __("posts.publish.empty.{$tab}.description"))
        ->assertSeeIn('@publish-empty-connect-more', __('posts.publish.welcome.connect_more'))
        ->assertMissing('@publish-welcome')
        ->click("@publish-empty-new-post-{$tab}");
    waitFor($page, '@post-composer-dialog');

    $page->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();
})->with(['drafts']);

test('a workspace without channels is welcomed with connect and invite actions', function () {
    $user = User::factory()->create(['timezone' => 'UTC']);
    $workspace = Workspace::factory()->create([
        'user_id' => $user->id,
        'account_id' => $user->account_id,
    ]);
    $workspace->members()->attach($user->id, membershipPivot('admin'));
    $user->update(['current_workspace_id' => $workspace->id]);
    subscribeAccount($user->account);
    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => 'drafts']));
    waitFor($page, '@publish-welcome');

    $page->assertSeeIn('@publish-welcome', __('posts.publish.welcome.title'))
        ->assertSeeIn('@publish-welcome-invite', __('posts.publish.welcome.invite'))
        ->assertMissing('@publish-empty-new-post-drafts')
        ->click('@publish-welcome-invite');
    waitFor($page, '@invite-member-dialog');

    $page->assertVisible('@invite-email')
        ->click('@invite-member-cancel');
    waitFor($page, '@publish-welcome-connect');

    $page->click('@publish-welcome-connect');
    waitFor($page, '@connect-channel-dialog');

    $page->assertVisible('@connect-channel-dialog')->assertNoJavaScriptErrors();
});

test('an active label filter shows its count in the primary color', function () {
    [$user, $workspace] = publishPageSetup();
    $label = WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id]);
    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => 'drafts', 'labels' => [$label->id]]));
    waitFor($page, '@posts-label-count');

    $page->assertSeeIn('@posts-label-count', '1')
        ->assertScript(<<<'JS'
            (() => {
                const probe = document.createElement('span');
                probe.className = 'bg-primary';
                document.body.appendChild(probe);
                const primary = getComputedStyle(probe).backgroundColor;
                probe.remove();
                return getComputedStyle(document.querySelector('[data-testid="posts-label-count"]')).backgroundColor === primary;
            })()
        JS, true)
        ->assertNoJavaScriptErrors();
});

test('the tabs row border keeps the page padding instead of touching the panel edges', function () {
    [$user] = publishPageSetup();
    $this->actingAs($user);

    $page = visit(route('app.posts.index'))->resize(1440, 900);
    waitFor($page, '@publish-filters');

    $edges = $page->script(<<<'JS'
        (() => {
            const row = document.querySelector('[data-testid="publish-filters"]').parentElement.getBoundingClientRect();
            const panel = document.querySelector('[data-slot="sidebar-inset"]').getBoundingClientRect();
            return [Math.round(row.left - panel.left), Math.round(panel.right - row.right)];
        })()
    JS);

    expect($edges[0])->toBeGreaterThanOrEqual(32)
        ->and($edges[1])->toBeGreaterThanOrEqual(32);
    $page->assertNoJavaScriptErrors();
});

test('the calendar keeps its filters in one menu until the screen is wide enough for all of them', function () {
    [$user, , $channel] = publishPageSetup();
    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week']))->resize(390, 844);
    waitFor($page, '@calendar-menu');
    waitFor($page, '@posts-channel-filter');

    $measure = <<<'JS'
        (() => {
            const rect = (id) => document.querySelector(`[data-testid="${id}"]`).getBoundingClientRect();
            const middle = (box) => Math.round(box.top + box.height / 2);
            const row = ['posts-channel-filter', 'calendar-menu'].map(rect);
            const channelFilter = document.querySelector('[data-testid="posts-channel-filter"]');
            const visible = (node) => node.getClientRects().length > 0 && getComputedStyle(node).display !== 'none';

            return {
                oneRow: row.every((box) => Math.abs(middle(box) - middle(row[0])) <= 2),
                viewSwitchInHeader: Boolean(document.querySelector('[data-testid="app-header"] [data-testid="schedule-view-trigger"]')?.getClientRects().length),
                noDateButton: visible(document.querySelector('[data-testid="calendar-no-date"]')),
                channelText: [...channelFilter.querySelectorAll('span')].filter((span) => visible(span) && span.textContent.trim() !== '').length,
                tags: Boolean(document.querySelector('[data-testid="posts-label-filter"]')?.getClientRects().length),
                overflow: document.documentElement.scrollWidth > window.innerWidth,
            };
        })()
    JS;

    expect($page->script($measure))->toBe([
        'oneRow' => true,
        'viewSwitchInHeader' => true,
        'noDateButton' => false,
        'channelText' => 0,
        'tags' => false,
        'overflow' => false,
    ]);

    $page->click('@calendar-menu');
    waitFor($page, '@calendar-menu-content');
    waitForState($page, '@calendar-menu-content', 'Math.abs(window.innerHeight - element.getBoundingClientRect().bottom) <= 1');

    $page->assertVisible('@calendar-status-drafts')
        ->assertVisible('@publish-timezone-trigger')
        ->assertVisible('@calendar-toggle-slots')
        ->assertAttribute('@calendar-no-date-menu', 'aria-pressed', 'false')
        ->click('@calendar-no-date-menu');

    waitFor($page, '@calendar-undated-panel');
    waitForGone($page, '@calendar-menu-content');
    $page->assertVisible('@calendar-undated-panel')
        ->assertMissing('@calendar-menu-content')
        ->click('@calendar-menu');
    waitFor($page, '@calendar-no-date-menu');
    $page->assertAttribute('@calendar-no-date-menu', 'aria-pressed', 'true')
        ->click('@calendar-no-date-menu');
    waitForGone($page, '@calendar-undated-panel');
    $page->assertMissing('@calendar-undated-panel');

    $page->resize(900, 900);
    waitForState($page, '@posts-label-filter', 'Boolean(element.getClientRects().length)');
    waitForGone($page, '@calendar-status-filter');

    expect($page->script('Boolean(document.querySelector(\'[data-testid="calendar-status-filter"]\'))'))->toBeFalse()
        ->and($page->script('Boolean(document.querySelector(\'[data-testid="calendar-menu"]\')?.getClientRects().length)'))->toBeTrue()
        ->and($page->script('document.documentElement.scrollWidth > window.innerWidth'))->toBeFalse();

    $page->resize(1600, 900);

    waitForState($page, '@calendar-status-filter', 'true');

    $order = $page->script(<<<'JS'
        (() => ['posts-channel-filter', 'posts-label-filter', 'calendar-status-filter', 'publish-timezone-trigger', 'calendar-no-date', 'calendar-menu']
            .map((id) => document.querySelector(`[data-testid="${id}"]`).getBoundingClientRect().left)
            .every((left, index, lefts) => index === 0 || left > lefts[index - 1]))()
    JS);

    expect($order)->toBeTrue()
        ->and($page->script('Boolean(document.querySelector(\'[data-testid="schedule-view-list"]\').closest("header"))'))->toBeTrue()
        ->and($page->script('document.querySelector(\'[data-testid="calendar-no-date"] span\').getBoundingClientRect().width > 1'))->toBeTrue();

    $page->assertNoJavaScriptErrors();
});

test('the channel page adapts its filters, tabs, calendar link and notes button to the viewport', function () {
    [$user, $workspace, $channel] = publishPageSetup();
    $channel->update(['display_name' => 'A channel with a rather long display name', 'posting_goal' => 5]);
    $post = publishPagePost($user, $workspace, $channel);
    $this->actingAs($user);

    $notes = <<<'JS'
        (() => {
            const row = document.querySelector('[data-testid^="post-card-"]');
            const card = row.querySelector('article').getBoundingClientRect();
            const notes = row.querySelector('[data-testid^="post-notes-trigger-"]').getBoundingClientRect();

            return {
                inside: notes.left >= card.left && notes.right <= card.right && notes.top >= card.top,
                beside: notes.left >= card.right,
            };
        })()
    JS;

    $calendarPath = 'new URL(document.querySelector(\'[data-testid="schedule-view-calendar"]\').href).pathname';

    $page = visit(route('app.channels.publish', $channel))->resize(900, 800);
    waitFor($page, "@post-notes-trigger-{$post->id}");
    expect($page->script($notes))->toBe(['inside' => true, 'beside' => false]);

    $page->resize(1280, 800);
    waitFor($page, "@post-notes-trigger-{$post->id}");
    expect($page->script($notes))->toBe(['inside' => true, 'beside' => false]);

    $page->resize(390, 844);
    waitFor($page, '@publish-tabs-mobile-trigger');
    waitForGone($page, '@posts-label-filter');

    $phone = $page->script(<<<'JS'
        (() => {
            const rect = (id) => document.querySelector(`[data-testid="${id}"]`).getBoundingClientRect();
            const middle = (box) => Math.round(box.top + box.height / 2);
            const row = ['publish-tabs-mobile-trigger', 'publish-menu', 'schedule-view-trigger', 'posts-new-post'].map(rect);

            return {
                oneRow: row.every((box) => Math.abs(middle(box) - middle(row[0])) <= 2),
                belowGoal: row[0].top >= rect('publish-goal-progress').bottom,
                tags: Boolean(document.querySelector('[data-testid="posts-label-filter"]')?.getClientRects().length),
                overflow: document.documentElement.scrollWidth > window.innerWidth,
            };
        })()
    JS);

    expect($phone)->toBe(['oneRow' => true, 'belowGoal' => true, 'tags' => false, 'overflow' => false])
        ->and($page->script('Boolean(document.querySelector(\'[data-testid="publish-timezone-trigger"]\'))'))->toBeFalse();

    $page->click('@schedule-view-trigger');
    waitForOpen($page, '@schedule-view-menu');

    expect($page->script($calendarPath))->toBe(route('app.channels.calendar', ['account' => $channel->id, 'view' => 'days'], false));

    $page->keys('@schedule-view-menu', 'Escape');
    waitForGone($page, '@schedule-view-menu');

    $page->click('@publish-menu');
    waitFor($page, '@publish-menu-content');
    waitForState($page, '@publish-menu-content', 'Math.abs(window.innerHeight - element.getBoundingClientRect().bottom) <= 1');

    $pressed = 'document.querySelector(\'[data-testid="publish-toggle-slots"]\').getAttribute("aria-pressed")';
    $before = $page->script($pressed);
    $page->assertVisible('@publish-timezone-trigger')
        ->click('@publish-toggle-slots');

    expect($page->script($pressed))->toBe($before === 'true' ? 'false' : 'true')
        ->and($page->script('new URL(document.querySelector(\'[data-testid="publish-manage-slots"]\').href).pathname'))
        ->toBe(route('app.channels.settings', $channel, false));

    $page->resize(1280, 800);
    waitForGone($page, '@publish-menu-content');
    waitFor($page, '@publish-timezone-trigger');

    $desktop = $page->script(<<<'JS'
        (() => {
            const left = (id) => document.querySelector(`[data-testid="${id}"]`).getBoundingClientRect().left;
            const inHeader = (id) => Boolean(document.querySelector(`[data-testid="${id}"]`).closest('header'));

            return {
                switchInHeader: inHeader('schedule-view-list'),
                newPostInHeader: inHeader('posts-new-post'),
                order: left('posts-label-filter') < left('publish-timezone-trigger') && left('publish-timezone-trigger') < left('publish-menu'),
            };
        })()
    JS);

    expect($desktop)->toBe(['switchInHeader' => true, 'newPostInHeader' => true, 'order' => true]);

    $page->click('@publish-menu');
    waitFor($page, '@publish-toggle-slots');
    $page->assertVisible('@publish-manage-slots');

    $page->resize(390, 844);
    waitFor($page, '@publish-tabs-mobile-trigger');

    expect($page->script('document.querySelector(\'[data-testid="posts-tabs"]\').getBoundingClientRect().height'))->toBe(0);
    $page->assertSeeIn('@publish-tabs-mobile-trigger', trans('posts.publish.tabs.queue'))
        ->click('@publish-tabs-mobile-trigger');
    waitFor($page, '@publish-tabs-sheet');

    $page->assertPresent('@publish-tab-sheet-queue-check')
        ->assertMissing('@publish-tab-sheet-drafts-check')
        ->click('@publish-tab-sheet-drafts');
    waitForQueryParameter($page, 'tab', 'drafts');

    $page->assertSeeIn('@publish-tabs-mobile-trigger', trans('posts.publish.tabs.drafts'))
        ->assertMissing('@publish-tabs-sheet');

    $page->navigate(route('app.posts.index'));
    waitFor($page, '@schedule-view-trigger');
    $page->click('@schedule-view-trigger');
    waitForOpen($page, '@schedule-view-menu');
    expect($page->script($calendarPath))->toBe(route('app.calendar', ['view' => 'days'], false));

    $page->keys('@schedule-view-menu', 'Escape');
    waitForGone($page, '@schedule-view-menu');
    $page->resize(1280, 800);
    waitForCondition($page, $calendarPath.'.endsWith("/week")');
    expect($page->script($calendarPath))->toBe(route('app.calendar', ['view' => 'week'], false));

    $page->assertNoJavaScriptErrors();
});

test('a draft without a channel shows no add to queue button', function () {
    [$user, $workspace] = publishPageSetup();
    $draft = Post::factory()->create([
        'workspace_id' => $workspace->id,
        'user_id' => $user->id,
        'content' => 'Draft without a channel',
        'status' => PostStatus::Draft,
    ]);
    $draft->forceFill(['social_account_id' => null, 'platform' => null, 'content_type' => null])->save();
    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => 'drafts']));
    waitFor($page, "@post-card-{$draft->id}");

    $page->assertVisible("@post-card-{$draft->id}")
        ->assertMissing("@post-add-to-queue-{$draft->id}")
        ->assertNoJavaScriptErrors();
});

test('on a phone the view switch and the new post button fit inside the card, on all channels and on a channel', function (bool $allChannels, string $tab) {
    [$user, $workspace, $channel] = publishPageSetup();
    $user->update(['locale' => Locale::from('pt-BR')]);
    SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
    $this->actingAs($user->fresh());

    $url = $allChannels ? route('app.posts.index', ['tab' => $tab]) : route('app.channels.publish', ['account' => $channel, 'tab' => $tab]);
    $page = visit($url)->resize(390, 844);
    waitFor($page, '@posts-new-post');

    $fits = $page->script(<<<'JS'
        (() => {
            const card = document.querySelector('[data-testid="publish-page"]').getBoundingClientRect();
            return ['posts-new-post', 'schedule-view-trigger'].every((testId) => {
                const box = document.querySelector(`[data-testid="${testId}"]`).getBoundingClientRect();
                return box.width > 0 && box.left >= card.left && box.right <= card.right;
            });
        })()
    JS);

    expect($fits)->toBeTrue();
    $page->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)
        ->assertNoJavaScriptErrors();
})->with([
    'all channels' => [true],
    'a channel' => [false],
])->with(['approvals', 'sent']);

test('the reel, story, ghost post and poll badges on a post card show a 16px icon', function (Platform $platform, ContentType $contentType) {
    [$user, $workspace] = publishPageSetup();
    $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform]);
    $post = Post::factory()->forAccount($account, $contentType)->create(['user_id' => $user->id, 'content' => 'Badge']);
    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => 'drafts']));
    waitFor($page, "@post-content-type-icon-{$post->id}");

    expect($page->script("(() => { const box = document.querySelector('[data-testid=\"post-content-type-icon-{$post->id}\"]').getBoundingClientRect(); return [Math.round(box.width), Math.round(box.height)]; })()"))->toBe([16, 16]);
    $page->assertNoJavaScriptErrors();
})->with([
    'instagram reel' => [Platform::Instagram, ContentType::InstagramReel],
    'instagram story' => [Platform::Instagram, ContentType::InstagramStory],
    'threads ghost post' => [Platform::Threads, ContentType::ThreadsGhostPost],
    'x poll' => [Platform::X, ContentType::XPoll],
]);

test('a post card names an x poll and leaves a regular x post unmarked', function (ContentType $contentType, bool $badged) {
    [$user, $workspace] = publishPageSetup();
    $x = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
    $post = Post::factory()->forAccount($x, $contentType)->create(['user_id' => $user->id, 'content' => 'Tabs or spaces?']);
    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => 'drafts']));
    waitFor($page, "@post-card-{$post->id}");

    $badged
        ? $page->assertSeeIn("@post-content-type-{$post->id}", __('posts.content_types.x_poll.label'))
        : $page->assertMissing("@post-content-type-{$post->id}");
    $page->assertNoJavaScriptErrors();
})->with([
    'poll' => [ContentType::XPoll, true],
    'post' => [ContentType::XPost, false],
]);

test('on a phone the channel filter opens as a sheet on the publish page and the calendar', function (string $route) {
    [$user, $workspace] = publishPageSetup();
    SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']);
    $this->actingAs($user);

    $page = visit(route($route))->resize(390, 844);
    waitFor($page, '@posts-channel-filter');
    $page->click('@posts-channel-filter');
    waitFor($page, '@posts-channel-sheet');

    $page->assertVisible('@posts-channel-sheet')
        ->assertNoJavaScriptErrors();
})->with(['app.posts.index', 'app.calendar']);

test('a thread in the queue shows each post with its own text and media, as the composer previews it', function () {
    [$user, $workspace] = publishPageSetup();
    connectAiTo($user);
    $x = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
    $post = Post::factory()->forAccount($x)->create([
        'user_id' => $user->id,
        'status' => PostStatus::Scheduled,
        'scheduled_at' => now()->addDay(),
        'content' => 'First post of the thread',
        'media' => [threadCardImage('root')],
        'meta' => ['thread_replies' => [
            ['text' => 'Second post of the thread', 'media' => []],
            ['text' => 'Third post, with a photo', 'media' => [threadCardImage('reply')]],
        ]],
    ]);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', $x));
    waitFor($page, "@post-thread-{$post->id}");

    $page->assertSeeIn("@post-thread-{$post->id}-0", 'First post of the thread')
        ->assertPresent("[data-testid=\"post-thread-{$post->id}-0\"] img[src=\"https://cdn.example.test/root.jpg\"]")
        ->assertSeeIn("@post-thread-{$post->id}-1", 'Second post of the thread')
        ->assertMissing("[data-testid=\"post-thread-{$post->id}-1\"] img[src^=\"https://cdn.example.test\"]")
        ->assertSeeIn("@post-thread-{$post->id}-2", 'Third post, with a photo')
        ->assertPresent("[data-testid=\"post-thread-{$post->id}-2\"] img[src=\"https://cdn.example.test/reply.jpg\"]")
        ->assertMissing("@post-thumbnail-{$post->id}-0")
        ->assertNoJavaScriptErrors();
});

test('a thread of polls in the queue shows each poll under its own post', function () {
    [$user, $workspace] = publishPageSetup();
    connectAiTo($user);
    $x = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
    $post = Post::factory()->forAccount($x)->create([
        'user_id' => $user->id,
        'status' => PostStatus::Scheduled,
        'scheduled_at' => now()->addDay(),
        'content_type' => ContentType::XPoll,
        'content' => 'Which desktop?',
        'meta' => [
            'poll' => ['options' => ['Linux', 'macOS'], 'duration_minutes' => 1440],
            'thread_replies' => [
                ['text' => 'And on the server?', 'media' => [], 'poll' => ['options' => ['Linux', 'Windows Server'], 'duration_minutes' => 1440]],
                ['text' => 'Thanks for voting', 'media' => [threadCardImage('reply')]],
            ],
        ],
    ]);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', $x));
    waitFor($page, "@post-thread-{$post->id}");

    $page->assertSeeIn("[data-testid=\"post-thread-{$post->id}-0\"] [data-testid=\"post-poll-{$post->id}\"]", 'macOS')
        ->assertSeeIn("[data-testid=\"post-thread-{$post->id}-1\"] [data-testid=\"post-poll-{$post->id}-reply-0\"]", 'Windows Server')
        ->assertMissing("[data-testid=\"post-thread-{$post->id}-2\"] [data-testid^=\"post-poll-\"]")
        ->assertPresent("[data-testid=\"post-thread-{$post->id}-2\"] img[src=\"https://cdn.example.test/reply.jpg\"]")
        ->assertMissing("@post-poll-{$post->id}-reply-0-caption");

    $page->click("@post-card-menu-{$post->id}");
    waitFor($page, "@post-details-open-{$post->id}");
    $page->click("@post-details-open-{$post->id}");
    waitFor($page, "@thread-view-{$post->id}");

    $page->assertSeeIn("[data-testid=\"thread-view-post-{$post->id}-0\"] [data-testid=\"post-details-poll\"]", 'macOS')
        ->assertSeeIn("[data-testid=\"thread-view-post-{$post->id}-1\"] [data-testid=\"post-details-poll-reply-0\"]", 'Windows Server')
        ->assertMissing('@post-details-poll-reply-0-caption')
        ->assertNoJavaScriptErrors();
});

/**
 * @return array<string, int|string>
 */
function threadCardImage(string $name): array
{
    return [
        'id' => (string) Str::uuid(),
        'path' => "medias/{$name}.jpg",
        'url' => "https://cdn.example.test/{$name}.jpg",
        'type' => 'image',
        'mime_type' => 'image/jpeg',
        'original_filename' => "{$name}.jpg",
        'size' => 1024,
    ];
}