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.

Show a posting activity heatmap on Insights (#528)

Paulo Castellanobca2fe33a352
diff --git a/AGENTS.md b/AGENTS.md
index d0965b7a7..7a1c8d49d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1350,6 +1350,7 @@ Whenever Laravel has a helper for something, use it instead of a native PHP func
- NEVER use inline class references (e.g., `\DB::listen`, `\Str::uuid()`). ALWAYS import classes at the top of the file with a `use` statement.
- PHP: `use Illuminate\Support\Facades\DB;` then `DB::listen(...)`
- TypeScript/Vue: `import { ref } from 'vue'` then `ref(...)`
+- **A class declares every trait it relies on, including the ones another trait brings in** (owner decision November 2026), so reading the class shows all the traits behind it. `PostController` uses `RendersPublishPage`, whose `flashQueuedToast()` calls `flashSuccessWithLink()` from `FlashesToast`; the trait keeps its own `use FlashesToast`, and the controller declares it too: `use FlashesToast, RendersPublishPage;`. PHP accepts the same trait reaching a class twice. Code written before this rule moves to it when touched, not in a sweep.
## API Response Status Codes
diff --git a/app/Actions/Analytics/BuildPostingActivity.php b/app/Actions/Analytics/BuildPostingActivity.php
new file mode 100644
index 000000000..59b03fdff
--- /dev/null
+++ b/app/Actions/Analytics/BuildPostingActivity.php
@@ -0,0 +1,93 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\Analytics;
+
+use App\Dto\Analytics\DateRange;
+use App\Dto\Analytics\PublicationFilter;
+use App\Models\Workspace;
+use Carbon\CarbonImmutable;
+use Carbon\CarbonInterface;
+use Carbon\CarbonPeriod;
+use Illuminate\Support\Collection;
+
+/**
+ * Posts that went out per day over the last year, for the Insights posting activity card.
+ *
+ * Counts the same publications as the posts chart (`BuildPublicationAnalyticsReport::query()`),
+ * on calendar days of the viewer's zone, whatever period the page shows.
+ */
+final class BuildPostingActivity
+{
+ public const int DAYS = 365;
+
+ public function __construct(private readonly BuildPublicationAnalyticsReport $publications) {}
+
+ /**
+ * @param list<string>|null $accountKeys Null counts every analytics account of the workspace.
+ * @return array{start: string, end: string, days: list<array{date: string, count: int}>, total: int, max_count: int, current_streak: int, best_streak: int}
+ */
+ public function execute(Workspace $workspace, ?array $accountKeys, string $timezone, ?PublicationFilter $filter = null): array
+ {
+ $today = CarbonImmutable::parse(now($timezone)->toDateString(), 'UTC');
+ $range = new DateRange($today->subDays(self::DAYS - 1), $today, timezone: $timezone);
+
+ $published = $this->publications->query($workspace, $range->startsAt(), $range->endsAt(), $accountKeys, $filter)
+ ->select('publication.provider_published_at')
+ ->cursor()
+ ->countBy(fn (object $row): string => $range->localDate($row->provider_published_at));
+
+ $days = collect(CarbonPeriod::create($range->start, $range->end))
+ ->map(fn (CarbonInterface $day): array => [
+ 'date' => $day->toDateString(),
+ 'count' => (int) $published->get($day->toDateString(), 0),
+ ])
+ ->values();
+ $streaks = self::streaks($days->all());
+
+ return [
+ 'start' => $range->start->toDateString(),
+ 'end' => $range->end->toDateString(),
+ 'days' => $days->all(),
+ 'total' => $days->sum('count'),
+ 'max_count' => $days->max('count'),
+ 'current_streak' => data_get($streaks, 'current'),
+ 'best_streak' => data_get($streaks, 'best'),
+ ];
+ }
+
+ /**
+ * Runs of days with at least one post. The current run ends on the last day,
+ * or on the day before when the last day has no post yet.
+ *
+ * @param list<array{date: string, count: int}> $days Chronological, one entry per day.
+ * @return array{current: int, best: int}
+ */
+ public static function streaks(array $days): array
+ {
+ $best = 0;
+ $run = 0;
+
+ foreach ($days as $day) {
+ $run = data_get($day, 'count') > 0 ? $run + 1 : 0;
+ $best = max($best, $run);
+ }
+
+ return ['current' => self::currentStreak(collect($days)), 'best' => $best];
+ }
+
+ /**
+ * @param Collection<int, array{date: string, count: int}> $days
+ */
+ private static function currentStreak(Collection $days): int
+ {
+ if (data_get($days->last(), 'count', 0) === 0) {
+ $days = $days->slice(0, -1);
+ }
+
+ return $days->reverse()
+ ->takeWhile(fn (array $day): bool => data_get($day, 'count') > 0)
+ ->count();
+ }
+}
diff --git a/app/Actions/Analytics/BuildPostingStreak.php b/app/Actions/Analytics/BuildPostingStreak.php
new file mode 100644
index 000000000..dc2111858
--- /dev/null
+++ b/app/Actions/Analytics/BuildPostingStreak.php
@@ -0,0 +1,103 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\Analytics;
+
+use App\Enums\SocialAccount\Platform;
+use App\Enums\User\WeekStart;
+use App\Models\AnalyticsPublication;
+use App\Models\Post;
+use App\Models\Workspace;
+use Carbon\CarbonImmutable;
+use Carbon\CarbonInterface;
+use Illuminate\Support\Collection;
+use Illuminate\Support\LazyCollection;
+
+/**
+ * Weeks in a row a workspace posted, for the streak badge in the sidebar.
+ *
+ * A week counts once anything went out in it: every publication Insights reads
+ * (published through TryPost or directly on the network), plus what TryPost
+ * published on the networks Insights does not read (LinkedIn, Google Business,
+ * Telegram, Discord). Each TryPost post on an Insights network is also one of its
+ * publications, so it is read once.
+ */
+final class BuildPostingStreak
+{
+ /** How many weeks a streak is read over, this one included; a longer one reads as this long. */
+ public const int WEEKS = 104;
+
+ /**
+ * @return array{weeks: int, posted_this_week: bool}
+ */
+ public function execute(Workspace $workspace, string $timezone, WeekStart $weekStart): array
+ {
+ $thisWeek = CarbonImmutable::now($timezone)->startOfWeek($weekStart->firstDay());
+ $weeks = self::postingInstants([$workspace->id], $thisWeek->subWeeks(self::WEEKS - 1)->utc())
+ ->map(fn (object $row): string => self::weekOf($row->at, $timezone, $weekStart))
+ ->unique()
+ ->collect();
+
+ return [
+ 'weeks' => self::streak($weeks, $thisWeek),
+ 'posted_this_week' => $weeks->contains($thisWeek->toDateString()),
+ ];
+ }
+
+ /**
+ * When each workspace posted since `$since`, from both sources.
+ *
+ * @param list<string> $workspaceIds
+ * @return LazyCollection<int, object{workspace_id: string, at: string}>
+ */
+ public static function postingInstants(array $workspaceIds, CarbonInterface $since): LazyCollection
+ {
+ $publications = AnalyticsPublication::query()
+ ->select(['workspace_id', 'provider_published_at as at'])
+ ->whereIn('platform', Platform::analyticsValues())
+ ->whereIn('workspace_id', $workspaceIds)
+ ->where('provider_published_at', '>=', $since);
+
+ $posts = Post::query()
+ ->select(['workspace_id', 'published_at as at'])
+ ->wentOut()
+ ->outsideAnalytics()
+ ->whereIn('workspace_id', $workspaceIds)
+ ->where('published_at', '>=', $since);
+
+ return $publications->toBase()->unionAll($posts->toBase())->cursor();
+ }
+
+ /** The first day of the week `$instant` falls in, in the viewer's zone and week. */
+ public static function weekOf(string $instant, string $timezone, WeekStart $weekStart): string
+ {
+ return CarbonImmutable::parse($instant, 'UTC')
+ ->setTimezone($timezone)
+ ->startOfWeek($weekStart->firstDay())
+ ->toDateString();
+ }
+
+ /**
+ * Weeks in a row with a post, ending this week, or last week while this one has none yet.
+ *
+ * @param Collection<int, string> $weeks The first day of each week with a post.
+ */
+ public static function streak(Collection $weeks, CarbonImmutable $thisWeek): int
+ {
+ $week = $thisWeek;
+
+ if (! $weeks->contains($week->toDateString())) {
+ $week = $week->subWeek();
+ }
+
+ $streak = 0;
+
+ while ($weeks->contains($week->toDateString())) {
+ $streak++;
+ $week = $week->subWeek();
+ }
+
+ return $streak;
+ }
+}
diff --git a/app/Actions/Analytics/RankPostingStreaks.php b/app/Actions/Analytics/RankPostingStreaks.php
new file mode 100644
index 000000000..ef8558bd5
--- /dev/null
+++ b/app/Actions/Analytics/RankPostingStreaks.php
@@ -0,0 +1,110 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\Analytics;
+
+use App\Enums\User\WeekStart;
+use App\Models\Workspace;
+use Carbon\CarbonImmutable;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\LazyCollection;
+
+/**
+ * Where a streak stands among every workspace with app access, for the "Top X%"
+ * in the streak popover. Recomputed daily on Monday weeks in UTC, close enough
+ * to rank a streak whatever week its viewer starts on.
+ */
+final class RankPostingStreaks
+{
+ /** The shares the popover names, smallest first; a streak below the last one gets none. */
+ public const array TOP_PERCENTS = [1, 5, 10, 25, 50];
+
+ private const string CACHE_KEY = 'posting-streak:ranks';
+
+ /** Fewer workspaces than this rank nothing: a small install would only rank itself. */
+ public const int MIN_RANKED = 10;
+
+ private const int CHUNK = 200;
+
+ public function execute(): void
+ {
+ $thisWeek = CarbonImmutable::now('UTC')->startOfWeek(WeekStart::Monday->firstDay());
+ $since = $thisWeek->subWeeks(BuildPostingStreak::WEEKS - 1);
+
+ $streaks = Workspace::query()
+ ->with('account.subscriptions')
+ ->lazyById(self::CHUNK)
+ ->filter(fn (Workspace $workspace): bool => $workspace->account?->hasAppAccess() === true)
+ ->chunk(self::CHUNK)
+ ->flatMap(fn (LazyCollection $workspaces): Collection => self::streaksOf($workspaces->pluck('id')->values()->all(), $since, $thisWeek))
+ ->collect();
+
+ Cache::forever(self::CACHE_KEY, self::thresholds($streaks));
+ }
+
+ /**
+ * The streak of each workspace, read a chunk at a time so the posts of every
+ * workspace are never held at once.
+ *
+ * @param list<string> $workspaceIds
+ * @return Collection<int, int>
+ */
+ private static function streaksOf(array $workspaceIds, CarbonImmutable $since, CarbonImmutable $thisWeek): Collection
+ {
+ $weeks = BuildPostingStreak::postingInstants($workspaceIds, $since)
+ ->collect()
+ ->groupBy('workspace_id')
+ ->map(fn (Collection $rows): Collection => $rows
+ ->map(fn (object $row): string => BuildPostingStreak::weekOf($row->at, 'UTC', WeekStart::Monday))
+ ->unique());
+
+ return collect($workspaceIds)->map(fn (string $id): int => BuildPostingStreak::streak($weeks->get($id, collect()), $thisWeek));
+ }
+
+ /**
+ * The fewest weeks each "Top X%" needs: one past the longest streak still
+ * shared by more than that share of the workspaces, so the rank keeps one
+ * number per share instead of every workspace's streak.
+ *
+ * @param Collection<int, int> $streaks
+ * @return array<int, int>
+ */
+ private static function thresholds(Collection $streaks): array
+ {
+ if ($streaks->count() < self::MIN_RANKED) {
+ return [];
+ }
+
+ $running = 0;
+ $atLeast = $streaks->countBy()
+ ->sortKeysDesc()
+ ->map(function (int $count) use (&$running): int {
+ $running += $count;
+
+ return $running;
+ });
+
+ return collect(self::TOP_PERCENTS)
+ ->mapWithKeys(fn (int $percent): array => [
+ $percent => ($atLeast
+ ->filter(fn (int $count, int $streak): bool => $streak >= 1 && $count / $streaks->count() * 100 > $percent)
+ ->keys()
+ ->max() ?? 0) + 1,
+ ])
+ ->all();
+ }
+
+ /** The smallest "Top X%" a streak reaches among the ranked workspaces, or null below the last one. */
+ public static function topPercent(int $weeks): ?int
+ {
+ $thresholds = collect(Cache::get(self::CACHE_KEY, []));
+
+ if ($weeks < 1) {
+ return null;
+ }
+
+ return $thresholds->keys()->first(fn (int $percent): bool => $weeks >= $thresholds->get($percent));
+ }
+}
diff --git a/app/Actions/Analytics/ShowPostingStreak.php b/app/Actions/Analytics/ShowPostingStreak.php
new file mode 100644
index 000000000..e2e4bb9c7
--- /dev/null
+++ b/app/Actions/Analytics/ShowPostingStreak.php
@@ -0,0 +1,89 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Actions\Analytics;
+
+use App\Models\User;
+use App\Models\Workspace;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+
+/**
+ * The streak badge the sidebar shows on every page, cached for a few minutes per
+ * user and workspace so a page change never reads the posts again. A post going
+ * out forgets the workspace's badges, so the next page counts it at once.
+ */
+final class ShowPostingStreak
+{
+ private const int CACHE_MINUTES = 10;
+
+ /**
+ * The streak of the user's current workspace, read in their zone and week,
+ * while its account has app access; null hides the badge.
+ *
+ * @return array{weeks: int, posted_this_week: bool, top_percent: ?int}|null
+ */
+ public static function forSidebar(?User $user): ?array
+ {
+ $workspace = $user?->currentWorkspace;
+
+ if (blank($workspace)) {
+ return null;
+ }
+
+ if ($workspace->account?->hasAppAccess() !== true) {
+ return null;
+ }
+
+ return self::cached($user, $workspace);
+ }
+
+ /**
+ * Null while the workspace has no streak: the sidebar shows no badge then.
+ * The streak is cached even at zero weeks, since the cache keeps no null.
+ *
+ * @return array{weeks: int, posted_this_week: bool, top_percent: ?int}|null
+ */
+ public static function cached(User $user, Workspace $workspace): ?array
+ {
+ $version = Cache::get(self::versionKey($workspace->id), '0');
+
+ $streak = Cache::remember(
+ "posting-streak:{$workspace->id}:{$version}:{$user->id}:{$user->timezone}:{$user->week_starts_on->value}",
+ now()->addMinutes(self::CACHE_MINUTES),
+ fn (): array => self::build($user, $workspace),
+ );
+
+ if (data_get($streak, 'weeks') === 0) {
+ return null;
+ }
+
+ return $streak;
+ }
+
+ /** Drops every member's cached badge of the workspace, once the change that calls it is committed. */
+ public static function forget(string $workspaceId): void
+ {
+ DB::afterCommit(fn () => Cache::forever(self::versionKey($workspaceId), (string) Str::ulid()));
+ }
+
+ private static function versionKey(string $workspaceId): string
+ {
+ return "posting-streak:version:{$workspaceId}";
+ }
+
+ /**
+ * @return array{weeks: int, posted_this_week: bool, top_percent: ?int}
+ */
+ private static function build(User $user, Workspace $workspace): array
+ {
+ $streak = app(BuildPostingStreak::class)->execute($workspace, $user->timezone, $user->week_starts_on);
+
+ return [
+ ...$streak,
+ 'top_percent' => RankPostingStreaks::topPercent(data_get($streak, 'weeks')),
+ ];
+ }
+}
diff --git a/app/Console/Commands/Analytics/RankPostingStreaks.php b/app/Console/Commands/Analytics/RankPostingStreaks.php
new file mode 100644
index 000000000..543666c39
--- /dev/null
+++ b/app/Console/Commands/Analytics/RankPostingStreaks.php
@@ -0,0 +1,22 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Console\Commands\Analytics;
+
+use App\Actions\Analytics\RankPostingStreaks as RankPostingStreaksAction;
+use Illuminate\Console\Attributes\Description;
+use Illuminate\Console\Attributes\Signature;
+use Illuminate\Console\Command;
+
+#[Signature('analytics:rank-posting-streaks')]
+#[Description('Rank every workspace posting streak for the "Top X%" of the streak popover')]
+class RankPostingStreaks extends Command
+{
+ public function handle(RankPostingStreaksAction $ranks): int
+ {
+ $ranks->execute();
+
+ return self::SUCCESS;
+ }
+}
diff --git a/app/Enums/Post/ScheduleAction.php b/app/Enums/Post/ScheduleAction.php
index dde652492..e80b28f7b 100644
--- a/app/Enums/Post/ScheduleAction.php
+++ b/app/Enums/Post/ScheduleAction.php
@@ -30,4 +30,18 @@ enum ScheduleAction: string
self::Reschedule => throw new LogicException('Reschedule goes through ReschedulePost.'),
};
}
+
+ /**
+ * What the toast says once the action puts the post in the queue; null for
+ * an action that does not. The top of the queue is a move, not an addition:
+ * "Move to top" only reaches posts already queued.
+ */
+ public function queuedMessage(): ?string
+ {
+ return match ($this) {
+ self::QueueNext => trans_choice('posts.composer.queue.added', 1, ['count' => 1]),
+ self::QueueTop => __('posts.composer.queue.moved_to_top'),
+ self::Draft, self::PublishNow, self::Reschedule => null,
+ };
+ }
}
diff --git a/app/Http/Controllers/App/ChannelController.php b/app/Http/Controllers/App/ChannelController.php
index d963a157d..9396aa479 100644
--- a/app/Http/Controllers/App/ChannelController.php
+++ b/app/Http/Controllers/App/ChannelController.php
@@ -7,6 +7,7 @@ namespace App\Http\Controllers\App;
use App\Actions\Analytics\BuildChannelMetricSeries;
use App\Actions\Analytics\BuildFollowerGrowthRateSeries;
use App\Actions\Analytics\BuildInsightsExport;
+use App\Actions\Analytics\BuildPostingActivity;
use App\Actions\Analytics\BuildWorkspaceAnalyticsReport;
use App\Actions\Analytics\ListAvailableChannelMetrics;
use App\Actions\Analytics\ListChannelPublicationPerformance;
@@ -22,6 +23,7 @@ use App\Enums\Analytics\ExportFormat;
use App\Enums\PostPlatform\ContentType;
use App\Http\Controllers\App\Concerns\EnsuresChannelInCurrentWorkspace;
use App\Http\Controllers\App\Concerns\RendersPublishPage;
+use App\Http\Controllers\Concerns\FlashesToast;
use App\Http\Requests\App\Channel\ChannelInsightsRequest;
use App\Http\Requests\App\Channel\DownloadChannelInsightsRequest;
use App\Http\Requests\App\Channel\ListChannelsRequest;
@@ -45,7 +47,7 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
class ChannelController extends Controller
{
- use EnsuresChannelInCurrentWorkspace, RendersPublishPage;
+ use EnsuresChannelInCurrentWorkspace, FlashesToast, RendersPublishPage;
public function index(ListChannelsRequest $request): Response
{
@@ -167,6 +169,7 @@ class ChannelController extends Controller
ListChannelPublicationPerformance $performance,
BuildChannelMetricSeries $series,
BuildFollowerGrowthRateSeries $growthRate,
+ BuildPostingActivity $postingActivity,
): Response {
$workspace = $request->user()->currentWorkspace;
$this->authorize('view', $workspace);
@@ -238,6 +241,7 @@ class ChannelController extends Controller
: null,
];
}),
+ 'postingActivity' => Inertia::defer(fn (): array => $postingActivity->execute($workspace, [$accountKey], $request->user()->timezone, $filter), 'activity'),
'publications' => function () use ($resolve, $performance, $account, $accountKey, $period, $sort, $filter, $request): LengthAwarePaginator {
$current = data_get($resolve(), 'range');
diff --git a/app/Http/Controllers/App/Concerns/RendersPublishPage.php b/app/Http/Controllers/App/Concerns/RendersPublishPage.php
index 9af06b69a..692e2d1f9 100644
--- a/app/Http/Controllers/App/Concerns/RendersPublishPage.php
+++ b/app/Http/Controllers/App/Concerns/RendersPublishPage.php
@@ -6,6 +6,7 @@ namespace App\Http\Controllers\App\Concerns;
use App\Actions\Post\BuildPublishPageProps;
use App\Enums\Post\Status as PostStatus;
+use App\Http\Controllers\Concerns\FlashesToast;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\Workspace;
@@ -26,6 +27,8 @@ use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
trait RendersPublishPage
{
+ use FlashesToast;
+
private const array PUBLISH_PAGE_ROUTES = ['app.posts.index', 'app.channels.publish'];
private function renderPublishPage(Request $request, Workspace $workspace, ?SocialAccount $channel = null): Response|RedirectResponse
@@ -164,6 +167,14 @@ trait RendersPublishPage
]);
}
+ /** The toast once a post goes to the queue, linking to it: a member who needs approval only asked for it. */
+ private function flashQueuedToast(Post $post, string $queued): void
+ {
+ $message = $post->status === PostStatus::PendingApproval ? __('posts.approvals.requested') : $queued;
+
+ $this->flashSuccessWithLink($message, __('posts.actions.view'), route('app.posts.index', ['post' => $post->id]));
+ }
+
private function canOpenComposer(Post $post): bool
{
if (! $post->hasChannel()) {
diff --git a/app/Http/Controllers/App/InsightsController.php b/app/Http/Controllers/App/InsightsController.php
index 0a2779708..c39cf65eb 100644
--- a/app/Http/Controllers/App/InsightsController.php
+++ b/app/Http/Controllers/App/InsightsController.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Http\Controllers\App;
use App\Actions\Analytics\BuildInsightsExport;
+use App\Actions\Analytics\BuildPostingActivity;
use App\Actions\Analytics\BuildWorkspaceAnalyticsReport;
use App\Actions\Analytics\ListAvailableChannelMetrics;
use App\Actions\Analytics\ReadPublicationAnalytics;
@@ -31,6 +32,7 @@ class InsightsController extends Controller
ResolveAnalyticsRangePreset $presets,
ResolveAnalyticsChannelFilter $channelFilter,
ListAvailableChannelMetrics $availableMetrics,
+ BuildPostingActivity $postingActivity,
): Response {
$workspace = $request->user()->currentWorkspace;
$this->authorize('view', $workspace);
@@ -46,6 +48,12 @@ class InsightsController extends Controller
'labels' => fn () => $workspace->labels()->orderBy('name')->get(['id', 'name', 'color']),
'availableMetrics' => $single === null ? null : $availableMetrics->handle($single, data_get($channelKeys, $single->id)),
'sync' => SyncCadence::toArray(),
+ 'postingActivity' => Inertia::defer(fn (): array => $postingActivity->execute(
+ $workspace,
+ $analytics->keys($channelKeys),
+ $request->user()->timezone,
+ $filter,
+ ), 'activity'),
'report' => [
...$report,
'filters' => [
diff --git a/app/Http/Controllers/App/PostController.php b/app/Http/Controllers/App/PostController.php
index 308b1d775..f96350a2b 100644
--- a/app/Http/Controllers/App/PostController.php
+++ b/app/Http/Controllers/App/PostController.php
@@ -15,6 +15,7 @@ use App\Enums\Post\Action as PostAction;
use App\Enums\Post\CreatedVia;
use App\Enums\Post\Status as PostStatus;
use App\Http\Controllers\App\Concerns\RendersPublishPage;
+use App\Http\Controllers\Concerns\FlashesToast;
use App\Http\Requests\App\Post\StorePostRequest;
use App\Http\Requests\App\Post\UpdatePostRequest;
use App\Models\Post;
@@ -28,7 +29,7 @@ use Symfony\Component\HttpFoundation\Response as HttpResponse;
class PostController extends Controller
{
- use RendersPublishPage;
+ use FlashesToast, RendersPublishPage;
public function index(Request $request): Response|RedirectResponse
{
@@ -140,6 +141,10 @@ class PostController extends Controller
default => [],
};
+ if ($request->filled('queue')) {
+ $this->flashQueuedToast($posts->first(), trans_choice('posts.composer.queue.added', $posts->count(), ['count' => $posts->count()]));
+ }
+
return redirect($this->originPageUrl($tab))
->with('created_post_ids', $posts->pluck('id')->all());
}
diff --git a/app/Http/Controllers/App/PostScheduleController.php b/app/Http/Controllers/App/PostScheduleController.php
index 76fe27656..8c5db7e12 100644
--- a/app/Http/Controllers/App/PostScheduleController.php
+++ b/app/Http/Controllers/App/PostScheduleController.php
@@ -9,6 +9,7 @@ use App\Actions\Post\UpdatePost;
use App\Enums\Post\Action as PostAction;
use App\Enums\Post\ScheduleAction;
use App\Http\Controllers\App\Concerns\RendersPublishPage;
+use App\Http\Controllers\Concerns\FlashesToast;
use App\Http\Requests\App\Post\UpdatePostScheduleRequest;
use App\Models\Post;
use App\Support\PostStatusRules;
@@ -16,7 +17,7 @@ use Illuminate\Http\RedirectResponse;
class PostScheduleController extends Controller
{
- use RendersPublishPage;
+ use FlashesToast, RendersPublishPage;
public function update(UpdatePostScheduleRequest $request, Post $post): RedirectResponse
{
@@ -42,8 +43,15 @@ class PostScheduleController extends Controller
$action = data_get($result, 'action');
if ($action === PostAction::Finalized) {
- session()->flash('flash.banner', __('posts.flash.cannot_edit_finalized'));
- session()->flash('flash.bannerStyle', 'danger');
+ return back()
+ ->with('flash.banner', __('posts.flash.cannot_edit_finalized'))
+ ->with('flash.bannerStyle', 'danger');
+ }
+
+ $queuedMessage = $scheduleAction->queuedMessage();
+
+ if (filled($queuedMessage)) {
+ $this->flashQueuedToast(data_get($result, 'post'), $queuedMessage);
}
if ($scheduleAction === ScheduleAction::PublishNow && in_array($action, [PostAction::Publishing, PostAction::Scheduled], true)) {
diff --git a/app/Http/Controllers/Concerns/FlashesToast.php b/app/Http/Controllers/Concerns/FlashesToast.php
new file mode 100644
index 000000000..48496fc69
--- /dev/null
+++ b/app/Http/Controllers/Concerns/FlashesToast.php
@@ -0,0 +1,19 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Controllers\Concerns;
+
+/**
+ * Flashes the toast the next page shows (`Toast.vue`). Any controller can use
+ * it; a message without a link still goes through `->with('flash.success', …)`.
+ */
+trait FlashesToast
+{
+ /** A success toast with a link after its message, like "View post". */
+ protected function flashSuccessWithLink(string $message, string $label, string $url): void
+ {
+ session()->flash('flash.success', $message);
+ session()->flash('flash.link', ['label' => $label, 'url' => $url]);
+ }
+}
diff --git a/app/Http/Middleware/App/HandleInertiaRequests.php b/app/Http/Middleware/App/HandleInertiaRequests.php
index 10df1e5fd..9dab7521c 100644
--- a/app/Http/Middleware/App/HandleInertiaRequests.php
+++ b/app/Http/Middleware/App/HandleInertiaRequests.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Http\Middleware\App;
use App\Actions\AccessToken\HasConnectedMcpClient;
+use App\Actions\Analytics\ShowPostingStreak;
use App\Actions\Changelog\BuildChangelogProps;
use App\Enums\Auth\SocialAuthProvider;
use App\Enums\Media\Source as MediaSource;
@@ -28,6 +29,7 @@ use App\Support\HeicConverter;
use App\Support\LinkTlds;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
+use Inertia\Inertia;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
@@ -64,6 +66,7 @@ class HandleInertiaRequests extends Middleware
'hasActiveSubscription' => $account ? $account->hasActiveSubscription() : false,
'subscriptionPastDue' => $account ? $account->isPastDue() : false,
],
+ 'postingStreak' => fn (): ?array => ShowPostingStreak::forSidebar($user),
'channels' => fn (): array => $user?->currentWorkspace
? SidebarChannelResource::collection($user->currentWorkspace)
: [],
@@ -74,7 +77,7 @@ class HandleInertiaRequests extends Middleware
'usage' => fn (): ?array => $account && ! $isSelfHosted ? $account->usage() : null,
'features' => fn (): ?array => $account && ! $isSelfHosted ? $account->featureLimits() : null,
...($user ? BuildChangelogProps::execute($user) : []),
- 'flash' => $request->session()->get('flash', []),
+ 'flash' => Inertia::always(fn (): array => $request->session()->get('flash', [])),
'applicationUrl' => config('app.url'),
'env' => config('app.env'),
'locale' => app()->getLocale(),
diff --git a/app/Models/AnalyticsPublication.php b/app/Models/AnalyticsPublication.php
index 73cbb53b4..ef072db24 100644
--- a/app/Models/AnalyticsPublication.php
+++ b/app/Models/AnalyticsPublication.php
@@ -9,7 +9,9 @@ use App\Enums\Analytics\PublicationAvailability;
use App\Enums\Analytics\PublicationContentType;
use App\Enums\Analytics\PublicationOrigin;
use App\Enums\SocialAccount\Platform;
+use App\Observers\AnalyticsPublicationObserver;
use Database\Factories\AnalyticsPublicationFactory;
+use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -17,6 +19,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
+#[ObservedBy([AnalyticsPublicationObserver::class])]
class AnalyticsPublication extends Model
{
/** @use HasFactory<AnalyticsPublicationFactory> */
diff --git a/app/Models/Post.php b/app/Models/Post.php
index 55daa5a05..02d671133 100644
--- a/app/Models/Post.php
+++ b/app/Models/Post.php
@@ -419,6 +419,12 @@ class Post extends Model
return $query->whereIn('posts.platform', Platform::analyticsValues());
}
+ /** Posts on the networks Insights does not read (LinkedIn, Google Business, Telegram, Discord). */
+ public function scopeOutsideAnalytics(Builder $query): Builder
+ {
+ return $query->whereNotIn('posts.platform', Platform::analyticsValues());
+ }
+
/**
* Posts carrying any of the labels, plus posts without labels when $untagged is set; no filter when both are empty.
*
diff --git a/app/Observers/AnalyticsPublicationObserver.php b/app/Observers/AnalyticsPublicationObserver.php
new file mode 100644
index 000000000..964b72bc6
--- /dev/null
+++ b/app/Observers/AnalyticsPublicationObserver.php
@@ -0,0 +1,24 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Observers;
+
+use App\Actions\Analytics\ShowPostingStreak;
+use App\Models\AnalyticsPublication;
+
+/** Keeps the sidebar's posting streak in step with the publications Insights finds. */
+class AnalyticsPublicationObserver
+{
+ public function saved(AnalyticsPublication $publication): void
+ {
+ if ($publication->wasRecentlyCreated || $publication->wasChanged('provider_published_at')) {
+ ShowPostingStreak::forget($publication->workspace_id);
+ }
+ }
+
+ public function deleted(AnalyticsPublication $publication): void
+ {
+ ShowPostingStreak::forget($publication->workspace_id);
+ }
+}
diff --git a/app/Observers/PostObserver.php b/app/Observers/PostObserver.php
index 3c8018db5..fad79565f 100644
--- a/app/Observers/PostObserver.php
+++ b/app/Observers/PostObserver.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Observers;
use App\Actions\Analytics\ResolveAnalyticsAccountKey;
+use App\Actions\Analytics\ShowPostingStreak;
use App\Dto\Analytics\TryPostPublicationIdentity;
use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
@@ -53,6 +54,10 @@ class PostObserver
return;
}
+ if ($this->movesPostingStreak($post)) {
+ ShowPostingStreak::forget($post->workspace_id);
+ }
+
$networkEvent = EventType::fromPublishStatus($post->publish_status, $post->getOriginal('publish_status'));
if (filled($networkEvent)) {
@@ -110,4 +115,10 @@ class PostObserver
->delay(now()->addSeconds(SyncAccountPublishingActivity::DEBOUNCE_SECONDS))
->afterCommit();
}
+
+ /** Whether the post started or stopped counting as sent, the only change the posting streak sees. */
+ private function movesPostingStreak(Post $post): bool
+ {
+ return $post->publish_status->wentOut() !== $post->getOriginal('publish_status')->wentOut();
+ }
}
diff --git a/lang/ar/analytics.php b/lang/ar/analytics.php
index aafe6a164..f847e6d2e 100644
--- a/lang/ar/analytics.php
+++ b/lang/ar/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric عبر قنواتنا: :value (:range) 📈',
'caption_summary_workspace' => 'أرقامنا للفترة :range 📈 :metrics',
'caption_summary_channel' => 'أرقامنا على :channel للفترة :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 :days من النشر المتواصل، وهذه أطول سلسلة لنا حتى الآن! عدد المنشورات خلال آخر 12 شهرًا: :posts.',
+ 'on_streak' => '🔥 :days من النشر المتواصل. رقمنا القياسي :best، وعدد المنشورات خلال آخر 12 شهرًا: :posts.',
+ 'no_streak' => '📅 عدد المنشورات خلال آخر 12 شهرًا: :posts، وأطول سلسلة نشر متواصل لنا :best.',
+ ],
'export_failed' => 'تعذّر إنشاء الصورة. حاول مرة أخرى.',
'colors' => [
'violet' => 'بنفسجي',
@@ -448,4 +453,33 @@ return [
'slate' => 'أردوازي',
],
],
+ 'posting_activity' => [
+ 'title' => 'نشاط النشر',
+ 'subtitle' => 'آخر 12 شهرًا',
+ 'current_streak' => 'السلسلة الحالية',
+ 'best_streak' => 'أطول سلسلة',
+ 'total' => 'المنشورات',
+ 'days' => '{0} :count يوم|{1} يوم واحد|{2} يومان|[3,10] :count أيام|[100,102] :count يوم|[103,110] :count أيام|[200,202] :count يوم|[203,210] :count أيام|[300,302] :count يوم|[303,310] :count أيام|[0,*] :count يومًا',
+ 'less' => 'أقل',
+ 'more' => 'أكثر',
+ 'posts_on_day' => '{0} لا توجد منشورات|[1,*] المنشورات: :count',
+ 'about' => [
+ 'current_streak' => 'الأيام المتتالية التي نشرت فيها. انشر مرة واحدة على الأقل يوميًا للحفاظ على السلسلة.',
+ 'best_streak' => 'أكبر عدد من الأيام المتتالية التي نشرت فيها خلال آخر 12 شهرًا.',
+ 'total' => 'كل ما نشرته خلال آخر 12 شهرًا، بما في ذلك ما نشرته خارج TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'عرض السلسلة',
+ 'title' => 'أسابيع متتالية: :count',
+ 'top' => 'أفضل :percent%',
+ 'rank_tooltip' => 'مقارنةً بمستخدمي TryPost الآخرين',
+ 'keep_going' => 'عمل رائع! جدول منشورًا للأسبوع القادم للحفاظ على السلسلة.',
+ 'post_this_week' => 'لم تنشر هذا الأسبوع بعد. جدول منشورًا للحفاظ على سلسلتك.',
+ 'schedule' => 'جدولة منشور',
+ 'share' => 'مشاركة السلسلة',
+ 'share_caption' => 'أنشر مع TryPost منذ أسابيع متتالية: :count!',
+ 'image_weeks' => '{1} أسبوع|{2} أسبوعان|[3,10] أسابيع|[100,102] أسبوع|[103,110] أسابيع|[0,*] أسبوعًا',
+ 'image_tagline' => 'من النشر المنتظم!',
+ ],
];
diff --git a/lang/ar/posts.php b/lang/ar/posts.php
index 3dc10bcca..1f986aaf7 100644
--- a/lang/ar/posts.php
+++ b/lang/ar/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'ضع هذا المنشور في أعلى قائمة الانتظار.',
'add' => 'إضافة إلى قائمة الانتظار',
'add_many' => 'إضافة :count إلى قائمة الانتظار',
- 'added' => '{1} تمت الإضافة إلى قائمة الانتظار|[0,*] تمت الإضافة إلى قائمة الانتظار: :count',
+ 'added' => '{1} تمت إضافة منشورك إلى قائمة الانتظار.|[0,*] المنشورات المضافة إلى قائمة الانتظار: :count.',
+ 'moved_to_top' => 'تم نقل منشورك إلى أعلى قائمة الانتظار.',
'no_slots_hint' => 'أضف أوقات النشر لاستخدام قائمة الانتظار.',
'no_slots_channels' => 'لا توجد أوقات نشر: :channels',
'no_slots_tooltip' => 'لا توجد أوقات نشر لـ :channels. أضف أوقات نشر لاستخدام قائمة الانتظار.',
diff --git a/lang/de/analytics.php b/lang/de/analytics.php
index 9f7e0c805..f8ea6be29 100644
--- a/lang/de/analytics.php
+++ b/lang/de/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric auf unseren Kanälen: :value (:range) 📈',
'caption_summary_workspace' => 'Unsere Zahlen für :range 📈 :metrics',
'caption_summary_channel' => 'Unsere Zahlen auf :channel für :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '{1} 🔥 :days in Folge gepostet, unsere bisher längste Serie! :posts Beitrag in den letzten 12 Monaten.|[0,*] 🔥 :days in Folge gepostet, unsere bisher längste Serie! :posts Beiträge in den letzten 12 Monaten.',
+ 'on_streak' => '{1} 🔥 :days in Folge gepostet. Unser Rekord: :best, mit :posts Beitrag in den letzten 12 Monaten.|[0,*] 🔥 :days in Folge gepostet. Unser Rekord: :best, mit :posts Beiträgen in den letzten 12 Monaten.',
+ 'no_streak' => '{1} 📅 :posts Beitrag in den letzten 12 Monaten. Längste Serie: :best in Folge.|[0,*] 📅 :posts Beiträge in den letzten 12 Monaten. Längste Serie: :best in Folge.',
+ ],
'export_failed' => 'Bild konnte nicht erstellt werden. Versuche es erneut.',
'colors' => [
'violet' => 'Violett',
@@ -448,4 +453,33 @@ return [
'slate' => 'Schiefer',
],
],
+ 'posting_activity' => [
+ 'title' => 'Posting-Aktivität',
+ 'subtitle' => 'Letzte 12 Monate',
+ 'current_streak' => 'Aktuelle Serie',
+ 'best_streak' => 'Längste Serie',
+ 'total' => 'Beiträge',
+ 'days' => '{1} :count Tag|[0,*] :count Tage',
+ 'less' => 'Weniger',
+ 'more' => 'Mehr',
+ 'posts_on_day' => '{0} Keine Beiträge|{1} :count Beitrag|[2,*] :count Beiträge',
+ 'about' => [
+ 'current_streak' => 'Tage in Folge, an denen du gepostet hast. Poste mindestens einmal am Tag, um die Serie zu halten.',
+ 'best_streak' => 'Deine meisten Tage in Folge mit einem Beitrag in den letzten 12 Monaten.',
+ 'total' => 'Alles, was du in den letzten 12 Monaten gepostet hast, auch außerhalb von TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Serie ansehen',
+ 'title' => '{1} :count Woche in Folge|[0,*] :count Wochen in Folge',
+ 'top' => 'Top :percent %',
+ 'rank_tooltip' => 'Im Vergleich zu anderen TryPost-Nutzern',
+ 'keep_going' => 'Super! Plane einen Beitrag für nächste Woche, damit die Serie weiterläuft.',
+ 'post_this_week' => 'Du hast diese Woche noch nichts gepostet. Plane einen Beitrag, damit deine Serie weiterläuft.',
+ 'schedule' => 'Beitrag planen',
+ 'share' => 'Serie teilen',
+ 'share_caption' => '{1} Ich poste seit :count Woche in Folge mit TryPost!|[0,*] Ich poste seit :count Wochen in Folge mit TryPost!',
+ 'image_weeks' => '{1} Woche|[0,*] Wochen',
+ 'image_tagline' => 'regelmäßig gepostet!',
+ ],
];
diff --git a/lang/de/posts.php b/lang/de/posts.php
index 34f8340ff..b9b624b74 100644
--- a/lang/de/posts.php
+++ b/lang/de/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Diesen Beitrag an den Anfang der Warteschlange setzen.',
'add' => 'Zur Warteschlange hinzufügen',
'add_many' => ':count zur Warteschlange hinzufügen',
- 'added' => 'Zur Warteschlange hinzugefügt|:count Beiträge zur Warteschlange hinzugefügt',
+ 'added' => '{1} Dein Beitrag wurde zur Warteschlange hinzugefügt.|[0,*] Deine :count Beiträge wurden zur Warteschlange hinzugefügt.',
+ 'moved_to_top' => 'Dein Beitrag steht jetzt ganz oben in der Warteschlange.',
'no_slots_hint' => 'Füge Veröffentlichungszeiten hinzu, um die Warteschlange zu nutzen.',
'no_slots_channels' => 'Keine Veröffentlichungszeiten: :channels',
'no_slots_tooltip' => 'Keine Veröffentlichungszeiten für :channels. Füge Zeiten hinzu, um die Warteschlange zu nutzen.',
diff --git a/lang/el/analytics.php b/lang/el/analytics.php
index 08ff913d1..afdb129e7 100644
--- a/lang/el/analytics.php
+++ b/lang/el/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric στα κανάλια μας: :value (:range) 📈',
'caption_summary_workspace' => 'Τα νούμερά μας για :range 📈 :metrics',
'caption_summary_channel' => 'Τα νούμερά μας στο :channel για :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '{1} 🔥 :days στη σειρά δημοσιεύουμε, το μεγαλύτερο σερί μας μέχρι τώρα! :posts δημοσίευση τους τελευταίους 12 μήνες.|[0,*] 🔥 :days στη σειρά δημοσιεύουμε, το μεγαλύτερο σερί μας μέχρι τώρα! :posts δημοσιεύσεις τους τελευταίους 12 μήνες.',
+ 'on_streak' => '{1} 🔥 :days στη σειρά δημοσιεύουμε. Το ρεκόρ μας είναι :best, με :posts δημοσίευση τους τελευταίους 12 μήνες.|[0,*] 🔥 :days στη σειρά δημοσιεύουμε. Το ρεκόρ μας είναι :best, με :posts δημοσιεύσεις τους τελευταίους 12 μήνες.',
+ 'no_streak' => '{1} 📅 :posts δημοσίευση τους τελευταίους 12 μήνες, με μεγαλύτερο σερί :best στη σειρά.|[0,*] 📅 :posts δημοσιεύσεις τους τελευταίους 12 μήνες, με μεγαλύτερο σερί :best στη σειρά.',
+ ],
'export_failed' => 'Η εικόνα δεν δημιουργήθηκε. Δοκιμάστε ξανά.',
'colors' => [
'violet' => 'Βιολετί',
@@ -448,4 +453,33 @@ return [
'slate' => 'Σχιστόλιθος',
],
],
+ 'posting_activity' => [
+ 'title' => 'Δραστηριότητα δημοσιεύσεων',
+ 'subtitle' => 'Τελευταίοι 12 μήνες',
+ 'current_streak' => 'Τρέχον σερί',
+ 'best_streak' => 'Μεγαλύτερο σερί',
+ 'total' => 'Δημοσιεύσεις',
+ 'days' => '{1} :count ημέρα|[0,*] :count ημέρες',
+ 'less' => 'Λιγότερο',
+ 'more' => 'Περισσότερο',
+ 'posts_on_day' => '{0} Καμία δημοσίευση|{1} :count δημοσίευση|[2,*] :count δημοσιεύσεις',
+ 'about' => [
+ 'current_streak' => 'Ημέρες στη σειρά που δημοσίευσες. Δημοσίευε τουλάχιστον μία φορά την ημέρα για να συνεχίσει το σερί.',
+ 'best_streak' => 'Οι περισσότερες ημέρες στη σειρά με δημοσίευση τους τελευταίους 12 μήνες.',
+ 'total' => 'Ό,τι δημοσίευσες τους τελευταίους 12 μήνες, μαζί με δημοσιεύσεις εκτός TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Προβολή σερί',
+ 'title' => '{1} Σερί :count εβδομάδας|[0,*] Σερί :count εβδομάδων',
+ 'top' => 'Top :percent%',
+ 'rank_tooltip' => 'Σε σύγκριση με άλλους χρήστες του TryPost',
+ 'keep_going' => 'Μπράβο! Προγραμμάτισε μια δημοσίευση για την επόμενη εβδομάδα για να συνεχίσει το σερί.',
+ 'post_this_week' => 'Δεν έχεις δημοσιεύσει ακόμα αυτή την εβδομάδα. Προγραμμάτισε μια δημοσίευση για να συνεχίσει το σερί σου.',
+ 'schedule' => 'Προγραμματισμός',
+ 'share' => 'Κοινοποίηση σερί',
+ 'share_caption' => '{1} Δημοσιεύω :count εβδομάδα στη σειρά με το TryPost!|[0,*] Δημοσιεύω :count εβδομάδες στη σειρά με το TryPost!',
+ 'image_weeks' => '{1} εβδομάδα|[0,*] εβδομάδες',
+ 'image_tagline' => 'σταθερών δημοσιεύσεων!',
+ ],
];
diff --git a/lang/el/posts.php b/lang/el/posts.php
index ca75240f9..9f3996009 100644
--- a/lang/el/posts.php
+++ b/lang/el/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Τοποθετήστε αυτή την ανάρτηση στην κορυφή της ουράς.',
'add' => 'Προσθήκη στην ουρά',
'add_many' => 'Προσθήκη :count στην ουρά',
- 'added' => 'Προστέθηκε στην ουρά|:count αναρτήσεις προστέθηκαν στην ουρά',
+ 'added' => '{1} Η δημοσίευσή σου προστέθηκε στην ουρά.|[0,*] Οι :count δημοσιεύσεις σου προστέθηκαν στην ουρά.',
+ 'moved_to_top' => 'Η δημοσίευσή σου μετακινήθηκε στην κορυφή της ουράς.',
'no_slots_hint' => 'Προσθέστε ώρες δημοσίευσης για να χρησιμοποιήσετε την ουρά.',
'no_slots_channels' => 'Χωρίς ώρες δημοσίευσης: :channels',
'no_slots_tooltip' => 'Δεν υπάρχουν ώρες δημοσίευσης για :channels. Προσθέστε ώρες για να χρησιμοποιήσετε την ουρά.',
diff --git a/lang/en/analytics.php b/lang/en/analytics.php
index fc63d2415..a386d8f7b 100644
--- a/lang/en/analytics.php
+++ b/lang/en/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric across our channels: :value (:range) 📈',
'caption_summary_workspace' => 'Our numbers for :range 📈 :metrics',
'caption_summary_channel' => 'Our numbers on :channel for :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '{1} 🔥 :days in a row posting, our longest streak yet! :posts post in the last 12 months.|[0,*] 🔥 :days in a row posting, our longest streak yet! :posts posts in the last 12 months.',
+ 'on_streak' => '{1} 🔥 :days in a row posting. Our record is :best, with :posts post in the last 12 months.|[0,*] 🔥 :days in a row posting. Our record is :best, with :posts posts in the last 12 months.',
+ 'no_streak' => '{1} 📅 :posts post in the last 12 months, and a longest streak of :best in a row.|[0,*] 📅 :posts posts in the last 12 months, and a longest streak of :best in a row.',
+ ],
'export_failed' => 'Couldn\'t create the image. Try again.',
'colors' => [
'violet' => 'Violet',
@@ -448,4 +453,33 @@ return [
'slate' => 'Slate',
],
],
+ 'posting_activity' => [
+ 'title' => 'Posting activity',
+ 'subtitle' => 'Last 12 months',
+ 'current_streak' => 'Current streak',
+ 'best_streak' => 'Longest streak',
+ 'total' => 'Posts',
+ 'days' => '{1} :count day|[0,*] :count days',
+ 'less' => 'Less',
+ 'more' => 'More',
+ 'posts_on_day' => '{0} No posts|{1} :count post|[2,*] :count posts',
+ 'about' => [
+ 'current_streak' => 'Days in a row you\'ve posted. Post at least once a day to keep it going.',
+ 'best_streak' => 'Your most days in a row with a post in the last 12 months.',
+ 'total' => 'Everything you posted in the last 12 months, including posts made outside TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'View streak',
+ 'title' => '{1} :count week streak|[0,*] :count week streak',
+ 'top' => 'Top :percent%',
+ 'rank_tooltip' => 'Compared to other TryPost users',
+ 'keep_going' => 'Great job! Schedule a post for next week to keep the streak going.',
+ 'post_this_week' => 'You haven\'t posted this week yet. Schedule a post to keep your streak going.',
+ 'schedule' => 'Schedule post',
+ 'share' => 'Share streak',
+ 'share_caption' => 'I\'ve reached a :count-week posting streak with TryPost!',
+ 'image_weeks' => '{1} week|[0,*] weeks',
+ 'image_tagline' => 'of consistent posting!',
+ ],
];
diff --git a/lang/en/posts.php b/lang/en/posts.php
index a0a5b2ad3..fbcf82c73 100644
--- a/lang/en/posts.php
+++ b/lang/en/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Put this post at the top of the queue.',
'add' => 'Add to queue',
'add_many' => 'Add :count to queue',
- 'added' => 'Added to queue|:count posts added to queue',
+ 'added' => '{1} Your post was added to the queue.|[0,*] Your :count posts were added to the queue.',
+ 'moved_to_top' => 'Your post was moved to the top of the queue.',
'no_slots_hint' => 'Add posting times to use the queue.',
'no_slots_channels' => 'No posting times: :channels',
'no_slots_tooltip' => 'No posting times for :channels. Add posting times to use the queue.',
diff --git a/lang/es/analytics.php b/lang/es/analytics.php
index fec3c232e..69e89de92 100644
--- a/lang/es/analytics.php
+++ b/lang/es/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric en nuestros canales: :value (:range) 📈',
'caption_summary_workspace' => 'Nuestros números de :range 📈 :metrics',
'caption_summary_channel' => 'Nuestros números en :channel de :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '{1} 🔥 :days publicando sin parar, ¡nuestra mejor racha hasta ahora! :posts publicación en los últimos 12 meses.|[0,*] 🔥 :days publicando sin parar, ¡nuestra mejor racha hasta ahora! :posts publicaciones en los últimos 12 meses.',
+ 'on_streak' => '{1} 🔥 :days publicando sin parar. Nuestro récord es de :best, con :posts publicación en los últimos 12 meses.|[0,*] 🔥 :days publicando sin parar. Nuestro récord es de :best, con :posts publicaciones en los últimos 12 meses.',
+ 'no_streak' => '{1} 📅 :posts publicación en los últimos 12 meses, con una racha récord de :best.|[0,*] 📅 :posts publicaciones en los últimos 12 meses, con una racha récord de :best.',
+ ],
'export_failed' => 'No se pudo crear la imagen. Inténtalo de nuevo.',
'colors' => [
'violet' => 'Violeta',
@@ -448,4 +453,33 @@ return [
'slate' => 'Pizarra',
],
],
+ 'posting_activity' => [
+ 'title' => 'Actividad de publicación',
+ 'subtitle' => 'Últimos 12 meses',
+ 'current_streak' => 'Racha actual',
+ 'best_streak' => 'Racha más larga',
+ 'total' => 'Publicaciones',
+ 'days' => '{1} :count día|[0,*] :count días',
+ 'less' => 'Menos',
+ 'more' => 'Más',
+ 'posts_on_day' => '{0} Sin publicaciones|{1} :count publicación|[2,*] :count publicaciones',
+ 'about' => [
+ 'current_streak' => 'Días seguidos en los que publicaste. Publica al menos una vez al día para mantener la racha.',
+ 'best_streak' => 'Tu mayor cantidad de días seguidos con una publicación en los últimos 12 meses.',
+ 'total' => 'Todo lo que publicaste en los últimos 12 meses, incluidas las publicaciones hechas fuera de TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Ver racha',
+ 'title' => '{1} Racha de :count semana|[0,*] Racha de :count semanas',
+ 'top' => 'Top :percent%',
+ 'rank_tooltip' => 'Comparado con otros usuarios de TryPost',
+ 'keep_going' => '¡Buen trabajo! Programa una publicación para la próxima semana y mantén la racha.',
+ 'post_this_week' => 'Aún no has publicado esta semana. Programa una publicación para mantener tu racha.',
+ 'schedule' => 'Programar publicación',
+ 'share' => 'Compartir racha',
+ 'share_caption' => '{1} ¡Llevo :count semana publicando sin parar con TryPost!|[0,*] ¡Llevo :count semanas seguidas publicando con TryPost!',
+ 'image_weeks' => '{1} semana|[0,*] semanas',
+ 'image_tagline' => '¡publicando sin parar!',
+ ],
];
diff --git a/lang/es/posts.php b/lang/es/posts.php
index cef0d686a..b5ce01156 100644
--- a/lang/es/posts.php
+++ b/lang/es/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Coloca esta publicación al principio de la cola.',
'add' => 'Añadir a la cola',
'add_many' => 'Añadir :count a la cola',
- 'added' => 'Añadida a la cola|:count publicaciones añadidas a la cola',
+ 'added' => '{1} Tu publicación se añadió a la cola.|[0,*] Tus :count publicaciones se añadieron a la cola.',
+ 'moved_to_top' => 'Tu publicación pasó al principio de la cola.',
'no_slots_hint' => 'Añade horarios de publicación para usar la cola.',
'no_slots_channels' => 'Sin horarios: :channels',
'no_slots_tooltip' => 'No hay horarios de publicación para :channels. Añade horarios para usar la cola.',
diff --git a/lang/fr/analytics.php b/lang/fr/analytics.php
index 04a551d00..3e0a0bba7 100644
--- a/lang/fr/analytics.php
+++ b/lang/fr/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric sur nos canaux : :value (:range) 📈',
'caption_summary_workspace' => 'Nos chiffres du :range 📈 :metrics',
'caption_summary_channel' => 'Nos chiffres sur :channel du :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '{1} 🔥 :days d’affilée à publier, notre meilleure série jusqu’ici ! :posts publication sur les 12 derniers mois.|[0,*] 🔥 :days d’affilée à publier, notre meilleure série jusqu’ici ! :posts publications sur les 12 derniers mois.',
+ 'on_streak' => '{1} 🔥 :days d’affilée à publier. Notre record est de :best, avec :posts publication sur les 12 derniers mois.|[0,*] 🔥 :days d’affilée à publier. Notre record est de :best, avec :posts publications sur les 12 derniers mois.',
+ 'no_streak' => '{1} 📅 :posts publication sur les 12 derniers mois, et une plus longue série de :best d’affilée.|[0,*] 📅 :posts publications sur les 12 derniers mois, et une plus longue série de :best d’affilée.',
+ ],
'export_failed' => 'Impossible de créer l’image. Réessayez.',
'colors' => [
'violet' => 'Violet',
@@ -448,4 +453,33 @@ return [
'slate' => 'Ardoise',
],
],
+ 'posting_activity' => [
+ 'title' => 'Activité de publication',
+ 'subtitle' => '12 derniers mois',
+ 'current_streak' => 'Série en cours',
+ 'best_streak' => 'Plus longue série',
+ 'total' => 'Publications',
+ 'days' => '{1} :count jour|[0,*] :count jours',
+ 'less' => 'Moins',
+ 'more' => 'Plus',
+ 'posts_on_day' => '{0} Aucune publication|{1} :count publication|[2,*] :count publications',
+ 'about' => [
+ 'current_streak' => 'Jours d’affilée où vous avez publié. Publiez au moins une fois par jour pour continuer la série.',
+ 'best_streak' => 'Votre plus grand nombre de jours d’affilée avec une publication sur les 12 derniers mois.',
+ 'total' => 'Tout ce que vous avez publié ces 12 derniers mois, y compris en dehors de TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Voir la série',
+ 'title' => '{1} Série de :count semaine|[0,*] Série de :count semaines',
+ 'top' => 'Top :percent %',
+ 'rank_tooltip' => 'Par rapport aux autres utilisateurs de TryPost',
+ 'keep_going' => 'Bravo ! Programmez une publication pour la semaine prochaine pour garder la série.',
+ 'post_this_week' => 'Vous n\'avez pas encore publié cette semaine. Programmez une publication pour garder votre série.',
+ 'schedule' => 'Programmer',
+ 'share' => 'Partager la série',
+ 'share_caption' => '{1} J\'ai publié :count semaine d\'affilée avec TryPost !|[0,*] J\'ai publié :count semaines d\'affilée avec TryPost !',
+ 'image_weeks' => '{1} semaine|[0,*] semaines',
+ 'image_tagline' => 'de publication régulière !',
+ ],
];
diff --git a/lang/fr/posts.php b/lang/fr/posts.php
index 1891f413f..b89b6a646 100644
--- a/lang/fr/posts.php
+++ b/lang/fr/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Placer ce post en tête de la file d\'attente.',
'add' => 'Ajouter à la file d\'attente',
'add_many' => 'Ajouter :count à la file d\'attente',
- 'added' => 'Ajouté à la file d\'attente|:count posts ajoutés à la file d\'attente',
+ 'added' => '{1} Votre publication a été ajoutée à la file d\'attente.|[0,*] Vos :count publications ont été ajoutées à la file d\'attente.',
+ 'moved_to_top' => 'Votre publication est passée en tête de la file d\'attente.',
'no_slots_hint' => 'Ajoutez des horaires de publication pour utiliser la file d\'attente.',
'no_slots_channels' => 'Aucun horaire : :channels',
'no_slots_tooltip' => 'Aucun horaire de publication pour :channels. Ajoutez des horaires pour utiliser la file.',
diff --git a/lang/id/analytics.php b/lang/id/analytics.php
index 1e6507b36..c5891eda3 100644
--- a/lang/id/analytics.php
+++ b/lang/id/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric di semua channel kami: :value (:range) 📈',
'caption_summary_workspace' => 'Angka kami untuk :range 📈 :metrics',
'caption_summary_channel' => 'Angka kami di :channel untuk :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 :days berturut-turut memposting, rangkaian terpanjang kami sejauh ini! :posts postingan dalam 12 bulan terakhir.',
+ 'on_streak' => '🔥 :days berturut-turut memposting. Rekor kami :best, dengan :posts postingan dalam 12 bulan terakhir.',
+ 'no_streak' => '📅 :posts postingan dalam 12 bulan terakhir, dengan rangkaian terpanjang :best berturut-turut.',
+ ],
'export_failed' => 'Gambar gagal dibuat. Coba lagi.',
'colors' => [
'violet' => 'Violet',
@@ -448,4 +453,33 @@ return [
'slate' => 'Abu kebiruan',
],
],
+ 'posting_activity' => [
+ 'title' => 'Aktivitas posting',
+ 'subtitle' => '12 bulan terakhir',
+ 'current_streak' => 'Rangkaian saat ini',
+ 'best_streak' => 'Rangkaian terpanjang',
+ 'total' => 'Postingan',
+ 'days' => ':count hari',
+ 'less' => 'Lebih sedikit',
+ 'more' => 'Lebih banyak',
+ 'posts_on_day' => '{0} Tidak ada postingan|[1,*] :count postingan',
+ 'about' => [
+ 'current_streak' => 'Hari berturut-turut kamu memposting. Posting setidaknya sekali sehari agar rangkaiannya berlanjut.',
+ 'best_streak' => 'Hari berturut-turut terbanyak kamu memposting dalam 12 bulan terakhir.',
+ 'total' => 'Semua yang kamu posting dalam 12 bulan terakhir, termasuk postingan di luar TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Lihat rangkaian',
+ 'title' => 'Rangkaian :count minggu',
+ 'top' => 'Top :percent%',
+ 'rank_tooltip' => 'Dibandingkan dengan pengguna TryPost lainnya',
+ 'keep_going' => 'Kerja bagus! Jadwalkan postingan untuk minggu depan agar rangkaiannya berlanjut.',
+ 'post_this_week' => 'Kamu belum memposting minggu ini. Jadwalkan postingan agar rangkaianmu berlanjut.',
+ 'schedule' => 'Jadwalkan postingan',
+ 'share' => 'Bagikan rangkaian',
+ 'share_caption' => 'Aku sudah :count minggu berturut-turut memposting dengan TryPost!',
+ 'image_weeks' => 'minggu',
+ 'image_tagline' => 'posting secara konsisten!',
+ ],
];
diff --git a/lang/id/posts.php b/lang/id/posts.php
index 3c1204d29..ac7324884 100644
--- a/lang/id/posts.php
+++ b/lang/id/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Taruh postingan ini di urutan teratas antrean.',
'add' => 'Tambahkan ke antrean',
'add_many' => 'Tambahkan :count ke antrean',
- 'added' => 'Ditambahkan ke antrean|:count postingan ditambahkan ke antrean',
+ 'added' => '{1} Postinganmu sudah ditambahkan ke antrean.|[0,*] :count postinganmu sudah ditambahkan ke antrean.',
+ 'moved_to_top' => 'Postinganmu dipindahkan ke urutan teratas antrean.',
'no_slots_hint' => 'Tambahkan waktu posting untuk memakai antrean.',
'no_slots_channels' => 'Belum ada waktu posting: :channels',
'no_slots_tooltip' => 'Belum ada waktu posting untuk :channels. Tambahkan waktu posting untuk memakai antrean.',
diff --git a/lang/it/analytics.php b/lang/it/analytics.php
index 2778310e4..383e2cf49 100644
--- a/lang/it/analytics.php
+++ b/lang/it/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric sui nostri canali: :value (:range) 📈',
'caption_summary_workspace' => 'I nostri numeri del :range 📈 :metrics',
'caption_summary_channel' => 'I nostri numeri su :channel del :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '{1} 🔥 :days di fila a pubblicare, la nostra serie più lunga finora! :posts post negli ultimi 12 mesi.|[0,*] 🔥 :days di fila a pubblicare, la nostra serie più lunga finora! :posts post negli ultimi 12 mesi.',
+ 'on_streak' => '{1} 🔥 :days di fila a pubblicare. Il nostro record è di :best, con :posts post negli ultimi 12 mesi.|[0,*] 🔥 :days di fila a pubblicare. Il nostro record è di :best, con :posts post negli ultimi 12 mesi.',
+ 'no_streak' => '{1} 📅 :posts post negli ultimi 12 mesi, con una serie record di :best di fila.|[0,*] 📅 :posts post negli ultimi 12 mesi, con una serie record di :best di fila.',
+ ],
'export_failed' => 'Impossibile creare l’immagine. Riprova.',
'colors' => [
'violet' => 'Viola',
@@ -448,4 +453,33 @@ return [
'slate' => 'Ardesia',
],
],
+ 'posting_activity' => [
+ 'title' => 'Attività di pubblicazione',
+ 'subtitle' => 'Ultimi 12 mesi',
+ 'current_streak' => 'Serie attuale',
+ 'best_streak' => 'Serie più lunga',
+ 'total' => 'Post',
+ 'days' => '{1} :count giorno|[0,*] :count giorni',
+ 'less' => 'Meno',
+ 'more' => 'Più',
+ 'posts_on_day' => '{0} Nessun post|{1} :count post|[2,*] :count post',
+ 'about' => [
+ 'current_streak' => 'Giorni di fila in cui hai pubblicato. Pubblica almeno una volta al giorno per non interrompere la serie.',
+ 'best_streak' => 'Il numero più alto di giorni di fila con un post negli ultimi 12 mesi.',
+ 'total' => 'Tutto ciò che hai pubblicato negli ultimi 12 mesi, compresi i post fatti fuori da TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Vedi serie',
+ 'title' => '{1} Serie di :count settimana|[0,*] Serie di :count settimane',
+ 'top' => 'Top :percent%',
+ 'rank_tooltip' => 'Rispetto agli altri utenti di TryPost',
+ 'keep_going' => 'Ottimo lavoro! Programma un post per la prossima settimana per mantenere la serie.',
+ 'post_this_week' => 'Non hai ancora pubblicato questa settimana. Programma un post per mantenere la serie.',
+ 'schedule' => 'Programma post',
+ 'share' => 'Condividi serie',
+ 'share_caption' => '{1} Pubblico da :count settimana di fila con TryPost!|[0,*] Pubblico da :count settimane di fila con TryPost!',
+ 'image_weeks' => '{1} settimana|[0,*] settimane',
+ 'image_tagline' => 'di pubblicazioni costanti!',
+ ],
];
diff --git a/lang/it/posts.php b/lang/it/posts.php
index 10333e408..b095f3101 100644
--- a/lang/it/posts.php
+++ b/lang/it/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Metti questo post in cima alla coda.',
'add' => 'Aggiungi alla coda',
'add_many' => 'Aggiungi :count alla coda',
- 'added' => 'Aggiunto alla coda|:count post aggiunti alla coda',
+ 'added' => '{1} Il tuo post è stato aggiunto alla coda.|[0,*] I tuoi :count post sono stati aggiunti alla coda.',
+ 'moved_to_top' => 'Il tuo post è stato spostato in cima alla coda.',
'no_slots_hint' => 'Aggiungi orari di pubblicazione per usare la coda.',
'no_slots_channels' => 'Nessun orario: :channels',
'no_slots_tooltip' => 'Nessun orario di pubblicazione per :channels. Aggiungi orari per usare la coda.',
diff --git a/lang/ja/analytics.php b/lang/ja/analytics.php
index e36b289a7..9894810cf 100644
--- a/lang/ja/analytics.php
+++ b/lang/ja/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => '全チャンネルの:metric: :value (:range) 📈',
'caption_summary_workspace' => ':rangeの数字 📈 :metrics',
'caption_summary_channel' => ':channelの:rangeの数字 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 :days連続で投稿中、これまでで最長の記録です!過去12か月の投稿は:posts件。',
+ 'on_streak' => '🔥 :days連続で投稿中。最長記録は:bestで、過去12か月の投稿は:posts件です。',
+ 'no_streak' => '📅 過去12か月の投稿は:posts件、最長連続記録は:bestです。',
+ ],
'export_failed' => '画像を作成できませんでした。もう一度お試しください。',
'colors' => [
'violet' => 'バイオレット',
@@ -448,4 +453,33 @@ return [
'slate' => 'スレート',
],
],
+ 'posting_activity' => [
+ 'title' => '投稿アクティビティ',
+ 'subtitle' => '過去12か月',
+ 'current_streak' => '現在の連続記録',
+ 'best_streak' => '最長連続記録',
+ 'total' => '投稿',
+ 'days' => ':count日',
+ 'less' => '少',
+ 'more' => '多',
+ 'posts_on_day' => '{0} 投稿なし|[1,*] :count件の投稿',
+ 'about' => [
+ 'current_streak' => '連続で投稿した日数です。記録を続けるには毎日1回以上投稿しましょう。',
+ 'best_streak' => '過去12か月で、連続して投稿した最長の日数です。',
+ 'total' => '過去12か月の投稿すべてです。TryPost 以外で投稿したものも含みます。',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => '連続記録を見る',
+ 'title' => ':count週連続',
+ 'top' => '上位:percent%',
+ 'rank_tooltip' => '他の TryPost ユーザーとの比較',
+ 'keep_going' => 'すばらしい!来週の投稿を予約して記録を続けましょう。',
+ 'post_this_week' => '今週はまだ投稿していません。投稿を予約して記録を続けましょう。',
+ 'schedule' => '投稿を予約',
+ 'share' => '記録をシェア',
+ 'share_caption' => 'TryPostで:count週連続で投稿しています!',
+ 'image_weeks' => '週',
+ 'image_tagline' => '継続して投稿中!',
+ ],
];
diff --git a/lang/ja/posts.php b/lang/ja/posts.php
index 410f3995a..d57410823 100644
--- a/lang/ja/posts.php
+++ b/lang/ja/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'この投稿をキューの先頭に置きます。',
'add' => 'キューに追加',
'add_many' => ':count件をキューに追加',
- 'added' => 'キューに追加しました|:count件の投稿をキューに追加しました',
+ 'added' => '{1} 投稿をキューに追加しました。|[0,*] :count件の投稿をキューに追加しました。',
+ 'moved_to_top' => '投稿をキューの先頭に移動しました。',
'no_slots_hint' => 'キューを使うには投稿時間を追加してください。',
'no_slots_channels' => '投稿時間なし::channels',
'no_slots_tooltip' => ':channels には投稿時間がありません。キューを使うには投稿時間を追加してください。',
diff --git a/lang/ko/analytics.php b/lang/ko/analytics.php
index 143aeb334..3cb0b2975 100644
--- a/lang/ko/analytics.php
+++ b/lang/ko/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => '전체 채널 :metric: :value (:range) 📈',
'caption_summary_workspace' => ':range 우리 숫자 📈 :metrics',
'caption_summary_channel' => ':channel의 :range 숫자 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 :days 연속 게시 중, 지금까지 가장 긴 기록이에요! 최근 12개월 동안 게시물 :posts개.',
+ 'on_streak' => '🔥 :days 연속 게시 중. 최고 기록은 :best이고, 최근 12개월 동안 게시물 :posts개를 올렸어요.',
+ 'no_streak' => '📅 최근 12개월 동안 게시물 :posts개, 최장 연속 기록은 :best이에요.',
+ ],
'export_failed' => '이미지를 만들지 못했어요. 다시 시도하세요.',
'colors' => [
'violet' => '바이올렛',
@@ -448,4 +453,33 @@ return [
'slate' => '슬레이트',
],
],
+ 'posting_activity' => [
+ 'title' => '게시 활동',
+ 'subtitle' => '최근 12개월',
+ 'current_streak' => '현재 연속 기록',
+ 'best_streak' => '최장 연속 기록',
+ 'total' => '게시물',
+ 'days' => ':count일',
+ 'less' => '적음',
+ 'more' => '많음',
+ 'posts_on_day' => '{0} 게시물 없음|[1,*] 게시물 :count개',
+ 'about' => [
+ 'current_streak' => '연속으로 게시한 일수입니다. 기록을 이어가려면 매일 한 번 이상 게시하세요.',
+ 'best_streak' => '최근 12개월 동안 연속으로 게시한 가장 긴 일수입니다.',
+ 'total' => '최근 12개월 동안 게시한 모든 게시물입니다. TryPost 밖에서 게시한 것도 포함됩니다.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => '연속 기록 보기',
+ 'title' => ':count주 연속',
+ 'top' => '상위 :percent%',
+ 'rank_tooltip' => '다른 TryPost 사용자와 비교한 순위',
+ 'keep_going' => '잘하고 있어요! 다음 주 게시물을 예약해 연속 기록을 이어가세요.',
+ 'post_this_week' => '이번 주에는 아직 게시하지 않았어요. 게시물을 예약해 연속 기록을 이어가세요.',
+ 'schedule' => '게시물 예약',
+ 'share' => '기록 공유',
+ 'share_caption' => 'TryPost로 :count주 연속 게시 중이에요!',
+ 'image_weeks' => '주',
+ 'image_tagline' => '꾸준히 게시 중!',
+ ],
];
diff --git a/lang/ko/posts.php b/lang/ko/posts.php
index a77ae82b4..1bc627598 100644
--- a/lang/ko/posts.php
+++ b/lang/ko/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => '이 게시물을 대기열 맨 앞에 둡니다.',
'add' => '대기열에 추가',
'add_many' => '대기열에 :count개 추가',
- 'added' => '대기열에 추가됨|게시물 :count개가 대기열에 추가됨',
+ 'added' => '{1} 게시물이 대기열에 추가되었습니다.|[0,*] 게시물 :count개가 대기열에 추가되었습니다.',
+ 'moved_to_top' => '게시물이 대기열 맨 위로 이동되었습니다.',
'no_slots_hint' => '대기열을 사용하려면 게시 시간을 추가하세요.',
'no_slots_channels' => '게시 시간 없음: :channels',
'no_slots_tooltip' => ':channels에 게시 시간이 없습니다. 대기열을 사용하려면 게시 시간을 추가하세요.',
diff --git a/lang/nl/analytics.php b/lang/nl/analytics.php
index df949e005..907f79d97 100644
--- a/lang/nl/analytics.php
+++ b/lang/nl/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric op onze kanalen: :value (:range) 📈',
'caption_summary_workspace' => 'Onze cijfers voor :range 📈 :metrics',
'caption_summary_channel' => 'Onze cijfers op :channel voor :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '{1} 🔥 :days op rij gepost, onze langste reeks tot nu toe! :posts bericht in de afgelopen 12 maanden.|[0,*] 🔥 :days op rij gepost, onze langste reeks tot nu toe! :posts berichten in de afgelopen 12 maanden.',
+ 'on_streak' => '{1} 🔥 :days op rij gepost. Ons record is :best, met :posts bericht in de afgelopen 12 maanden.|[0,*] 🔥 :days op rij gepost. Ons record is :best, met :posts berichten in de afgelopen 12 maanden.',
+ 'no_streak' => '{1} 📅 :posts bericht in de afgelopen 12 maanden, met een langste reeks van :best op rij.|[0,*] 📅 :posts berichten in de afgelopen 12 maanden, met een langste reeks van :best op rij.',
+ ],
'export_failed' => 'Kan de afbeelding niet maken. Probeer het opnieuw.',
'colors' => [
'violet' => 'Violet',
@@ -448,4 +453,33 @@ return [
'slate' => 'Leisteen',
],
],
+ 'posting_activity' => [
+ 'title' => 'Plaatsingsactiviteit',
+ 'subtitle' => 'Afgelopen 12 maanden',
+ 'current_streak' => 'Huidige reeks',
+ 'best_streak' => 'Langste reeks',
+ 'total' => 'Berichten',
+ 'days' => '{1} :count dag|[0,*] :count dagen',
+ 'less' => 'Minder',
+ 'more' => 'Meer',
+ 'posts_on_day' => '{0} Geen berichten|{1} :count bericht|[2,*] :count berichten',
+ 'about' => [
+ 'current_streak' => 'Dagen op rij waarop je hebt gepost. Post minstens één keer per dag om de reeks vast te houden.',
+ 'best_streak' => 'Je meeste dagen op rij met een bericht in de afgelopen 12 maanden.',
+ 'total' => 'Alles wat je de afgelopen 12 maanden hebt gepost, ook buiten TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Reeks bekijken',
+ 'title' => '{1} :count week op rij|[0,*] :count weken op rij',
+ 'top' => 'Top :percent%',
+ 'rank_tooltip' => 'Vergeleken met andere TryPost-gebruikers',
+ 'keep_going' => 'Goed bezig! Plan een bericht voor volgende week om de reeks vast te houden.',
+ 'post_this_week' => 'Je hebt deze week nog niet gepost. Plan een bericht om je reeks vast te houden.',
+ 'schedule' => 'Bericht plannen',
+ 'share' => 'Reeks delen',
+ 'share_caption' => '{1} Ik post al :count week op rij met TryPost!|[0,*] Ik post al :count weken op rij met TryPost!',
+ 'image_weeks' => '{1} week|[0,*] weken',
+ 'image_tagline' => 'consequent gepost!',
+ ],
];
diff --git a/lang/nl/posts.php b/lang/nl/posts.php
index d44eb6dc6..021e2fd52 100644
--- a/lang/nl/posts.php
+++ b/lang/nl/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Zet dit bericht bovenaan de wachtrij.',
'add' => 'Toevoegen aan wachtrij',
'add_many' => ':count toevoegen aan wachtrij',
- 'added' => 'Toegevoegd aan wachtrij|:count berichten toegevoegd aan wachtrij',
+ 'added' => '{1} Je bericht is aan de wachtrij toegevoegd.|[0,*] Je :count berichten zijn aan de wachtrij toegevoegd.',
+ 'moved_to_top' => 'Je bericht staat nu bovenaan de wachtrij.',
'no_slots_hint' => 'Voeg publicatietijden toe om de wachtrij te gebruiken.',
'no_slots_channels' => 'Geen publicatietijden: :channels',
'no_slots_tooltip' => 'Geen publicatietijden voor :channels. Voeg tijden toe om de wachtrij te gebruiken.',
diff --git a/lang/pl/analytics.php b/lang/pl/analytics.php
index 940cab1d9..1632055cb 100644
--- a/lang/pl/analytics.php
+++ b/lang/pl/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric na naszych kanałach: :value (:range) 📈',
'caption_summary_workspace' => 'Nasze liczby za :range 📈 :metrics',
'caption_summary_channel' => 'Nasze liczby na :channel za :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 :days z rzędu publikujemy, to nasza najdłuższa seria! Posty z ostatnich 12 miesięcy: :posts.',
+ 'on_streak' => '🔥 :days z rzędu publikujemy. Nasz rekord to :best. Posty z ostatnich 12 miesięcy: :posts.',
+ 'no_streak' => '📅 Posty z ostatnich 12 miesięcy: :posts. Najdłuższa seria: :best z rzędu.',
+ ],
'export_failed' => 'Nie udało się utworzyć obrazu. Spróbuj ponownie.',
'colors' => [
'violet' => 'Fioletowy',
@@ -448,4 +453,33 @@ return [
'slate' => 'Łupkowy',
],
],
+ 'posting_activity' => [
+ 'title' => 'Aktywność publikowania',
+ 'subtitle' => 'Ostatnie 12 miesięcy',
+ 'current_streak' => 'Obecna seria',
+ 'best_streak' => 'Najdłuższa seria',
+ 'total' => 'Posty',
+ 'days' => '{1} :count dzień|[0,*] :count dni',
+ 'less' => 'Mniej',
+ 'more' => 'Więcej',
+ 'posts_on_day' => '{0} Brak postów|[1,*] Posty: :count',
+ 'about' => [
+ 'current_streak' => 'Kolejne dni z publikacją. Publikuj co najmniej raz dziennie, żeby utrzymać serię.',
+ 'best_streak' => 'Najwięcej kolejnych dni z publikacją w ostatnich 12 miesiącach.',
+ 'total' => 'Wszystkie posty z ostatnich 12 miesięcy, także te opublikowane poza TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Zobacz serię',
+ 'title' => 'Tygodnie z rzędu: :count',
+ 'top' => 'Top :percent%',
+ 'rank_tooltip' => 'W porównaniu z innymi użytkownikami TryPost',
+ 'keep_going' => 'Świetnie! Zaplanuj post na przyszły tydzień, żeby utrzymać serię.',
+ 'post_this_week' => 'W tym tygodniu nie ma jeszcze posta. Zaplanuj post, żeby utrzymać serię.',
+ 'schedule' => 'Zaplanuj post',
+ 'share' => 'Udostępnij serię',
+ 'share_caption' => 'Publikuję z TryPost już od tygodni: :count z rzędu!',
+ 'image_weeks' => 'tyg.',
+ 'image_tagline' => 'regularnego publikowania!',
+ ],
];
diff --git a/lang/pl/posts.php b/lang/pl/posts.php
index 902bbb392..5318fbbfe 100644
--- a/lang/pl/posts.php
+++ b/lang/pl/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Umieść ten post na początku kolejki.',
'add' => 'Dodaj do kolejki',
'add_many' => 'Dodaj do kolejki: :count',
- 'added' => '{1} Dodano do kolejki|[0,*] Dodano do kolejki: :count',
+ 'added' => '{1} Twój post został dodany do kolejki.|[0,*] Posty dodane do kolejki: :count.',
+ 'moved_to_top' => 'Twój post trafił na początek kolejki.',
'no_slots_hint' => 'Dodaj godziny publikacji, aby korzystać z kolejki.',
'no_slots_channels' => 'Brak godzin publikacji: :channels',
'no_slots_tooltip' => 'Brak godzin publikacji dla :channels. Dodaj godziny, aby korzystać z kolejki.',
diff --git a/lang/pt-BR/analytics.php b/lang/pt-BR/analytics.php
index daeb1ae6c..99deb6e8b 100644
--- a/lang/pt-BR/analytics.php
+++ b/lang/pt-BR/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric nos nossos canais: :value (:range) 📈',
'caption_summary_workspace' => 'Nossos números de :range 📈 :metrics',
'caption_summary_channel' => 'Nossos números em :channel de :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '{1} 🔥 :days postando sem parar, nossa maior sequência até agora! Foi :posts post nos últimos 12 meses.|[0,*] 🔥 :days postando sem parar, nossa maior sequência até agora! Foram :posts posts nos últimos 12 meses.',
+ 'on_streak' => '{1} 🔥 :days postando sem parar. Nosso recorde é de :best, com :posts post nos últimos 12 meses.|[0,*] 🔥 :days postando sem parar. Nosso recorde é de :best, com :posts posts nos últimos 12 meses.',
+ 'no_streak' => '{1} 📅 :posts post nos últimos 12 meses, com um recorde de :best em sequência.|[0,*] 📅 :posts posts nos últimos 12 meses, com um recorde de :best em sequência.',
+ ],
'export_failed' => 'Não foi possível criar a imagem. Tente de novo.',
'colors' => [
'violet' => 'Violeta',
@@ -448,4 +453,33 @@ return [
'slate' => 'Ardósia',
],
],
+ 'posting_activity' => [
+ 'title' => 'Atividade de publicação',
+ 'subtitle' => 'Últimos 12 meses',
+ 'current_streak' => 'Sequência atual',
+ 'best_streak' => 'Maior sequência',
+ 'total' => 'Posts',
+ 'days' => '{1} :count dia|[0,*] :count dias',
+ 'less' => 'Menos',
+ 'more' => 'Mais',
+ 'posts_on_day' => '{0} Nenhum post|{1} :count post|[2,*] :count posts',
+ 'about' => [
+ 'current_streak' => 'Dias seguidos em que você postou. Poste pelo menos uma vez por dia para manter a sequência.',
+ 'best_streak' => 'Seu maior número de dias seguidos com post nos últimos 12 meses.',
+ 'total' => 'Tudo o que você postou nos últimos 12 meses, incluindo posts feitos fora do TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Ver sequência',
+ 'title' => '{1} Sequência de :count semana|[0,*] Sequência de :count semanas',
+ 'top' => 'Top :percent%',
+ 'rank_tooltip' => 'Comparado com outros usuários do TryPost',
+ 'keep_going' => 'Mandou bem! Agende um post para a próxima semana e mantenha a sequência.',
+ 'post_this_week' => 'Você ainda não postou esta semana. Agende um post para manter sua sequência.',
+ 'schedule' => 'Agendar post',
+ 'share' => 'Compartilhar sequência',
+ 'share_caption' => '{1} Cheguei a :count semana seguida postando com o TryPost!|[0,*] Cheguei a :count semanas seguidas postando com o TryPost!',
+ 'image_weeks' => '{1} semana|[0,*] semanas',
+ 'image_tagline' => 'postando sem parar!',
+ ],
];
diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php
index c509b4948..57fc14cbf 100644
--- a/lang/pt-BR/posts.php
+++ b/lang/pt-BR/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Coloca este post no topo da fila.',
'add' => 'Adicionar à fila',
'add_many' => 'Adicionar :count à fila',
- 'added' => 'Adicionado à fila|:count posts adicionados à fila',
+ 'added' => '{1} Seu post foi adicionado à fila.|[0,*] Seus :count posts foram adicionados à fila.',
+ 'moved_to_top' => 'Seu post foi para o topo da fila.',
'no_slots_hint' => 'Adicione horários de postagem para usar a fila.',
'no_slots_channels' => 'Sem horários: :channels',
'no_slots_tooltip' => 'Sem horários de publicação para :channels. Adicione horários para usar a fila.',
diff --git a/lang/ru/analytics.php b/lang/ru/analytics.php
index f54b501fd..0c2ab1c91 100644
--- a/lang/ru/analytics.php
+++ b/lang/ru/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric в наших каналах: :value (:range) 📈',
'caption_summary_workspace' => 'Наши цифры за :range 📈 :metrics',
'caption_summary_channel' => 'Наши цифры в :channel за :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 Публикуем :days подряд — это наш лучший результат! Публикаций за последние 12 месяцев: :posts.',
+ 'on_streak' => '🔥 Публикуем :days подряд. Наш рекорд — :best. Публикаций за последние 12 месяцев: :posts.',
+ 'no_streak' => '📅 Публикаций за последние 12 месяцев: :posts. Самая длинная серия — :best подряд.',
+ ],
'export_failed' => 'Не удалось создать изображение. Попробуйте ещё раз.',
'colors' => [
'violet' => 'Фиолетовый',
@@ -448,4 +453,33 @@ return [
'slate' => 'Сланцевый',
],
],
+ 'posting_activity' => [
+ 'title' => 'Активность публикаций',
+ 'subtitle' => 'Последние 12 месяцев',
+ 'current_streak' => 'Текущая серия',
+ 'best_streak' => 'Самая длинная серия',
+ 'total' => 'Публикации',
+ 'days' => ':count дн.',
+ 'less' => 'Меньше',
+ 'more' => 'Больше',
+ 'posts_on_day' => '{0} Нет публикаций|[1,*] Публикаций: :count',
+ 'about' => [
+ 'current_streak' => 'Дни подряд с публикациями. Публикуйте хотя бы раз в день, чтобы не прервать серию.',
+ 'best_streak' => 'Больше всего дней подряд с публикациями за последние 12 месяцев.',
+ 'total' => 'Все публикации за последние 12 месяцев, включая сделанные не через TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Посмотреть серию',
+ 'title' => 'Недель подряд: :count',
+ 'top' => 'Топ :percent%',
+ 'rank_tooltip' => 'По сравнению с другими пользователями TryPost',
+ 'keep_going' => 'Отлично! Запланируйте публикацию на следующую неделю, чтобы не прервать серию.',
+ 'post_this_week' => 'На этой неделе публикаций ещё не было. Запланируйте публикацию, чтобы не прервать серию.',
+ 'schedule' => 'Запланировать',
+ 'share' => 'Поделиться серией',
+ 'share_caption' => 'Публикую с TryPost уже недель подряд: :count!',
+ 'image_weeks' => 'нед.',
+ 'image_tagline' => 'регулярных публикаций!',
+ ],
];
diff --git a/lang/ru/posts.php b/lang/ru/posts.php
index 473430599..4e9875d9f 100644
--- a/lang/ru/posts.php
+++ b/lang/ru/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Поставить этот пост в начало очереди.',
'add' => 'Добавить в очередь',
'add_many' => 'Добавить в очередь: :count',
- 'added' => '{1} Добавлено в очередь|[0,*] Добавлено в очередь: :count',
+ 'added' => '{1} Ваша публикация добавлена в очередь.|[0,*] Публикаций добавлено в очередь: :count.',
+ 'moved_to_top' => 'Ваша публикация перемещена в начало очереди.',
'no_slots_hint' => 'Добавьте время публикации, чтобы использовать очередь.',
'no_slots_channels' => 'Нет времени публикации: :channels',
'no_slots_tooltip' => 'Нет времени публикации для :channels. Добавьте время, чтобы использовать очередь.',
diff --git a/lang/tr/analytics.php b/lang/tr/analytics.php
index 3e9f6d84b..f4f1101a7 100644
--- a/lang/tr/analytics.php
+++ b/lang/tr/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => 'Kanallarımızda :metric: :value (:range) 📈',
'caption_summary_workspace' => ':range rakamlarımız 📈 :metrics',
'caption_summary_channel' => ':channel üzerinde :range rakamlarımız 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 :days üst üste paylaşım yaptık, şimdiye kadarki en uzun serimiz! Son 12 ayda :posts gönderi.',
+ 'on_streak' => '🔥 :days üst üste paylaşım yaptık. Rekorumuz :best, son 12 ayda :posts gönderi.',
+ 'no_streak' => '📅 Son 12 ayda :posts gönderi, en uzun serimiz :best üst üste.',
+ ],
'export_failed' => 'Görsel oluşturulamadı. Tekrar dene.',
'colors' => [
'violet' => 'Menekşe',
@@ -448,4 +453,33 @@ return [
'slate' => 'Arduvaz',
],
],
+ 'posting_activity' => [
+ 'title' => 'Paylaşım etkinliği',
+ 'subtitle' => 'Son 12 ay',
+ 'current_streak' => 'Mevcut seri',
+ 'best_streak' => 'En uzun seri',
+ 'total' => 'Gönderiler',
+ 'days' => ':count gün',
+ 'less' => 'Daha az',
+ 'more' => 'Daha fazla',
+ 'posts_on_day' => '{0} Gönderi yok|[1,*] :count gönderi',
+ 'about' => [
+ 'current_streak' => 'Üst üste paylaşım yaptığın günler. Seriyi sürdürmek için her gün en az bir kez paylaş.',
+ 'best_streak' => 'Son 12 ayda üst üste paylaşım yaptığın en fazla gün sayısı.',
+ 'total' => 'Son 12 ayda paylaştığın her şey, TryPost dışında paylaştıkların da dahil.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Seriyi gör',
+ 'title' => ':count haftalık seri',
+ 'top' => 'En iyi %:percent',
+ 'rank_tooltip' => 'Diğer TryPost kullanıcılarıyla karşılaştırıldığında',
+ 'keep_going' => 'Harika! Serinin devam etmesi için gelecek haftaya bir gönderi planla.',
+ 'post_this_week' => 'Bu hafta henüz paylaşım yapmadın. Serini sürdürmek için bir gönderi planla.',
+ 'schedule' => 'Gönderi planla',
+ 'share' => 'Seriyi paylaş',
+ 'share_caption' => 'TryPost ile :count haftadır üst üste paylaşım yapıyorum!',
+ 'image_weeks' => 'hafta',
+ 'image_tagline' => 'düzenli paylaşım!',
+ ],
];
diff --git a/lang/tr/posts.php b/lang/tr/posts.php
index df4fee9ed..aed341b7a 100644
--- a/lang/tr/posts.php
+++ b/lang/tr/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Bu gönderiyi kuyruğun en başına koy.',
'add' => 'Kuyruğa ekle',
'add_many' => ':count gönderiyi kuyruğa ekle',
- 'added' => 'Kuyruğa eklendi|:count gönderi kuyruğa eklendi',
+ 'added' => '{1} Gönderin kuyruğa eklendi.|[0,*] :count gönderin kuyruğa eklendi.',
+ 'moved_to_top' => 'Gönderin kuyruğun en üstüne taşındı.',
'no_slots_hint' => 'Kuyruğu kullanmak için paylaşım saatleri ekleyin.',
'no_slots_channels' => 'Paylaşım saati yok: :channels',
'no_slots_tooltip' => ':channels için paylaşım saati yok. Kuyruğu kullanmak için saat ekleyin.',
diff --git a/lang/uk/analytics.php b/lang/uk/analytics.php
index 3fe554be8..54f742210 100644
--- a/lang/uk/analytics.php
+++ b/lang/uk/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => ':metric у наших каналах: :value (:range) 📈',
'caption_summary_workspace' => 'Наші цифри за :range 📈 :metrics',
'caption_summary_channel' => 'Наші цифри в :channel за :range 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 Публікуємо :days поспіль — це наш найкращий результат! Дописів за останні 12 місяців: :posts.',
+ 'on_streak' => '🔥 Публікуємо :days поспіль. Наш рекорд — :best. Дописів за останні 12 місяців: :posts.',
+ 'no_streak' => '📅 Дописів за останні 12 місяців: :posts. Найдовша серія — :best поспіль.',
+ ],
'export_failed' => 'Не вдалося створити зображення. Спробуйте ще раз.',
'colors' => [
'violet' => 'Фіолетовий',
@@ -448,4 +453,33 @@ return [
'slate' => 'Сланцевий',
],
],
+ 'posting_activity' => [
+ 'title' => 'Активність дописів',
+ 'subtitle' => 'Останні 12 місяців',
+ 'current_streak' => 'Поточна серія',
+ 'best_streak' => 'Найдовша серія',
+ 'total' => 'Дописи',
+ 'days' => ':count дн.',
+ 'less' => 'Менше',
+ 'more' => 'Більше',
+ 'posts_on_day' => '{0} Немає дописів|[1,*] Дописів: :count',
+ 'about' => [
+ 'current_streak' => 'Дні поспіль із дописами. Публікуйте хоча б раз на день, щоб не перервати серію.',
+ 'best_streak' => 'Найбільше днів поспіль із дописами за останні 12 місяців.',
+ 'total' => 'Усі дописи за останні 12 місяців, зокрема ті, що опубліковані не через TryPost.',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => 'Переглянути серію',
+ 'title' => 'Тижнів поспіль: :count',
+ 'top' => 'Топ :percent%',
+ 'rank_tooltip' => 'Порівняно з іншими користувачами TryPost',
+ 'keep_going' => 'Чудово! Заплануйте допис на наступний тиждень, щоб не перервати серію.',
+ 'post_this_week' => 'Цього тижня дописів ще не було. Заплануйте допис, щоб не перервати серію.',
+ 'schedule' => 'Запланувати',
+ 'share' => 'Поділитися серією',
+ 'share_caption' => 'Публікую з TryPost уже тижнів поспіль: :count!',
+ 'image_weeks' => 'тиж.',
+ 'image_tagline' => 'регулярних публікацій!',
+ ],
];
diff --git a/lang/uk/posts.php b/lang/uk/posts.php
index 100bf78f6..b9bafbbf8 100644
--- a/lang/uk/posts.php
+++ b/lang/uk/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => 'Поставити цей допис на початок черги.',
'add' => 'Додати до черги',
'add_many' => 'Додати до черги: :count',
- 'added' => '{1} Додано до черги|[0,*] Додано до черги: :count',
+ 'added' => '{1} Ваш допис додано до черги.|[0,*] Дописів додано до черги: :count.',
+ 'moved_to_top' => 'Ваш допис переміщено на початок черги.',
'no_slots_hint' => 'Додайте час публікації, щоб користуватися чергою.',
'no_slots_channels' => 'Немає часу публікації: :channels',
'no_slots_tooltip' => 'Немає часу публікації для :channels. Додайте час, щоб користуватися чергою.',
diff --git a/lang/zh/analytics.php b/lang/zh/analytics.php
index 33b308b60..fda4882cd 100644
--- a/lang/zh/analytics.php
+++ b/lang/zh/analytics.php
@@ -428,6 +428,11 @@ return [
'caption_workspace' => '我们所有频道的:metric::value(:range)📈',
'caption_summary_workspace' => '我们 :range 的数据 📈 :metrics',
'caption_summary_channel' => '我们在 :channel 上 :range 的数据 📈 :metrics',
+ 'caption_posting_activity' => [
+ 'record_streak' => '🔥 已连续发布 :days,创下我们的最长纪录!过去 12 个月共发布 :posts 篇帖子。',
+ 'on_streak' => '🔥 已连续发布 :days。我们的纪录是 :best,过去 12 个月共发布 :posts 篇帖子。',
+ 'no_streak' => '📅 过去 12 个月共发布 :posts 篇帖子,最长连续发布 :best。',
+ ],
'export_failed' => '无法生成图片,请重试。',
'colors' => [
'violet' => '紫罗兰色',
@@ -448,4 +453,33 @@ return [
'slate' => '石板色',
],
],
+ 'posting_activity' => [
+ 'title' => '发布活跃度',
+ 'subtitle' => '过去 12 个月',
+ 'current_streak' => '当前连续',
+ 'best_streak' => '最长连续',
+ 'total' => '帖子',
+ 'days' => ':count 天',
+ 'less' => '少',
+ 'more' => '多',
+ 'posts_on_day' => '{0} 没有帖子|[1,*] :count 篇帖子',
+ 'about' => [
+ 'current_streak' => '你连续发布的天数。每天至少发布一次,才能保持连续。',
+ 'best_streak' => '过去 12 个月中你连续发布的最长天数。',
+ 'total' => '过去 12 个月你发布的所有帖子,包括在 TryPost 之外发布的。',
+ ],
+ ],
+ 'posting_streak' => [
+ 'button' => '查看连续记录',
+ 'title' => '连续 :count 周',
+ 'top' => '前 :percent%',
+ 'rank_tooltip' => '与其他 TryPost 用户相比',
+ 'keep_going' => '做得好!安排下周的帖子,保持连续记录。',
+ 'post_this_week' => '你本周还没有发布。安排一篇帖子来保持连续记录。',
+ 'schedule' => '安排帖子',
+ 'share' => '分享记录',
+ 'share_caption' => '我已用 TryPost 连续发布 :count 周!',
+ 'image_weeks' => '周',
+ 'image_tagline' => '持续发布中!',
+ ],
];
diff --git a/lang/zh/posts.php b/lang/zh/posts.php
index be9f9a31d..c102c0192 100644
--- a/lang/zh/posts.php
+++ b/lang/zh/posts.php
@@ -211,7 +211,8 @@ return [
'top_description' => '将此帖子放在队列最前面。',
'add' => '加入队列',
'add_many' => '将 :count 个加入队列',
- 'added' => '已加入队列|已将 :count 个帖子加入队列',
+ 'added' => '{1} 你的帖子已加入队列。|[0,*] 你的 :count 个帖子已加入队列。',
+ 'moved_to_top' => '你的帖子已移到队列最前面。',
'no_slots_hint' => '添加发布时间以使用队列。',
'no_slots_channels' => '没有发布时间::channels',
'no_slots_tooltip' => ':channels 没有发布时间。添加发布时间即可使用队列。',
diff --git a/resources/css/app.css b/resources/css/app.css
index 3c4992aae..d2878bcfe 100644
--- a/resources/css/app.css
+++ b/resources/css/app.css
@@ -707,3 +707,22 @@ html {
animation: motion-sound-wave 0.9s ease-in-out infinite;
}
}
+
+@keyframes streak-sway {
+ 0%,
+ 100% {
+ transform: rotate(-8deg);
+ }
+
+ 50% {
+ transform: rotate(8deg);
+ }
+}
+
+@utility streak-sway {
+ transform-origin: 50% 85%;
+
+ @media (prefers-reduced-motion: no-preference) {
+ animation: streak-sway 2.4s ease-in-out infinite;
+ }
+}
diff --git a/resources/js/components/AppSidebar.vue b/resources/js/components/AppSidebar.vue
index 281fbb6a4..c11bdf835 100644
--- a/resources/js/components/AppSidebar.vue
+++ b/resources/js/components/AppSidebar.vue
@@ -20,6 +20,7 @@ import InviteMemberDialog from '@/components/members/InviteMemberDialog.vue';
import NavChannels from '@/components/NavChannels.vue';
import NavMain from '@/components/NavMain.vue';
import SidebarUserMenu from '@/components/SidebarUserMenu.vue';
+import PostingStreakBadge from '@/components/streak/PostingStreakBadge.vue';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
@@ -55,6 +56,8 @@ const page = usePage();
const currentWorkspace = computed(
() => page.props.auth.currentWorkspace,
);
+/** The workspace's weeks in a row with a post; null hides the badge. */
+const postingStreak = computed(() => page.props.postingStreak);
const {
canCreatePost,
@@ -134,6 +137,12 @@ const mainNavItems = computed<NavItem[]>(() => [
<AppLogo variant="mark" class="text-[21px]" />
</span>
</Link>
+ <div
+ v-if="postingStreak"
+ class="flex group-data-[collapsible=icon]:hidden"
+ >
+ <PostingStreakBadge :streak="postingStreak" />
+ </div>
</SidebarHeader>
<SidebarContent class="gap-0">
diff --git a/resources/js/components/Toast.vue b/resources/js/components/Toast.vue
index 4f83beb8b..3fbaf33dd 100644
--- a/resources/js/components/Toast.vue
+++ b/resources/js/components/Toast.vue
@@ -1,9 +1,10 @@
<script setup lang="ts">
-import { usePage } from '@inertiajs/vue3';
+import { router, usePage } from '@inertiajs/vue3';
import { watch } from 'vue';
import { toast } from 'vue-sonner';
import { Toaster } from '@/components/ui/sonner';
+import { type ToastLink, toastLinkOptions } from '@/lib/toastLink';
type Flash = {
banner?: string;
@@ -12,6 +13,7 @@ type Flash = {
error?: string;
warning?: string;
info?: string;
+ link?: ToastLink;
};
const page = usePage();
@@ -40,20 +42,22 @@ watch(
}
}
+ const link = toastLinkOptions(flash.link, (url) => router.visit(url));
+
if (flash.success) {
- toast.success(flash.success, { id: 'flash-success' });
+ toast.success(flash.success, { id: 'flash-success', testId: 'flash-success-toast', ...link });
}
if (flash.error) {
- toast.error(flash.error, { id: 'flash-error' });
+ toast.error(flash.error, { id: 'flash-error', testId: 'flash-error-toast', ...link });
}
if (flash.warning) {
- toast.warning(flash.warning, { id: 'flash-warning' });
+ toast.warning(flash.warning, { id: 'flash-warning', testId: 'flash-warning-toast', ...link });
}
if (flash.info) {
- toast.info(flash.info, { id: 'flash-info' });
+ toast.info(flash.info, { id: 'flash-info', testId: 'flash-info-toast', ...link });
}
},
{ deep: true, immediate: true },
diff --git a/resources/js/components/analytics/PostingActivityCard.vue b/resources/js/components/analytics/PostingActivityCard.vue
new file mode 100644
index 000000000..688ca9573
--- /dev/null
+++ b/resources/js/components/analytics/PostingActivityCard.vue
@@ -0,0 +1,128 @@
+<script setup lang="ts">
+import { transChoice } from 'laravel-vue-i18n';
+import { computed } from 'vue';
+
+import ShareChartButton from '@/components/analytics/ShareChartButton.vue';
+import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';
+import PostingActivityHeatmap from '@/components/analytics/workspace/charts/PostingActivityHeatmap.vue';
+import InfoTip from '@/components/analytics/workspace/InfoTip.vue';
+import { Skeleton } from '@/components/ui/skeleton';
+import { blank, filled } from '@/lib/helpers';
+import { postingActivityShareOption } from '@/lib/insightsShare';
+import {
+ POSTING_ACTIVITY_STAT_ICONS,
+ type PostingActivityStat,
+} from '@/lib/postingActivity';
+import type { ShareMetricOption } from '@/lib/shareCard';
+import { formatFullNumber } from '@/lib/utils';
+import type { PostingActivity } from '@/types/analytics';
+
+const props = defineProps<{
+ activity?: PostingActivity;
+ /** The channel the activity belongs to, as the share card names it; the workspace when left out. */
+ channel?: string;
+}>();
+
+const STATS: PostingActivityStat[] = ['current_streak', 'best_streak', 'total'];
+
+const isLoading = computed((): boolean => blank(props.activity));
+
+const days = (count: number): string =>
+ transChoice('analytics.posting_activity.days', count);
+
+/** The activity the share button shares: none while it loads, and none without a post to show. */
+const shareable = computed((): PostingActivity | null => {
+ if (!filled(props.activity)) {
+ return null;
+ }
+
+ if (props.activity.total === 0) {
+ return null;
+ }
+
+ return props.activity;
+});
+
+const statValue = (activity: PostingActivity, key: PostingActivityStat): string => {
+ if (key === 'total') {
+ return formatFullNumber(activity.total);
+ }
+
+ return days(activity[key]);
+};
+
+const labelKey = (key: PostingActivityStat): string => `analytics.posting_activity.${key}`;
+
+const aboutKey = (key: PostingActivityStat): string =>
+ `analytics.posting_activity.about.${key}`;
+
+/** The share card's builder for the loaded activity. */
+const shareBuilder = (activity: PostingActivity) => (): ShareMetricOption =>
+ postingActivityShareOption(activity);
+</script>
+
+<template>
+ <AnalyticsSection
+ :title="$t('analytics.posting_activity.title')"
+ :subtitle="$t('analytics.posting_activity.subtitle')"
+ data-testid="posting-activity"
+ >
+ <template v-if="shareable" #actions>
+ <ShareChartButton
+ :subject="channel"
+ :range="$t('analytics.posting_activity.subtitle')"
+ :build="shareBuilder(shareable)"
+ test-id="share-posting-activity"
+ />
+ </template>
+ <div
+ v-if="isLoading"
+ class="grid gap-5"
+ data-testid="posting-activity-skeleton"
+ aria-busy="true"
+ >
+ <Skeleton class="h-9 w-2/3" />
+ <Skeleton class="h-40 w-full" />
+ </div>
+
+ <div v-else-if="activity" class="min-w-0">
+ <div
+ class="mb-5 flex flex-wrap gap-x-8 gap-y-3"
+ data-testid="posting-activity-stats"
+ >
+ <div
+ v-for="key in STATS"
+ :key="key"
+ class="flex min-w-0 flex-col gap-1"
+ >
+ <span
+ class="flex items-center gap-0.5 text-sm whitespace-nowrap text-muted-foreground"
+ >
+ {{ $t(labelKey(key)) }}
+ <InfoTip
+ :text="$t(aboutKey(key))"
+ :test-id="`posting-activity-${key}-about`"
+ />
+ </span>
+ <span class="flex items-center gap-1.5">
+ <component
+ :is="POSTING_ACTIVITY_STAT_ICONS[key].icon"
+ class="size-5 shrink-0"
+ :style="{ color: POSTING_ACTIVITY_STAT_ICONS[key].color }"
+ aria-hidden="true"
+ />
+ <span
+ class="font-heading text-2xl leading-8 font-medium whitespace-nowrap text-foreground tabular-nums"
+ :data-testid="`posting-activity-${key}`"
+ >{{ statValue(activity, key) }}</span
+ >
+ </span>
+ </div>
+ </div>
+ <PostingActivityHeatmap
+ :days="activity.days"
+ :max-count="activity.max_count"
+ />
+ </div>
+ </AnalyticsSection>
+</template>
diff --git a/resources/js/components/analytics/workspace/charts/PostingActivityHeatmap.vue b/resources/js/components/analytics/workspace/charts/PostingActivityHeatmap.vue
new file mode 100644
index 000000000..ac1ab1509
--- /dev/null
+++ b/resources/js/components/analytics/workspace/charts/PostingActivityHeatmap.vue
@@ -0,0 +1,235 @@
+<script setup lang="ts">
+import {
+ VisHeatmap,
+ VisHeatmapSelectors,
+ VisSingleContainer,
+} from '@unovis/vue';
+import { useElementSize } from '@vueuse/core';
+import { computed, nextTick, ref, useTemplateRef, watch } from 'vue';
+
+import PostingActivityTooltip from '@/components/analytics/workspace/charts/PostingActivityTooltip.vue';
+import {
+ ChartContainer,
+ ChartTooltip,
+ componentToString,
+ type ChartConfig,
+} from '@/components/ui/chart';
+import { useChartAppContext } from '@/composables/analytics/useChartAppContext';
+import date from '@/date';
+import { filled } from '@/lib/helpers';
+import {
+ DAYS_PER_WEEK,
+ postingActivityMonths,
+ postingActivityOffset,
+} from '@/lib/postingActivity';
+import { orderedWeekdays } from '@/preferences';
+import type { PostingActivityDay } from '@/types/analytics';
+
+const props = defineProps<{
+ /** One entry per day, oldest first. */
+ days: PostingActivityDay[];
+ /** The busiest day's posts, the top of the colour scale. */
+ maxCount: number;
+}>();
+
+const CELL_GAP = 4;
+const MIN_CELL = 10;
+/** Room the weekday labels take on the left: the chart's padding and the widest short weekday. */
+const ROW_LABEL_SPACE = 36;
+/** Room the month labels take on top: their font size and Unovis' label padding. */
+const COLUMN_LABEL_SPACE = 17;
+/** Monday, Wednesday and Friday (0 = Sunday), wherever the user's week starts. */
+const LABELLED_WEEKDAYS = [1, 3, 5];
+/** One violet at rising strength, so the scale reads the same in light and dark. */
+const LEVEL_COLORS = [
+ 'color-mix(in oklab, var(--chart-3) 30%, transparent)',
+ 'color-mix(in oklab, var(--chart-3) 55%, transparent)',
+ 'color-mix(in oklab, var(--chart-3) 80%, transparent)',
+ 'var(--chart-3)',
+];
+
+/** A zero-height ruler: its width never depends on the grid, so measuring it cannot loop. */
+const ruler = useTemplateRef<HTMLElement>('ruler');
+const { width } = useElementSize(ruler);
+const scroller = useTemplateRef<HTMLElement>('scroller');
+
+const offset = computed((): number => postingActivityOffset(props.days));
+
+const columns = computed((): number =>
+ Math.ceil((props.days.length + offset.value) / DAYS_PER_WEEK),
+);
+
+/**
+ * The cells stretch across the whole card; the chart's height keeps them square.
+ * Below the smallest cell, a phone scrolls the grid instead of shrinking it.
+ */
+const cellSize = computed((): number => {
+ const gaps = (columns.value - 1) * CELL_GAP;
+ const fitting = (width.value - ROW_LABEL_SPACE - gaps) / columns.value;
+
+ return Math.max(fitting, MIN_CELL);
+});
+
+const chartHeight = computed(
+ (): number =>
+ COLUMN_LABEL_SPACE +
+ DAYS_PER_WEEK * cellSize.value +
+ (DAYS_PER_WEEK - 1) * CELL_GAP,
+);
+
+const minChartWidth = computed(
+ (): string =>
+ `${ROW_LABEL_SPACE + columns.value * (MIN_CELL + CELL_GAP)}px`,
+);
+
+/** The chart never narrower than its smallest cells, so a phone scrolls it. */
+const chartStyle = computed((): { minWidth: string } => ({
+ minWidth: minChartWidth.value,
+}));
+
+/** A legend square in one of the grid's colors. */
+const swatchStyle = (color: string): { backgroundColor: string } => ({
+ backgroundColor: color,
+});
+
+const colorDomain = computed((): [number, number] => {
+ if (props.maxCount < 1) {
+ return [1, 1];
+ }
+
+ return [1, props.maxCount];
+});
+
+/** A day without posts has no value, so it is drawn as an empty cell. */
+const cellValue = (day: PostingActivityDay): number | null => {
+ if (day.count === 0) {
+ return null;
+ }
+
+ return day.count;
+};
+
+const months = computed(() => postingActivityMonths(props.days, offset.value));
+
+/** The month's short name above the week its first day falls in. */
+const columnLabel = (column: number): string | undefined =>
+ months.value.find((month) => month.column === column)?.label;
+
+const rowLabel = (row: number): string | undefined => {
+ const weekday = orderedWeekdays()[row];
+
+ if (!LABELLED_WEEKDAYS.includes(weekday)) {
+ return undefined;
+ }
+
+ return date.formatShortWeekday(weekday);
+};
+
+/** The chart draws one series; the config only satisfies the container. */
+const chartConfig: ChartConfig = {};
+
+const appContext = useChartAppContext();
+const tooltipTemplate = componentToString(
+ chartConfig,
+ PostingActivityTooltip,
+ {},
+ appContext,
+);
+
+const tooltipTriggers = {
+ [VisHeatmapSelectors.cell]: (cell: {
+ datum: PostingActivityDay;
+ }): string | undefined => tooltipTemplate?.({ ...cell.datum }),
+};
+
+/** Whether the grid shows its latest weeks; false once the user scrolls back to older ones. */
+const followsToday = ref(true);
+
+/** A grid wider than a phone opens on the latest weeks, and keeps them in view as it resizes until the user scrolls away. */
+const scrollToToday = async (): Promise<void> => {
+ await nextTick();
+
+ if (!filled(scroller.value)) {
+ return;
+ }
+
+ if (!followsToday.value) {
+ return;
+ }
+
+ scroller.value.scrollLeft = scroller.value.scrollWidth;
+};
+
+/** Remembers whether the user left the latest weeks, so a resize never pulls them back. */
+const rememberScroll = (): void => {
+ if (!filled(scroller.value)) {
+ return;
+ }
+
+ const { scrollLeft, clientWidth, scrollWidth } = scroller.value;
+
+ followsToday.value = scrollLeft + clientWidth >= scrollWidth - 1;
+};
+
+watch(width, scrollToToday);
+
+const cellAttributes = {
+ [VisHeatmapSelectors.cell]: { 'data-testid': 'posting-activity-cell' },
+};
+</script>
+
+<template>
+ <div class="grid gap-3" data-testid="posting-activity-heatmap">
+ <div ref="ruler" class="h-0 w-full" />
+ <div
+ ref="scroller"
+ class="overflow-x-auto"
+ dir="ltr"
+ role="img"
+ @scroll="rememberScroll"
+ :aria-label="$t('analytics.posting_activity.title')"
+ data-testid="posting-activity-scroller"
+ >
+ <ChartContainer
+ :config="chartConfig"
+ class="[--vis-heatmap-cell-fill-color:var(--muted)] [--vis-heatmap-label-color:var(--muted-foreground)] [--vis-heatmap-label-font-size:11px] dark:[--vis-heatmap-cell-fill-color:var(--accent)]"
+ :style="chartStyle"
+ >
+ <VisSingleContainer
+ :data="days"
+ :height="chartHeight"
+ :padding="{ left: 6 }"
+ >
+ <VisHeatmap
+ :value="cellValue"
+ :color-range="LEVEL_COLORS"
+ :color-domain="colorDomain"
+ :num-rows="DAYS_PER_WEEK"
+ layout="column"
+ :offset="offset"
+ :cell-padding="CELL_GAP"
+ :cell-corner-radius="3"
+ :column-label="columnLabel"
+ :row-label="rowLabel"
+ :attributes="cellAttributes"
+ />
+ <ChartTooltip :triggers="tooltipTriggers" />
+ </VisSingleContainer>
+ </ChartContainer>
+ </div>
+
+ <div
+ class="flex items-center justify-center gap-1.5 text-xs text-muted-foreground"
+ >
+ <span>{{ $t('analytics.posting_activity.less') }}</span>
+ <span class="size-3 rounded-[3px] bg-muted dark:bg-accent" />
+ <span
+ v-for="color in LEVEL_COLORS"
+ :key="color"
+ class="size-3 rounded-[3px]"
+ :style="swatchStyle(color)"
+ />
+ <span>{{ $t('analytics.posting_activity.more') }}</span>
+ </div>
+ </div>
+</template>
diff --git a/resources/js/components/analytics/workspace/charts/PostingActivityTooltip.vue b/resources/js/components/analytics/workspace/charts/PostingActivityTooltip.vue
new file mode 100644
index 000000000..6dc9939b4
--- /dev/null
+++ b/resources/js/components/analytics/workspace/charts/PostingActivityTooltip.vue
@@ -0,0 +1,39 @@
+<script setup lang="ts">
+import { transChoice } from 'laravel-vue-i18n';
+import { computed } from 'vue';
+
+import date from '@/date';
+import { formatFullNumber } from '@/lib/utils';
+import type { PostingActivityDay } from '@/types/analytics';
+
+defineOptions({ inheritAttrs: false });
+
+/** Rendered to a string by `componentToString`, which hands the day over as `payload`. */
+const props = defineProps<{
+ payload: PostingActivityDay;
+}>();
+
+const posts = computed((): string =>
+ transChoice(
+ 'analytics.posting_activity.posts_on_day',
+ props.payload.count,
+ {
+ count: formatFullNumber(props.payload.count),
+ },
+ ),
+);
+
+const day = computed((): string =>
+ date.formatWeekdayMonthDay(props.payload.date, 'UTC'),
+);
+</script>
+
+<template>
+ <div
+ class="grid gap-0.5 rounded-xl bg-popover px-3 py-2 text-xs shadow-md ring-1 ring-foreground/5 dark:ring-border"
+ data-testid="posting-activity-tooltip"
+ >
+ <p class="font-medium text-foreground tabular-nums">{{ posts }}</p>
+ <p class="text-muted-foreground">{{ day }}</p>
+ </div>
+</template>
diff --git a/resources/js/components/posts/composer/GlobalPostComposer.vue b/resources/js/components/posts/composer/GlobalPostComposer.vue
index 0bf0a9a2b..7346b7f61 100644
--- a/resources/js/components/posts/composer/GlobalPostComposer.vue
+++ b/resources/js/components/posts/composer/GlobalPostComposer.vue
@@ -1,8 +1,6 @@
<script setup lang="ts">
import { router, usePage } from '@inertiajs/vue3';
-import { transChoice } from 'laravel-vue-i18n';
import { computed, ref, watch } from 'vue';
-import { toast } from 'vue-sonner';
import PostComposerDialog from '@/components/posts/composer/PostComposerDialog.vue';
import { clearComposerAutosave } from '@/composables/useComposerAutosave';
@@ -82,14 +80,6 @@ const submitComposition = (
page.props.auth?.currentWorkspace?.id,
);
closePostComposer();
- if (composition.queue) {
- const count = composition.destinations.length;
- toast.success(
- transChoice('posts.composer.queue.added', count, {
- count: String(count),
- }),
- );
- }
if (createAnother) openPostComposer();
onSaved?.();
},
diff --git a/resources/js/components/publish/AddToQueueButton.vue b/resources/js/components/publish/AddToQueueButton.vue
index a372d9f51..a24b6da4f 100644
--- a/resources/js/components/publish/AddToQueueButton.vue
+++ b/resources/js/components/publish/AddToQueueButton.vue
@@ -25,14 +25,12 @@ const props = defineProps<{
account: PublishSocialAccount;
}>();
-const { canManageAccounts, requiresApproval } = useWorkspaceAbilities();
+const { canManageAccounts } = useWorkspaceAbilities();
const queueSetupOpen = ref(false);
const addToQueue = (): void => {
- schedulePostCard(props.post.id, 'queue_next', {
- requestsApproval: requiresApproval.value,
- });
+ schedulePostCard(props.post.id, 'queue_next');
};
const closeQueueSetup = (): void => {
diff --git a/resources/js/components/streak/PostingStreakBadge.vue b/resources/js/components/streak/PostingStreakBadge.vue
new file mode 100644
index 000000000..f36e3b953
--- /dev/null
+++ b/resources/js/components/streak/PostingStreakBadge.vue
@@ -0,0 +1,282 @@
+<script setup lang="ts">
+import { IconFlameFilled, IconShare } from '@tabler/icons-vue';
+import { trans, transChoice } from 'laravel-vue-i18n';
+import { onBeforeUnmount, ref } from 'vue';
+import { toast } from 'vue-sonner';
+
+import { Button } from '@/components/ui/button';
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@/components/ui/popover';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
+import { openPostComposer } from '@/composables/useGlobalPostComposer';
+import { filled } from '@/lib/helpers';
+import { streakShareFile } from '@/lib/streakShareImage';
+import { formatFullNumber } from '@/lib/utils';
+import { storeChunked } from '@/routes/app/media';
+import type { PostingStreak } from '@/types/posting-streak';
+import { uploadChunked } from '@/utils/chunkedUpload';
+
+const props = defineProps<{
+ streak: PostingStreak;
+}>();
+
+const open = ref(false);
+const sharing = ref(false);
+const mounted = ref(true);
+
+onBeforeUnmount(() => {
+ mounted.value = false;
+});
+
+/** Whether the share the user asked for still has somewhere to land: the popover open, the badge on the page. */
+const stillSharing = (): boolean => {
+ if (!mounted.value) {
+ return false;
+ }
+
+ return open.value;
+};
+
+const weeks = (): string => formatFullNumber(props.streak.weeks);
+
+/** What keeps the streak going: next week once this one has a post, this week otherwise. */
+const nudgeKey = (): string => {
+ if (props.streak.posted_this_week) {
+ return 'analytics.posting_streak.keep_going';
+ }
+
+ return 'analytics.posting_streak.post_this_week';
+};
+
+/** Three digits shrink so the number stays inside its 80px circle. */
+const numberSize = (): string => {
+ if (props.streak.weeks >= 100) {
+ return 'text-[30px]';
+ }
+
+ return 'text-[40px]';
+};
+
+const hasRank = (): boolean => filled(props.streak.top_percent);
+
+const percent = (): string => String(props.streak.top_percent);
+
+/**
+ * Opening the streak focuses the popover itself, so the rank's tooltip waits
+ * for a hover or a Tab. The event comes from Reka's wrapper; the popover is in it.
+ */
+const focusPopover = (event: Event): void => {
+ event.preventDefault();
+
+ const popover = (event.target as HTMLElement).querySelector<HTMLElement>(
+ '[data-slot="popover-content"]',
+ );
+
+ if (!filled(popover)) {
+ return;
+ }
+
+ popover.focus({ preventScroll: true });
+};
+
+const schedulePost = (): void => {
+ open.value = false;
+ openPostComposer();
+};
+
+/** Opens the composer with the streak's image and a post that announces it. */
+const sharePost = async (): Promise<void> => {
+ sharing.value = true;
+
+ try {
+ const file = await streakShareFile(props.streak.weeks, {
+ number: weeks(),
+ unit: transChoice(
+ 'analytics.posting_streak.image_weeks',
+ props.streak.weeks,
+ ),
+ tagline: trans('analytics.posting_streak.image_tagline'),
+ });
+ const media = await uploadChunked({ file, url: storeChunked.url() });
+
+ if (!stillSharing()) {
+ return;
+ }
+
+ open.value = false;
+ openPostComposer({
+ draft: {
+ content: transChoice(
+ 'analytics.posting_streak.share_caption',
+ props.streak.weeks,
+ ),
+ media: [media],
+ scheduled_at: null,
+ label_ids: [],
+ },
+ });
+ } catch {
+ if (!stillSharing()) {
+ return;
+ }
+
+ toast.error(trans('analytics.share.post_failed'), {
+ testId: 'posting-streak-share-error',
+ });
+ } finally {
+ sharing.value = false;
+ }
+};
+</script>
+
+<template>
+ <Popover v-model:open="open">
+ <PopoverTrigger as-child>
+ <button
+ type="button"
+ class="relative inline-flex size-8 shrink-0 items-center justify-center rounded-lg outline-hidden hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-sidebar-ring"
+ :aria-label="$t('analytics.posting_streak.button')"
+ data-testid="posting-streak-badge"
+ >
+ <IconFlameFilled
+ class="size-6 text-orange-500"
+ aria-hidden="true"
+ />
+ <span
+ class="absolute top-4 left-4 inline-flex h-4 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-[11px] leading-4 font-[650] text-primary-foreground tabular-nums"
+ data-testid="posting-streak-count"
+ >{{ weeks() }}</span
+ >
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ side="bottom"
+ align="center"
+ :side-offset="16"
+ class="w-61 rounded-xl p-2"
+ data-testid="posting-streak-popover"
+ @open-auto-focus="focusPopover"
+ >
+ <div class="flex flex-col gap-4">
+ <div class="relative h-25.25">
+ <div
+ class="relative h-16.5 overflow-hidden rounded-lg bg-violet-100 dark:bg-violet-950/60"
+ aria-hidden="true"
+ >
+ <div
+ class="absolute -top-3 -left-4 h-12 w-24 rounded-full bg-violet-50/80 dark:bg-violet-900/40"
+ />
+ <div
+ class="absolute inset-0 bg-violet-300 [clip-path:polygon(60%_0,100%_0,100%_100%,57%_100%)] dark:bg-violet-700"
+ />
+ <span
+ class="absolute top-2.5 left-3 size-1 rounded-full bg-violet-400"
+ />
+ <span
+ class="absolute top-9 left-9 size-1.5 rounded-full bg-white/90"
+ />
+ <span
+ class="absolute top-2 left-36 size-1 rounded-full bg-violet-950"
+ />
+ <span
+ class="absolute top-11 left-48 size-1 rounded-full bg-white/90"
+ />
+ <span
+ class="absolute top-4 right-3 size-1.5 rounded-full bg-violet-950"
+ />
+ </div>
+ <div
+ class="absolute top-4 left-17.25 size-20 rounded-full bg-primary text-center font-heading leading-20 font-normal text-primary-foreground tabular-nums"
+ :class="numberSize()"
+ >
+ {{ weeks() }}
+ </div>
+ <div
+ class="absolute top-15 left-29.75 inline-flex size-10 items-center justify-center rounded-full bg-orange-100 ring-2 ring-popover dark:bg-orange-950"
+ >
+ <IconFlameFilled
+ class="size-6 streak-sway text-orange-500"
+ aria-hidden="true"
+ />
+ </div>
+ </div>
+
+ <div class="flex flex-col items-center text-center">
+ <h3
+ class="font-heading text-lg leading-[22.5px] font-medium text-foreground"
+ data-testid="posting-streak-title"
+ >
+ {{
+ $tChoice(
+ 'analytics.posting_streak.title',
+ streak.weeks,
+ { count: weeks() },
+ )
+ }}
+ </h3>
+ <TooltipProvider v-if="hasRank()" :delay-duration="200">
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <button
+ type="button"
+ class="mt-0.5 rounded bg-primary-text/20 px-1 text-xs leading-4.5 font-medium text-primary-text outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
+ data-testid="posting-streak-rank"
+ >
+ {{
+ $t('analytics.posting_streak.top', {
+ percent: percent(),
+ })
+ }}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent
+ class="max-w-[calc(100vw-2rem)] sm:max-w-none sm:whitespace-nowrap"
+ data-testid="posting-streak-rank-tooltip"
+ >
+ {{
+ $t('analytics.posting_streak.rank_tooltip')
+ }}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <p
+ class="mt-2 px-2 text-sm leading-5.25 text-muted-foreground"
+ data-testid="posting-streak-nudge"
+ >
+ {{ $t(nudgeKey()) }}
+ </p>
+ </div>
+
+ <div class="flex justify-center gap-2 px-2">
+ <Button
+ size="sm"
+ class="h-8 rounded-lg px-3"
+ data-testid="posting-streak-schedule"
+ @click="schedulePost"
+ >
+ {{ $t('analytics.posting_streak.schedule') }}
+ </Button>
+ <Button
+ variant="outline"
+ size="icon"
+ class="size-8 rounded-lg"
+ :loading="sharing"
+ :aria-label="$t('analytics.posting_streak.share')"
+ data-testid="posting-streak-share"
+ @click="sharePost"
+ >
+ <IconShare aria-hidden="true" />
+ </Button>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+</template>
diff --git a/resources/js/components/ui/sonner/Sonner.vue b/resources/js/components/ui/sonner/Sonner.vue
index 2142d6d1c..577c90796 100644
--- a/resources/js/components/ui/sonner/Sonner.vue
+++ b/resources/js/components/ui/sonner/Sonner.vue
@@ -19,6 +19,13 @@ const props = defineProps<ToasterProps>()
position="top-center"
offset="16px"
close-button
+ :toast-options="{
+ classes: {
+ toast: '!text-sm',
+ actionButton:
+ '!ms-1.5 !h-auto !self-center !bg-transparent !p-0 !text-sm !leading-[1.5] !font-medium !text-primary-text hover:!text-primary-text-hover hover:underline',
+ },
+ }"
:style="{
'--width': '480px',
'--normal-bg': 'var(--popover)',
diff --git a/resources/js/composables/usePostCardActions.ts b/resources/js/composables/usePostCardActions.ts
index 2f2664252..0c528a0df 100644
--- a/resources/js/composables/usePostCardActions.ts
+++ b/resources/js/composables/usePostCardActions.ts
@@ -1,5 +1,5 @@
import { router, usePage } from '@inertiajs/vue3';
-import { trans, transChoice } from 'laravel-vue-i18n';
+import { trans } from 'laravel-vue-i18n';
import { inject, type InjectionKey, type Ref } from 'vue';
import { toast } from 'vue-sonner';
@@ -57,19 +57,6 @@ export const usePostCardReload = (
fallback: PostCardReload,
): (() => PostCardReload) => inject(postCardReloadKey, () => fallback);
-const successMessage = (
- action: PostScheduleAction,
- requestsApproval: boolean,
-): string | null => {
- if (action !== 'queue_next' && action !== 'queue_top') {
- return null;
- }
-
- return requestsApproval
- ? trans('posts.approvals.requested')
- : transChoice('posts.composer.queue.added', 1, { count: '1' });
-};
-
export const toastFirstError = (errors: Record<string, string>): void => {
const message = Object.values(errors)[0];
@@ -84,26 +71,16 @@ export const schedulePostCard = (
options: {
only?: string[];
reset?: string[];
- requestsApproval?: boolean;
onStart?: () => void;
onFinish?: () => void;
} = {},
): void => {
- const { requestsApproval = false, ...reload } = options;
-
router.put(
updatePostSchedule.url(postId),
{ action },
{
- ...reload,
+ ...options,
preserveScroll: true,
- onSuccess: () => {
- const message = successMessage(action, requestsApproval);
-
- if (message) {
- toast.success(message, { testId: 'post-schedule-toast' });
- }
- },
onError: toastFirstError,
},
);
diff --git a/resources/js/date.ts b/resources/js/date.ts
index e5fddf72b..7109e9a02 100644
--- a/resources/js/date.ts
+++ b/resources/js/date.ts
@@ -227,6 +227,11 @@ export default {
return localized(date).format('D MMM');
},
+ /** A weekday by its number (0 = Sunday), short: "Mon". */
+ formatShortWeekday(weekday: number) {
+ return localized().day(weekday).format('ddd');
+ },
+
formatDayMonthYear(date: string | Date) {
return localized(date).format('D MMM YYYY');
},
diff --git a/resources/js/lib/insightsShare.ts b/resources/js/lib/insightsShare.ts
index 53286f7fc..c46022746 100644
--- a/resources/js/lib/insightsShare.ts
+++ b/resources/js/lib/insightsShare.ts
@@ -3,7 +3,7 @@
* script-level computed, so every `trans()` here reads the loaded locale.
*/
-import { trans } from 'laravel-vue-i18n';
+import { trans, transChoice } from 'laravel-vue-i18n';
import date from '@/date';
import { activeLocale } from '@/language';
@@ -19,6 +19,7 @@ import {
seriesDelta,
shownPeriod,
} from '@/lib/channelMetrics';
+import { POSTING_ACTIVITY_STAT_ICONS, type PostingActivityStat, postingActivityMonths, postingActivityOffset } from '@/lib/postingActivity';
import {
periodFigure,
type ShareChannel,
@@ -29,12 +30,13 @@ import {
type ShareShape,
type ShareTile,
} from '@/lib/shareCard';
-import { formatCountChange, formatNumberCompact } from '@/lib/utils';
+import { formatCountChange, formatFullNumber, formatNumberCompact } from '@/lib/utils';
import type {
AccountIdentityData,
ChannelMetricSeries,
FollowerAccount,
FollowersChartMode,
+ PostingActivity,
PostsChartMode,
PublicationPeriod,
SeriesMetric,
@@ -140,6 +142,7 @@ const shareOption = (
lines: [],
series: [],
chartMode: 'current',
+ heatmap: null,
...option,
});
@@ -389,3 +392,61 @@ export const postsShareOption = (
caption: metricCaption({ metric: label, value: figure, range }),
});
};
+
+/** A number of days as the posting activity card prints it: "9 days". */
+const streakDays = (count: number): string => transChoice('analytics.posting_activity.days', count);
+
+/**
+ * The post text for the posting activity, a sentence that fits the moment:
+ * a streak at its record, a streak still under it, or no streak today.
+ */
+const postingActivityCaption = (activity: PostingActivity): string => {
+ const replacements = {
+ days: streakDays(activity.current_streak),
+ best: streakDays(activity.best_streak),
+ posts: formatFullNumber(activity.total),
+ };
+
+ if (activity.current_streak === 0) {
+ return transChoice('analytics.share.caption_posting_activity.no_streak', activity.total, replacements);
+ }
+
+ if (activity.current_streak === activity.best_streak) {
+ return transChoice('analytics.share.caption_posting_activity.record_streak', activity.total, replacements);
+ }
+
+ return transChoice('analytics.share.caption_posting_activity.on_streak', activity.total, replacements);
+};
+
+/** A number of the posting activity card, which always has a value. */
+const activityTile = (stat: PostingActivityStat, figure: string): ShareTile => ({
+ label: trans(`analytics.posting_activity.${stat}`),
+ figure,
+ missing: false,
+ change: null,
+ icon: POSTING_ACTIVITY_STAT_ICONS[stat],
+});
+
+/** The posting activity card: the streaks and posts as the card prints them, and the year's grid. */
+export const postingActivityShareOption = (activity: PostingActivity): ShareMetricOption => {
+ const offset = postingActivityOffset(activity.days);
+ const tiles = [
+ activityTile('current_streak', streakDays(activity.current_streak)),
+ activityTile('best_streak', streakDays(activity.best_streak)),
+ activityTile('total', formatFullNumber(activity.total)),
+ ];
+
+ return shareOption({
+ key: 'posting_activity',
+ label: trans('analytics.posting_activity.title'),
+ shape: 'heatmap',
+ tiles,
+ heatmap: {
+ counts: activity.days.map((day) => day.count),
+ maxCount: activity.max_count,
+ offset,
+ months: postingActivityMonths(activity.days, offset),
+ },
+ caption: postingActivityCaption(activity),
+ });
+};
diff --git a/resources/js/lib/postingActivity.ts b/resources/js/lib/postingActivity.ts
new file mode 100644
index 000000000..94070171a
--- /dev/null
+++ b/resources/js/lib/postingActivity.ts
@@ -0,0 +1,64 @@
+import {
+ IconCrownFilled,
+ IconFlameFilled,
+ IconSendFilled,
+ type Icon,
+} from '@tabler/icons-vue';
+
+import date from '@/date';
+import dayjs from '@/dayjs';
+import { filled } from '@/lib/helpers';
+import { weekStartIndex } from '@/preferences';
+import type { PostingActivityDay } from '@/types/analytics';
+
+/** The three numbers over the grid, in the order the card and the share image show them. */
+export type PostingActivityStat = 'current_streak' | 'best_streak' | 'total';
+
+/** Each number's icon and color (a CSS color, so the share card's canvas can resolve it too). */
+export const POSTING_ACTIVITY_STAT_ICONS: Record<
+ PostingActivityStat,
+ { icon: Icon; color: string }
+> = {
+ current_streak: { icon: IconFlameFilled, color: 'var(--color-orange-500)' },
+ best_streak: { icon: IconCrownFilled, color: 'var(--color-amber-400)' },
+ total: { icon: IconSendFilled, color: 'var(--chart-3)' },
+};
+
+/** The grid's rows: one per weekday, one column per week. */
+export const DAYS_PER_WEEK = 7;
+
+/** A month's short name over the column its first day falls in. */
+export type PostingActivityMonth = { column: number; label: string };
+
+/** Empty cells before the first day, so it lands on its weekday's row in the user's week. */
+export const postingActivityOffset = (days: PostingActivityDay[]): number => {
+ const first = days[0];
+
+ if (!filled(first)) {
+ return 0;
+ }
+
+ const weekday = dayjs(first.date).day();
+
+ return (weekday - weekStartIndex() + DAYS_PER_WEEK) % DAYS_PER_WEEK;
+};
+
+/** The column each month starts in, for the labels over the grid; the page and the share card read the same ones. */
+export const postingActivityMonths = (
+ days: PostingActivityDay[],
+ offset: number,
+): PostingActivityMonth[] =>
+ days.flatMap((day, index) => {
+ const when = dayjs(day.date);
+
+ if (when.date() !== 1) {
+ return [];
+ }
+
+ return [
+ {
+ column: Math.floor((index + offset) / DAYS_PER_WEEK),
+ label: date.formatShortMonth(when.month() + 1),
+ },
+ ];
+ });
diff --git a/resources/js/lib/shareCard/frame.ts b/resources/js/lib/shareCard/frame.ts
index dca450777..22b266756 100644
--- a/resources/js/lib/shareCard/frame.ts
+++ b/resources/js/lib/shareCard/frame.ts
@@ -107,7 +107,7 @@ export const paintPanel = (context: CanvasRenderingContext2D): Box => {
const LOGO_GRID = 410;
/** The TryPost mark, the four quarters of `AppLogo.vue`. */
-const paintLogo = (context: CanvasRenderingContext2D, at: Point, size: number): void => {
+export const paintLogo = (context: CanvasRenderingContext2D, at: Point, size: number): void => {
const quarters: [string, string][] = [
['M410 109.736V410H128.863L410 109.736Z', '#3660E0'],
['M410 0H281.138L205 81.3178L410 300.264V0Z', '#855ED4'],
diff --git a/resources/js/lib/shareCard/heatmap.ts b/resources/js/lib/shareCard/heatmap.ts
new file mode 100644
index 000000000..a99d32d99
--- /dev/null
+++ b/resources/js/lib/shareCard/heatmap.ts
@@ -0,0 +1,255 @@
+import { filled } from '@/lib/helpers';
+import { ink, lightColor, muted } from '@/lib/shareCard/colors';
+import { paintIdentity } from '@/lib/shareCard/frame';
+import { paintIcon } from '@/lib/shareCard/icons';
+import { quantizeLevel } from '@/lib/shareCard/scale';
+import { widest, writeText } from '@/lib/shareCard/text';
+import { heading, IDENTITY, PANEL, sans } from '@/lib/shareCard/theme';
+import type {
+ Box,
+ Point,
+ ShareCardOptions,
+ ShareHeatmap,
+ ShareTile,
+} from '@/lib/shareCard/types';
+
+/**
+ * The posting activity card: the three numbers under the identity, and the
+ * year's grid under them, one square per day in the card's tint, the way the
+ * page draws it at twice the size.
+ */
+const HEATMAP = {
+ statsTop: 178,
+ statLabelSize: 22,
+ statFigureSize: 60,
+ statFigureGap: 66,
+ statIcon: 50,
+ statIconGap: 15,
+ statGap: 80,
+ capShare: 0.7,
+ gridTop: 300,
+ monthSize: 18,
+ monthGap: 12,
+ rows: 7,
+ gapShare: 0.2,
+ radiusShare: 0.2,
+};
+
+/** How strong each level is, lightest to strongest, like the page's four steps of one color. */
+const LEVEL_ALPHAS = [0.3, 0.55, 0.8, 1];
+
+/** The numbers' fonts and icon at `fit` of their full size, so three long figures shrink together instead of being cut. */
+type StatSizes = {
+ label: string;
+ figure: string;
+ figureSize: number;
+ icon: number;
+ iconGap: number;
+ gap: number;
+};
+
+const statSizes = (fit: number): StatSizes => ({
+ label: sans(500, HEATMAP.statLabelSize * fit),
+ figure: heading(500, HEATMAP.statFigureSize * fit),
+ figureSize: HEATMAP.statFigureSize * fit,
+ icon: HEATMAP.statIcon * fit,
+ iconGap: HEATMAP.statIconGap * fit,
+ gap: HEATMAP.statGap * fit,
+});
+
+/** The room a tile's icon and its gap take before the figure; none without an icon. */
+const iconWidth = (tile: ShareTile, sizes: StatSizes): number => {
+ if (!filled(tile.icon)) {
+ return 0;
+ }
+
+ return sizes.icon + sizes.iconGap;
+};
+
+/** The width a tile takes: its label or its icon and figure, whichever is wider. */
+const statWidth = (
+ context: CanvasRenderingContext2D,
+ tile: ShareTile,
+ sizes: StatSizes,
+): number => {
+ context.font = sizes.label;
+
+ const label = context.measureText(tile.label).width;
+
+ context.font = sizes.figure;
+
+ return Math.max(
+ label,
+ iconWidth(tile, sizes) + context.measureText(tile.figure).width,
+ );
+};
+
+/** How much the numbers shrink so all of them fit the panel's width; never grown past their full size. */
+const statsFit = (
+ context: CanvasRenderingContext2D,
+ tiles: ShareTile[],
+ width: number,
+): number => {
+ const full = statSizes(1);
+ const needed =
+ tiles.reduce(
+ (total, tile) => total + statWidth(context, tile, full),
+ 0,
+ ) +
+ full.gap * Math.max(tiles.length - 1, 0);
+
+ if (needed <= width) {
+ return 1;
+ }
+
+ return width / needed;
+};
+
+/** A tile's icon, centred on its figure's capitals. */
+const paintStatIcon = (
+ context: CanvasRenderingContext2D,
+ tile: ShareTile,
+ sizes: StatSizes,
+ at: Point,
+): void => {
+ if (!filled(tile.icon)) {
+ return;
+ }
+
+ paintIcon(
+ context,
+ tile.icon.icon,
+ lightColor(tile.icon.color),
+ {
+ x: at.x,
+ y:
+ at.y -
+ (sizes.figureSize * HEATMAP.capShare) / 2 -
+ sizes.icon / 2,
+ },
+ sizes.icon,
+ );
+};
+
+/** The numbers one after another, label over icon and figure, like the page's stats, shrunk together when they would not fit. */
+const paintStats = (
+ context: CanvasRenderingContext2D,
+ options: ShareCardOptions,
+ inner: Box,
+): void => {
+ const sizes = statSizes(statsFit(context, options.tiles, inner.width));
+ const figureY = inner.y + HEATMAP.statFigureGap;
+ let left = inner.x;
+
+ options.tiles.forEach((tile) => {
+ writeText(
+ context,
+ tile.label,
+ { x: left, y: inner.y },
+ { font: sizes.label, color: muted() },
+ );
+ paintStatIcon(context, tile, sizes, { x: left, y: figureY });
+ writeText(
+ context,
+ tile.figure,
+ { x: left + iconWidth(tile, sizes), y: figureY },
+ { font: sizes.figure, color: ink() },
+ );
+
+ left += statWidth(context, tile, sizes) + sizes.gap;
+ });
+};
+
+/** The year's squares: the widest square that fits the panel, every week a column, month names over the weeks they start in. */
+const paintGrid = (
+ context: CanvasRenderingContext2D,
+ heatmap: ShareHeatmap,
+ color: string,
+ area: Box,
+): void => {
+ const columns = Math.ceil(
+ (heatmap.counts.length + heatmap.offset) / HEATMAP.rows,
+ );
+ const stride = Math.min(area.width / columns, area.height / HEATMAP.rows);
+ const top = area.y + area.height - stride * HEATMAP.rows;
+ const gap = stride * HEATMAP.gapShare;
+ const cell = stride - gap;
+ const empty = lightColor('var(--muted)');
+ const monthFont = sans(500, HEATMAP.monthSize);
+
+ const gridRight = area.x + columns * stride - gap;
+
+ heatmap.months.forEach((month) => {
+ const labelWidth = widest(context, [month.label], monthFont);
+
+ writeText(
+ context,
+ month.label,
+ {
+ x: Math.min(
+ area.x + month.column * stride,
+ gridRight - labelWidth,
+ ),
+ y: top - HEATMAP.monthGap,
+ },
+ { font: monthFont, color: muted() },
+ );
+ });
+
+ heatmap.counts.forEach((count, index) => {
+ const slot = index + heatmap.offset;
+ const x = area.x + Math.floor(slot / HEATMAP.rows) * stride;
+ const y = top + (slot % HEATMAP.rows) * stride;
+
+ context.beginPath();
+ context.roundRect(x, y, cell, cell, cell * HEATMAP.radiusShare);
+ context.globalAlpha = 1;
+ context.fillStyle = empty;
+
+ if (count > 0) {
+ context.globalAlpha =
+ LEVEL_ALPHAS[
+ quantizeLevel(count, heatmap.maxCount, LEVEL_ALPHAS.length)
+ ];
+ context.fillStyle = color;
+ }
+
+ context.fill();
+ });
+
+ context.globalAlpha = 1;
+};
+
+export const paintHeatmapCard = (
+ context: CanvasRenderingContext2D,
+ options: ShareCardOptions,
+ panel: Box,
+): void => {
+ const inner = {
+ x: panel.x + PANEL.padding,
+ width: panel.width - PANEL.padding * 2,
+ };
+
+ paintIdentity(
+ context,
+ options.subject,
+ `${options.label} · ${options.range}`,
+ { x: inner.x, y: panel.y + IDENTITY.top },
+ inner.width,
+ );
+ paintStats(context, options, {
+ ...inner,
+ y: panel.y + HEATMAP.statsTop,
+ height: 0,
+ });
+
+ if (!filled(options.heatmap)) {
+ return;
+ }
+
+ paintGrid(context, options.heatmap, options.tint.strong, {
+ ...inner,
+ y: panel.y + HEATMAP.gridTop,
+ height: panel.height - HEATMAP.gridTop - PANEL.padding,
+ });
+};
diff --git a/resources/js/lib/shareCard/icons.ts b/resources/js/lib/shareCard/icons.ts
index f1ec18313..a282db3b4 100644
--- a/resources/js/lib/shareCard/icons.ts
+++ b/resources/js/lib/shareCard/icons.ts
@@ -1,6 +1,8 @@
import type { Icon } from '@tabler/icons-vue';
import type { VNode } from 'vue';
+import type { Point } from '@/lib/shareCard/types';
+
/** A Tabler icon's paths on its 24px grid, read from the same component the page renders, so the card draws the same icon. */
export const iconPaths = (icon: Icon): string[] => {
const svg = icon({}, { attrs: {}, slots: {}, emit: () => {} }) as VNode;
@@ -8,3 +10,13 @@ export const iconPaths = (icon: Icon): string[] => {
return children.filter((child) => child.type === 'path').map((child) => child.props?.d);
};
+
+/** Fills a Tabler icon at `at` (its top left corner), `size` pixels square, in a color the canvas can draw. */
+export const paintIcon = (context: CanvasRenderingContext2D, icon: Icon, color: string, at: Point, size: number): void => {
+ context.save();
+ context.translate(at.x, at.y);
+ context.scale(size / 24, size / 24);
+ context.fillStyle = color;
+ iconPaths(icon).forEach((path) => context.fill(new Path2D(path)));
+ context.restore();
+};
diff --git a/resources/js/lib/shareCard/images.ts b/resources/js/lib/shareCard/images.ts
index fef00539b..bf4d80f7c 100644
--- a/resources/js/lib/shareCard/images.ts
+++ b/resources/js/lib/shareCard/images.ts
@@ -29,12 +29,13 @@ const optionText = (option: Partial<ShareCardOptions> & Pick<ShareMetricOption,
...option.lines.map((line) => line.figure),
...(option.series ?? []).flatMap((series) => [series.label, series.figure, series.previousFigure]),
...(option.tiles ?? []).flatMap((tile) => [tile.label, tile.figure]),
+ ...(option.heatmap?.months ?? []).map((month) => month.label),
]
.filter((text): text is string => Boolean(text))
.join(' ');
/** Canvas draws in the fallback face unless the page's fonts are loaded first, with the glyphs the card writes. */
-const loadFonts = async (text: string): Promise<void> => {
+export const loadFonts = async (text: string): Promise<void> => {
if (!('fonts' in document)) {
return;
}
diff --git a/resources/js/lib/shareCard/index.ts b/resources/js/lib/shareCard/index.ts
index 1bf9eed4f..2b462ac27 100644
--- a/resources/js/lib/shareCard/index.ts
+++ b/resources/js/lib/shareCard/index.ts
@@ -4,7 +4,7 @@
* same in every browser and needs no dependency. Every image it draws loads
* with CORS: one that does not would stop the canvas exporting.
*
- * Each shape has its painter (`lines`, `rows`, `stacked`, `combo`, `summary`)
+ * Each shape has its painter (`lines`, `rows`, `stacked`, `combo`, `summary`, `heatmap`)
* on the shared frame, text, drawing and channel helpers; `scale` and `curve`
* hold the pure arithmetic the painters share with the page's charts.
*/
@@ -14,6 +14,7 @@ import { canvasToFile } from '@/lib/canvasFile';
import { lightColor } from '@/lib/shareCard/colors';
import { paintCombo } from '@/lib/shareCard/combo';
import { paintGround, paintMark, paintPanel } from '@/lib/shareCard/frame';
+import { paintHeatmapCard } from '@/lib/shareCard/heatmap';
import { prepareShareCard } from '@/lib/shareCard/images';
import { paintLinesCard } from '@/lib/shareCard/lines';
import { paintRowsCard } from '@/lib/shareCard/rows';
@@ -28,6 +29,7 @@ export { SHARE_CARD_SIZE, SHARE_TINTS, type ShareTint } from '@/lib/shareCard/th
export type {
ShareCardOptions,
ShareChannel,
+ ShareHeatmap,
ShareLine,
ShareMetricOption,
SharePoint,
@@ -43,6 +45,7 @@ const PAINTERS: Record<ShareShape, (context: CanvasRenderingContext2D, options:
stacked: (context, options, _images, panel) => paintStackedCard(context, options, panel),
combo: (context, options, _images, panel) => paintCombo(context, options, panel),
tiles: (context, options, _images, panel) => paintSummary(context, options, panel),
+ heatmap: (context, options, _images, panel) => paintHeatmapCard(context, options, panel),
};
/**
diff --git a/resources/js/lib/shareCard/scale.ts b/resources/js/lib/shareCard/scale.ts
index 8f20bdc1e..215582215 100644
--- a/resources/js/lib/shareCard/scale.ts
+++ b/resources/js/lib/shareCard/scale.ts
@@ -147,3 +147,18 @@ export const fittingColumns = (count: number, fitting: number): number[] => {
return Array.from({ length: count }, (_, index) => index).filter((index) => index % step === 0);
};
+
+/**
+ * The step a day's count takes among `levels` steps from one post to the
+ * busiest day, as d3's `scaleQuantize` over `[1, maxCount]` (the page's
+ * heatmap scale) picks it; a busiest day of one post puts every day on the top step.
+ */
+export const quantizeLevel = (count: number, maxCount: number, levels: number): number => {
+ if (maxCount <= 1) {
+ return levels - 1;
+ }
+
+ const step = Math.floor(((count - 1) / (maxCount - 1)) * levels);
+
+ return Math.min(levels - 1, step);
+};
diff --git a/resources/js/lib/shareCard/types.ts b/resources/js/lib/shareCard/types.ts
index 41ba7fd84..7f71487bb 100644
--- a/resources/js/lib/shareCard/types.ts
+++ b/resources/js/lib/shareCard/types.ts
@@ -1,11 +1,13 @@
+import type { Icon } from '@tabler/icons-vue';
+
import type { ChartMode, MetricDelta } from '@/lib/channelMetrics';
import type { ShareTint } from '@/lib/shareCard/theme';
import type { SeriesMetric } from '@/types/analytics';
import type { VerifiedBadge } from '@/types/social-account';
-/** One line per channel, the channel chart, columns split by channel over time, one bar per channel, or the Summary's numbers. */
-export type ShareShape = 'lines' | 'combo' | 'stacked' | 'rows' | 'tiles';
+/** One line per channel, the channel chart, columns split by channel over time, one bar per channel, the Summary's numbers, or the posting activity grid. */
+export type ShareShape = 'lines' | 'combo' | 'stacked' | 'rows' | 'tiles' | 'heatmap';
/** The channel a `rows` bar belongs to, drawn next to its name like the page's chart. */
export type ShareChannel = {
@@ -62,11 +64,26 @@ export type ShareSeries = {
/** The images a card draws, loaded before painting: a canvas only draws images already loaded. */
export type ShareImages = ReadonlyMap<string, HTMLImageElement>;
+/** The icon drawn before a tile's figure, in a CSS color. */
+export type ShareTileIcon = { icon: Icon; color: string };
+
/** One number of the Summary, as its card prints it; `missing` while the metric has no value, which the card draws muted and the post leaves out. */
-export type ShareTile = { label: string; figure: string; missing: boolean; change: MetricDelta | null };
+export type ShareTile = { label: string; figure: string; missing: boolean; change: MetricDelta | null; icon?: ShareTileIcon };
+
+/**
+ * The posting activity grid for `heatmap`: one count per day, oldest first,
+ * filled column by column (one column per week) after `offset` empty cells.
+ */
+export type ShareHeatmap = {
+ counts: number[];
+ maxCount: number;
+ offset: number;
+ /** The column each month starts in, with its short name. */
+ months: { column: number; label: string }[];
+};
-/** What a share option draws, which names its file: one metric of a series, the channel's chart, or the whole Summary. */
-type ShareMetricKey = SeriesMetric | 'channel' | 'summary';
+/** What a share option draws, which names its file: one metric of a series, the channel's chart, the whole Summary, or the posting activity. */
+type ShareMetricKey = SeriesMetric | 'channel' | 'summary' | 'posting_activity';
/** One metric a share dialog can draw, with the post text it opens the composer with. */
export type ShareMetricOption = {
@@ -84,6 +101,8 @@ export type ShareMetricOption = {
series: ShareSeries[];
/** The periods `combo` shows, as the page's chart toggle sets them. */
chartMode: ChartMode;
+ /** The posting activity grid, for `heatmap`. */
+ heatmap: ShareHeatmap | null;
caption: string;
};
diff --git a/resources/js/lib/streakShareImage.ts b/resources/js/lib/streakShareImage.ts
new file mode 100644
index 000000000..a7575cfea
--- /dev/null
+++ b/resources/js/lib/streakShareImage.ts
@@ -0,0 +1,254 @@
+/**
+ * The image a posting streak shares: the streak popover's band art (violet,
+ * a light blob, a darker wedge and white and dark confetti) as the whole
+ * background, with translucent tiles over it, the number in the largest one,
+ * the unit and a line under it, signed with the TryPost logo. Drawn on a
+ * canvas like the Insights share cards.
+ */
+
+import { canvasToFile } from '@/lib/canvasFile';
+import { filled } from '@/lib/helpers';
+import { POSTING_ACTIVITY_STAT_ICONS } from '@/lib/postingActivity';
+import { lightColor } from '@/lib/shareCard/colors';
+import { paintLogo } from '@/lib/shareCard/frame';
+import { paintIcon } from '@/lib/shareCard/icons';
+import { loadFonts } from '@/lib/shareCard/images';
+import { writeText } from '@/lib/shareCard/text';
+import { heading, sans } from '@/lib/shareCard/theme';
+import type { ShareTileIcon } from '@/lib/shareCard/types';
+
+/** A 4:5 portrait, the size feeds show whole. */
+const SIZE = { width: 1080, height: 1350 };
+
+/** The popover band's colors, as Tailwind draws them. */
+const COLORS = {
+ ground: '#ede9fe',
+ blob: '#f5f3ff',
+ wedge: '#c4b5fd',
+ tile: 'rgba(255, 255, 255, 0.55)',
+ ink: '#1f1633',
+ muted: '#4c4466',
+ dots: { light: '#a78bfa', white: '#ffffff', dark: '#2e1065' },
+};
+
+/** The confetti over the background: left, top and diameter of each dot. */
+const DOTS: { x: number; y: number; size: number; color: string }[] = [
+ { x: 60, y: 300, size: 18, color: COLORS.dots.light },
+ { x: 210, y: 520, size: 26, color: COLORS.dots.white },
+ { x: 650, y: 40, size: 18, color: COLORS.dots.dark },
+ { x: 1000, y: 330, size: 26, color: COLORS.dots.dark },
+ { x: 860, y: 760, size: 18, color: COLORS.dots.white },
+ { x: 120, y: 1100, size: 22, color: COLORS.dots.dark },
+ { x: 940, y: 1080, size: 22, color: COLORS.dots.white },
+ { x: 300, y: 1210, size: 16, color: COLORS.dots.light },
+];
+
+/** The small tiles around the number, some with the posting activity's icons. */
+const TILES: { x: number; y: number; icon?: ShareTileIcon }[] = [
+ { x: 70, y: 70 },
+ { x: 270, y: 70, icon: POSTING_ACTIVITY_STAT_ICONS.current_streak },
+ { x: 70, y: 320, icon: POSTING_ACTIVITY_STAT_ICONS.best_streak },
+ { x: 990, y: 70 },
+ { x: 800, y: 320 },
+ { x: 800, y: 530, icon: POSTING_ACTIVITY_STAT_ICONS.total },
+ { x: -80, y: 530 },
+];
+
+const TILE = { size: 170, radius: 36, icon: 84 };
+
+const NUMBER_TILE = { x: 320, y: 300, size: 440, radius: 64 };
+
+const paintBackground = (context: CanvasRenderingContext2D): void => {
+ context.fillStyle = COLORS.ground;
+ context.fillRect(0, 0, SIZE.width, SIZE.height);
+
+ context.beginPath();
+ context.ellipse(140, 60, 420, 260, 0, 0, Math.PI * 2);
+ context.fillStyle = COLORS.blob;
+ context.fill();
+
+ const { width, height } = SIZE;
+
+ context.beginPath();
+ context.moveTo(width * 0.64, 0);
+ context.lineTo(width, 0);
+ context.lineTo(width, height);
+ context.lineTo(width * 0.56, height);
+ context.bezierCurveTo(
+ width * 0.44,
+ height * 0.82,
+ width * 0.66,
+ height * 0.62,
+ width * 0.58,
+ height * 0.46,
+ );
+ context.bezierCurveTo(
+ width * 0.5,
+ height * 0.3,
+ width * 0.72,
+ height * 0.14,
+ width * 0.64,
+ 0,
+ );
+ context.closePath();
+ context.fillStyle = COLORS.wedge;
+ context.fill();
+
+ DOTS.forEach((dot) => {
+ context.beginPath();
+ context.arc(
+ dot.x + dot.size / 2,
+ dot.y + dot.size / 2,
+ dot.size / 2,
+ 0,
+ Math.PI * 2,
+ );
+ context.fillStyle = dot.color;
+ context.fill();
+ });
+};
+
+const paintTiles = (context: CanvasRenderingContext2D): void => {
+ TILES.forEach((tile) => {
+ context.beginPath();
+ context.roundRect(tile.x, tile.y, TILE.size, TILE.size, TILE.radius);
+ context.fillStyle = COLORS.tile;
+ context.fill();
+
+ if (!filled(tile.icon)) {
+ return;
+ }
+
+ const inset = (TILE.size - TILE.icon) / 2;
+
+ paintIcon(
+ context,
+ tile.icon.icon,
+ lightColor(tile.icon.color),
+ { x: tile.x + inset, y: tile.y + inset },
+ TILE.icon,
+ );
+ });
+};
+
+/** Three digits shrink so the number stays inside its tile. */
+const numberSize = (weeks: number): number => {
+ if (weeks >= 100) {
+ return 230;
+ }
+
+ return 300;
+};
+
+const paintNumber = (
+ context: CanvasRenderingContext2D,
+ weeks: number,
+ number: string,
+): void => {
+ context.beginPath();
+ context.roundRect(
+ NUMBER_TILE.x,
+ NUMBER_TILE.y,
+ NUMBER_TILE.size,
+ NUMBER_TILE.size,
+ NUMBER_TILE.radius,
+ );
+ context.fillStyle = COLORS.tile;
+ context.fill();
+
+ writeText(
+ context,
+ number,
+ {
+ x: NUMBER_TILE.x + NUMBER_TILE.size / 2,
+ y: NUMBER_TILE.y + NUMBER_TILE.size / 2 + 12,
+ },
+ {
+ font: heading(600, numberSize(weeks)),
+ color: COLORS.ink,
+ align: 'center',
+ baseline: 'middle',
+ },
+ );
+};
+
+const paintTexts = (
+ context: CanvasRenderingContext2D,
+ unit: string,
+ tagline: string,
+): void => {
+ writeText(
+ context,
+ unit,
+ { x: SIZE.width / 2, y: 900 },
+ {
+ font: heading(600, 170),
+ color: COLORS.ink,
+ align: 'center',
+ },
+ );
+ writeText(
+ context,
+ tagline,
+ { x: SIZE.width / 2, y: 990 },
+ {
+ font: sans(500, 52),
+ color: COLORS.muted,
+ align: 'center',
+ },
+ );
+};
+
+const paintSignature = (context: CanvasRenderingContext2D): void => {
+ const logo = 60;
+ const font = heading(600, 46);
+
+ context.font = font;
+
+ const width = logo + 16 + context.measureText('TryPost').width;
+ const left = (SIZE.width - width) / 2;
+ const centre = SIZE.height - 150;
+
+ paintLogo(context, { x: left, y: centre - logo / 2 }, logo);
+ writeText(
+ context,
+ 'TryPost',
+ { x: left + logo + 16, y: centre + 2 },
+ {
+ font,
+ color: COLORS.ink,
+ baseline: 'middle',
+ },
+ );
+};
+
+/** The streak image as a PNG file, named after the streak: `trypost-streak-20-weeks.png`. */
+export const streakShareFile = async (
+ weeks: number,
+ texts: { number: string; unit: string; tagline: string },
+): Promise<File> => {
+ await loadFonts(`${texts.number} ${texts.unit} ${texts.tagline} TryPost`);
+
+ const canvas = document.createElement('canvas');
+
+ canvas.width = SIZE.width;
+ canvas.height = SIZE.height;
+
+ const context = canvas.getContext('2d');
+
+ if (!filled(context)) {
+ throw new Error('Canvas is not available');
+ }
+
+ paintBackground(context);
+ paintTiles(context);
+ paintNumber(context, weeks, texts.number);
+ paintTexts(context, texts.unit, texts.tagline);
+ paintSignature(context);
+
+ return canvasToFile(
+ canvas,
+ `trypost-streak-${weeks}-weeks.png`,
+ 'image/png',
+ );
+};
diff --git a/resources/js/lib/toastLink.ts b/resources/js/lib/toastLink.ts
new file mode 100644
index 000000000..6bc00765f
--- /dev/null
+++ b/resources/js/lib/toastLink.ts
@@ -0,0 +1,39 @@
+import { filled } from '@/lib/helpers';
+
+/** A link a toast offers next to its message: "View post" and where it goes. */
+export type ToastLink = {
+ label: string;
+ url: string;
+};
+
+/** The options a toast takes for its link; both stay as keys without one, so they clear a toast still on screen. */
+export type ToastLinkOptions = {
+ action: { label: string; onClick: () => void } | undefined;
+ classes: { toast: string; content: string } | undefined;
+};
+
+/**
+ * What a toast adds when the flash carries a link: the link right after the
+ * message, in a toast as wide as both. Without a link both options are still
+ * set, to nothing: a toast on screen under the same id keeps every option it
+ * is not given, so leaving them out would keep the previous toast's link.
+ */
+export const toastLinkOptions = (
+ link: ToastLink | undefined,
+ visit: (url: string) => void,
+): ToastLinkOptions => {
+ if (!filled(link)) {
+ return { action: undefined, classes: undefined };
+ }
+
+ return {
+ action: {
+ label: link.label,
+ onClick: () => visit(link.url),
+ },
+ classes: {
+ toast: '!inset-x-0 !mx-auto !w-fit !max-w-(--width)',
+ content: '!grow-0',
+ },
+ };
+};
diff --git a/resources/js/pages/channels/Insights.vue b/resources/js/pages/channels/Insights.vue
index 4ab433640..d2437b8be 100644
--- a/resources/js/pages/channels/Insights.vue
+++ b/resources/js/pages/channels/Insights.vue
@@ -9,6 +9,7 @@ import ChannelPublicationTable from '@/components/analytics/channel/ChannelPubli
import PostTypeFilter from '@/components/analytics/channel/PostTypeFilter.vue';
import InsightsExportMenu from '@/components/analytics/InsightsExportMenu.vue';
import InsightsSyncStatus from '@/components/analytics/InsightsSyncStatus.vue';
+import PostingActivityCard from '@/components/analytics/PostingActivityCard.vue';
import ImportCoverage from '@/components/analytics/workspace/ImportCoverage.vue';
import SummaryCards from '@/components/analytics/workspace/SummaryCards.vue';
import EmptyState from '@/components/EmptyState.vue';
@@ -27,6 +28,7 @@ import type {
ChannelPublicationPage,
ContentTypeOption,
InsightsSyncCadence,
+ PostingActivity,
SummaryMetric,
} from '@/types/analytics';
import { channelName } from '@/types/channel';
@@ -44,11 +46,18 @@ const props = defineProps<{
labels?: { id: string; name: string; color: string }[];
contentTypes?: ContentTypeOption[];
metricSeries?: ChannelMetricSeries;
+ postingActivity?: PostingActivity;
}>();
useAnalyticsCoveragePoll(() => props.report?.coverage, {
firstDay: () => props.report?.bounds.min,
- only: ['availableMetrics', 'publications', 'filters', 'metricSeries'],
+ only: [
+ 'availableMetrics',
+ 'publications',
+ 'filters',
+ 'metricSeries',
+ 'postingActivity',
+ ],
});
const url = computed(() => insights.url(props.channel.id));
@@ -271,6 +280,10 @@ watch(selectedTypes, applyFilters, { deep: true });
:series="metricSeries"
:channel="shareChannel"
/>
+ <PostingActivityCard
+ :activity="postingActivity"
+ :channel="shareChannel"
+ />
</template>
</template>
</div>
diff --git a/resources/js/pages/insights/Index.vue b/resources/js/pages/insights/Index.vue
index 0f65b3f4a..ae6059ddb 100644
--- a/resources/js/pages/insights/Index.vue
+++ b/resources/js/pages/insights/Index.vue
@@ -6,6 +6,7 @@ import { computed, ref, watch } from 'vue';
import AnalyticsRangePresets from '@/components/analytics/AnalyticsRangePresets.vue';
import InsightsExportMenu from '@/components/analytics/InsightsExportMenu.vue';
import InsightsSyncStatus from '@/components/analytics/InsightsSyncStatus.vue';
+import PostingActivityCard from '@/components/analytics/PostingActivityCard.vue';
import FollowersChart from '@/components/analytics/workspace/FollowersChart.vue';
import ImportCoverage from '@/components/analytics/workspace/ImportCoverage.vue';
import InsightsEmptyState from '@/components/analytics/workspace/InsightsEmptyState.vue';
@@ -26,6 +27,7 @@ import { insights as insightsRoute } from '@/routes/app';
import type {
AnalyticsChannelOption,
InsightsSyncCadence,
+ PostingActivity,
SummaryMetric,
WorkspaceAnalyticsReport,
} from '@/types/analytics';
@@ -37,6 +39,7 @@ const props = defineProps<{
labels: PostCardLabel[];
availableMetrics: SummaryMetric[] | null;
sync: InsightsSyncCadence;
+ postingActivity?: PostingActivity;
}>();
const selectedChannelIds = ref<string[]>([...props.report.filters.channels]);
@@ -138,7 +141,10 @@ watch(
{ deep: true },
);
-useAnalyticsCoveragePoll(() => props.report.coverage);
+useAnalyticsCoveragePoll(() => props.report.coverage, {
+ firstDay: () => props.report.bounds.min,
+ only: ['postingActivity'],
+});
const accountColors = computed<Record<string, string>>(() => {
const keys = [
@@ -271,6 +277,7 @@ const accountColors = computed<Record<string, string>>(() => {
:channel-filtered="channelFiltered"
:total-channels="channelOptions.length"
/>
+ <PostingActivityCard :activity="postingActivity" />
</template>
</div>
</AppLayout>
diff --git a/resources/js/pages/publish/Index.vue b/resources/js/pages/publish/Index.vue
index d21c3726c..0110d304e 100644
--- a/resources/js/pages/publish/Index.vue
+++ b/resources/js/pages/publish/Index.vue
@@ -12,7 +12,7 @@ import {
IconPlus,
IconUsers,
} from '@tabler/icons-vue';
-import { trans, transChoice } from 'laravel-vue-i18n';
+import { trans } from 'laravel-vue-i18n';
import { computed, nextTick, provide, ref, shallowRef, watch } from 'vue';
import { toast } from 'vue-sonner';
@@ -747,21 +747,7 @@ const submitComposition = (
...composition,
recover_post_id: editPost.id,
};
- router.post(storePost.url(), data, {
- ...options,
- onSuccess: () => {
- if (composition.queue) {
- const count = composition.destinations.length;
- toast.success(
- transChoice('posts.composer.queue.added', count, {
- count: String(count),
- }),
- { testId: 'queue-added-toast' },
- );
- }
- options.onSuccess();
- },
- });
+ router.post(storePost.url(), data, options);
return;
}
const destination = composition.destinations[0];
diff --git a/resources/js/types/analytics.ts b/resources/js/types/analytics.ts
index 957348205..53a937209 100644
--- a/resources/js/types/analytics.ts
+++ b/resources/js/types/analytics.ts
@@ -341,3 +341,19 @@ export interface UnsupportedPublicationAnalytics {
unsupported: true;
reason: string;
}
+
+/** Posts that went out per day over the last 365 days (`BuildPostingActivity`). */
+export interface PostingActivityDay {
+ date: string;
+ count: number;
+}
+
+export interface PostingActivity {
+ start: string;
+ end: string;
+ days: PostingActivityDay[];
+ total: number;
+ max_count: number;
+ current_streak: number;
+ best_streak: number;
+}
diff --git a/resources/js/types/index.d.ts b/resources/js/types/index.d.ts
index 0bc96f74e..756453a2e 100644
--- a/resources/js/types/index.d.ts
+++ b/resources/js/types/index.d.ts
@@ -11,6 +11,7 @@ import type {
} from '@/preferences';
import type { ScrollChangelogEntries, SharedChangelog } from '@/types/changelog';
import type { AuthPlan, Features, PlanOption } from '@/types/plan';
+import type { PostingStreak } from '@/types/posting-streak';
export type { AuthPlan, BillingInterval, Features, PlanOption } from '@/types/plan';
export type { WelcomeStep } from '@/types/welcome';
@@ -114,6 +115,7 @@ export interface SharedData {
mediaSources?: { menu: MediaSourceOption[] } | null;
referralSources?: string[] | null;
mcpPrompt?: { mcp_url: string } | null;
+ postingStreak?: PostingStreak | null;
changelog?: SharedChangelog | null;
changelogEntries?: ScrollChangelogEntries;
mediaUploadLimits?: MediaUploadLimits | null;
diff --git a/resources/js/types/posting-streak.ts b/resources/js/types/posting-streak.ts
new file mode 100644
index 000000000..b8ab5fec1
--- /dev/null
+++ b/resources/js/types/posting-streak.ts
@@ -0,0 +1,7 @@
+/** The workspace's weeks in a row with a post, shared on every page for the sidebar badge (`ShowPostingStreak`). */
+export interface PostingStreak {
+ weeks: number;
+ posted_this_week: boolean;
+ /** The smallest "Top X%" the streak reaches among every workspace, or null below the last one. */
+ top_percent: number | null;
+}
diff --git a/routes/console.php b/routes/console.php
index f2f530a4e..dbd9024a6 100644
--- a/routes/console.php
+++ b/routes/console.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
use App\Console\Commands\Analytics\DispatchAccountDailyAnalytics;
use App\Console\Commands\Analytics\DispatchPublicationDiscovery;
use App\Console\Commands\Analytics\DispatchPublicationMetrics;
+use App\Console\Commands\Analytics\RankPostingStreaks;
use App\Console\Commands\CheckSocialConnections;
use App\Console\Commands\CheckUpcomingPostConnections;
use App\Console\Commands\ProcessScheduledPosts;
@@ -32,6 +33,7 @@ Schedule::command(RecoverStuckPosts::class)->everyThirtyMinutes()->withoutOverla
Schedule::command(ReconcileGoogleBusinessPosts::class)->everyFiveMinutes()->withoutOverlapping()->onOneServer();
Schedule::command(ResolveTikTokVideoIds::class)->everyFifteenMinutes()->withoutOverlapping()->onOneServer();
Schedule::command(PruneWebhookLogs::class)->daily()->withoutOverlapping()->onOneServer();
+Schedule::command(RankPostingStreaks::class)->daily()->withoutOverlapping()->onOneServer();
Schedule::command(PruneExpiredPostHistoryCommand::class)->daily()->withoutOverlapping()->onOneServer();
Schedule::command(PruneTemporaryUploadsCommand::class)->hourly()->withoutOverlapping()->onOneServer();
Schedule::command(PollRepurposes::class)->everyFiveMinutes()->withoutOverlapping()->onOneServer();
diff --git a/tests/Browser/ComposerQueueTest.php b/tests/Browser/ComposerQueueTest.php
index eb136bb2d..3b151992f 100644
--- a/tests/Browser/ComposerQueueTest.php
+++ b/tests/Browser/ComposerQueueTest.php
@@ -318,16 +318,16 @@ test('recovering an empty-target draft into the queue confirms it with a toast',
$page->click('@composer-submit');
waitForGone($page, '@post-composer-dialog');
- waitFor($page, '@queue-added-toast');
+ waitFor($page, '@flash-success-toast');
$recovered = Post::query()->where('workspace_id', $workspace->id)->sole();
expect($recovered->id)->not->toBe($legacy->id)
->and($recovered->schedule_mode)->toBe(ScheduleMode::Queue)
- ->and($recovered->scheduled_at->toIso8601String())->toBe(composerQueueSlots($channel, 1)[0]->toIso8601String())
- ->and($page->script('document.querySelector("[data-testid=queue-added-toast]")?.textContent.trim() ?? ""'))->toContain('Added to queue');
+ ->and($recovered->scheduled_at->toIso8601String())->toBe(composerQueueSlots($channel, 1)[0]->toIso8601String());
- $page->assertNoJavaScriptErrors();
+ $page->assertSeeIn('[data-testid="flash-success-toast"]', 'Your post was added to the queue.')
+ ->assertNoJavaScriptErrors();
});
/**
@@ -437,3 +437,26 @@ test('the picker calendar starts the week on the user preference', function (Wee
'sunday' => [WeekStart::Sunday, 'S', 0],
'monday' => [WeekStart::Monday, 'M', 1],
]);
+
+test('the added-to-queue toast opens the new post details in the queue', function () {
+ [$user, $workspace] = composerQueueWorkspace();
+ $channel = composerQueueChannel($workspace, composerQueueSchedule());
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.create'));
+ composerQueueOpenWith($page, $channel);
+ waitFor($page, '@composer-submit');
+ $page->click('@composer-submit');
+ waitForGone($page, '@post-composer-dialog');
+ waitFor($page, '@flash-success-toast [data-button]');
+
+ $post = Post::query()->where('workspace_id', $workspace->id)->sole();
+
+ $page->assertSeeIn('[data-testid="flash-success-toast"] [data-button]', 'View post')
+ ->click('[data-testid="flash-success-toast"] [data-button]');
+ waitForOpen($page, "@post-details-{$post->id}");
+
+ $page->assertPathIs(route('app.posts.index', absolute: false))
+ ->assertQueryStringHas('post', $post->id)
+ ->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/PostApprovalsTest.php b/tests/Browser/PostApprovalsTest.php
index 9a64694fc..8fa8f0476 100644
--- a/tests/Browser/PostApprovalsTest.php
+++ b/tests/Browser/PostApprovalsTest.php
@@ -147,10 +147,10 @@ test('a requester adding a draft to the queue is told it awaits approval', funct
waitFor($page, "@post-add-to-queue-{$draft->id}");
$page->click("@post-add-to-queue-{$draft->id}");
- waitFor($page, '@post-schedule-toast');
+ waitFor($page, '@flash-success-toast');
- $page->assertSeeIn('@post-schedule-toast', 'Approval requested')
- ->assertDontSee('Added to queue')
+ $page->assertSeeIn('@flash-success-toast', 'Approval requested')
+ ->assertDontSee('added to the queue')
->assertNoJavaScriptErrors();
expect($draft->fresh()->status)->toBe(PostStatus::PendingApproval);
});
diff --git a/tests/Browser/PostingActivityTest.php b/tests/Browser/PostingActivityTest.php
new file mode 100644
index 000000000..5052cb264
--- /dev/null
+++ b/tests/Browser/PostingActivityTest.php
@@ -0,0 +1,227 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Analytics\PublicationContentType;
+use App\Enums\SocialAccount\Platform;
+use App\Enums\User\Locale;
+use App\Enums\User\WeekStart;
+use App\Jobs\Analytics\BootstrapAccountAnalytics;
+use App\Jobs\Analytics\CollectAccountDailySnapshot;
+use App\Models\AnalyticsPublication;
+use App\Models\AnalyticsPublicationDailySnapshot;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use Carbon\CarbonImmutable;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Facades\Storage;
+
+function postingActivityBrowserPublication(SocialAccount $account, CarbonImmutable $publishedAt, PublicationContentType $type = PublicationContentType::Image): void
+{
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'platform' => $account->platform,
+ 'network' => $account->platform->network(),
+ 'platform_user_id' => $account->platform_user_id,
+ 'content_type' => $type,
+ 'provider_published_at' => $publishedAt,
+ ]);
+ AnalyticsPublicationDailySnapshot::factory()->create([
+ 'publication_id' => $publication->id,
+ 'date' => $publishedAt->toDateString(),
+ ]);
+}
+
+beforeEach(function () {
+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
+
+ $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);
+ connectAiTo($user);
+ $this->user = $user->fresh();
+
+ $this->instagram = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);
+ $this->today = CarbonImmutable::today('UTC');
+
+ $this->actingAs($this->user);
+});
+
+test('the workspace insights page shows the posting activity card', function () {
+ foreach ([1, 2, 3] as $daysAgo) {
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays($daysAgo)->setTime(10, 0));
+ }
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@posting-activity-current_streak');
+ waitForCount($page, '@posting-activity-cell', 365);
+
+ $page->assertSeeIn('@posting-activity-current_streak', '3')
+ ->assertSeeIn('@posting-activity-best_streak', '3')
+ ->assertSeeIn('@posting-activity-total', '3')
+ ->assertNoJavaScriptErrors();
+});
+
+test('the channel insights page shows its posting activity and follows the post type filter', function () {
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(1)->setTime(10, 0), PublicationContentType::Story);
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(2)->setTime(10, 0));
+
+ $page = visit(route('app.channels.insights', $this->instagram));
+ waitForText($page, '@posting-activity-total', '2');
+
+ $page->click('@insights-post-type-filter');
+ waitFor($page, '@insights-post-type-option-instagram_story');
+ $page->click('@insights-post-type-option-instagram_story');
+ waitForText($page, '@posting-activity-total', '1');
+
+ $page->assertSeeIn('@posting-activity-current_streak', '1')
+ ->assertNoJavaScriptErrors();
+});
+
+test('the workspace card fills in when the first posts arrive after opening the page', function () {
+ $page = visit(route('app.insights'));
+ waitFor($page, '@analytics-empty-state');
+ letPageRun($page, 2000);
+
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(1)->setTime(10, 0));
+
+ waitForText($page, '@posting-activity-total', '1');
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a year without posts has nothing to share', function () {
+ postingActivityBrowserPublication($this->instagram, $this->today->subYears(2)->setTime(10, 0));
+
+ $page = visit(route('app.insights'));
+ waitForText($page, '@posting-activity-total', '0');
+
+ $page->assertMissing('@share-posting-activity')
+ ->assertNoJavaScriptErrors();
+});
+
+test('on a phone the grid opens on the latest weeks', function () {
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(1)->setTime(10, 0));
+
+ $page = visit(route('app.insights'))->on()->mobile();
+ waitFor($page, '@posting-activity-cell');
+ waitForState($page, '@posting-activity-scroller', 'element.scrollWidth > element.clientWidth && element.scrollLeft + element.clientWidth >= element.scrollWidth - 1');
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('on a phone the grid stays on older weeks the user scrolled back to when it resizes', function (Locale $locale) {
+ $this->user->update(['locale' => $locale]);
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(1)->setTime(10, 0));
+
+ $page = visit(route('app.insights'))->on()->mobile();
+ waitForState($page, '@posting-activity-scroller', 'element.scrollWidth > element.clientWidth && element.scrollLeft + element.clientWidth >= element.scrollWidth - 1');
+
+ onElement($page, '@posting-activity-scroller', 'element.scrollLeft = 0');
+ waitForState($page, '@posting-activity-scroller', 'element.scrollLeft === 0');
+ onElement($page, '@posting-activity-heatmap', 'element.style.paddingRight = "24px"');
+ letPageRun($page, 500);
+ waitForState($page, '@posting-activity-scroller', 'element.scrollLeft === 0');
+
+ $page->assertNoJavaScriptErrors();
+})->with([
+ 'left to right' => [Locale::English],
+ 'right to left' => [Locale::Arabic],
+]);
+
+test('hovering a day shows its posts and the day', function () {
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(1)->setTime(10, 0));
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(1)->setTime(12, 0));
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@posting-activity-cell');
+ $page->hover('[data-testid="posting-activity-cell"]:nth-of-type(364)');
+ waitForText($page, '@posting-activity-tooltip', '2 posts');
+
+ $page->assertSeeIn('@posting-activity-tooltip', $this->today->subDays(1)->format('j'))
+ ->assertNoJavaScriptErrors();
+});
+
+test('the workspace posting activity shares as a card that turns into a post', function () {
+ Storage::fake();
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(1)->setTime(10, 0));
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@share-posting-activity');
+ $page->click('@share-posting-activity');
+ waitForState($page, '@share-chart-preview', "element.dataset.state === 'ready'");
+
+ $page->assertAttribute('@share-chart-preview', 'data-shape', 'heatmap')
+ ->click('@share-chart-post');
+ waitForState($page, '@composer-base-content', "element.value === '🔥 1 day in a row posting, our longest streak yet! 1 post in the last 12 months.'");
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a channel under its record shares a post that names the record', function () {
+ Storage::fake();
+
+ foreach ([1, 2, 5, 6, 7] as $daysAgo) {
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays($daysAgo)->setTime(10, 0));
+ }
+
+ $page = visit(route('app.channels.insights', $this->instagram));
+ waitFor($page, '@share-posting-activity');
+ $page->click('@share-posting-activity');
+ waitForState($page, '@share-chart-preview', "element.dataset.state === 'ready'");
+ $page->click('@share-chart-post');
+ waitForState($page, '@composer-base-content', "element.value === '🔥 2 days in a row posting. Our record is 3 days, with 5 posts in the last 12 months.'");
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('without a streak today the post leads with the year', function () {
+ Storage::fake();
+
+ foreach ([3, 4] as $daysAgo) {
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays($daysAgo)->setTime(10, 0));
+ }
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@share-posting-activity');
+ $page->click('@share-posting-activity');
+ waitForState($page, '@share-chart-preview', "element.dataset.state === 'ready'");
+ $page->click('@share-chart-post');
+ waitForState($page, '@composer-base-content', "element.value === '📅 2 posts in the last 12 months, and a longest streak of 2 days in a row.'");
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('today lands on its weekday row in the week the user starts on', function (WeekStart $weekStart, int $firstWeekday) {
+ $this->user->update(['week_starts_on' => $weekStart]);
+ postingActivityBrowserPublication($this->instagram, $this->today->setTime(10, 0));
+
+ $page = visit(route('app.insights'));
+ waitForCount($page, '@posting-activity-cell', 365);
+
+ $tops = collect(elementsMap($page, '@posting-activity-cell', 'Math.round(element.getBBox().y)'));
+ $row = $tops->unique()->sort()->values()->search($tops->last());
+
+ expect($row)->toBe(($this->today->dayOfWeek - $firstWeekday + 7) % 7);
+ $page->assertNoJavaScriptErrors();
+})->with([
+ 'sunday' => [WeekStart::Sunday, 0],
+ 'monday' => [WeekStart::Monday, 1],
+]);
+
+test('the channel card fills in when the first posts arrive after opening the page', function () {
+ $page = visit(route('app.channels.insights', $this->instagram));
+ waitFor($page, '@insights-no-data');
+ letPageRun($page, 2000);
+
+ postingActivityBrowserPublication($this->instagram, $this->today->subDays(1)->setTime(10, 0));
+
+ waitForText($page, '@posting-activity-total', '1');
+
+ $page->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/PostingStreakTest.php b/tests/Browser/PostingStreakTest.php
new file mode 100644
index 000000000..65ed00c32
--- /dev/null
+++ b/tests/Browser/PostingStreakTest.php
@@ -0,0 +1,195 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Actions\Analytics\RankPostingStreaks;
+use App\Enums\SocialAccount\Platform;
+use App\Enums\User\WeekStart;
+use App\Jobs\Analytics\BootstrapAccountAnalytics;
+use App\Jobs\Analytics\CollectAccountDailySnapshot;
+use App\Models\AnalyticsPublication;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use Carbon\CarbonImmutable;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Facades\Storage;
+
+function postingStreakBrowserWeeks(SocialAccount $account, array $weeksAgo): void
+{
+ $thisWeek = CarbonImmutable::now('UTC')->startOfWeek(CarbonImmutable::MONDAY);
+
+ foreach ($weeksAgo as $ago) {
+ AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'network' => $account->platform->network(),
+ 'platform_user_id' => $account->platform_user_id,
+ 'platform' => $account->platform,
+ 'provider_published_at' => $thisWeek->subWeeks($ago),
+ ]);
+ }
+}
+
+beforeEach(function () {
+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
+ Storage::fake();
+
+ $user = User::factory()->create(['timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+ $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);
+ connectAiTo($user);
+ $this->user = $user->fresh();
+ $this->instagram = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);
+
+ $this->actingAs($this->user);
+});
+
+test('the sidebar shows no streak badge without a streak', function () {
+ $page = visit(route('app.insights'));
+ waitFor($page, '@sidebar-logo');
+
+ $page->assertMissing('@posting-streak-badge')
+ ->assertNoJavaScriptErrors();
+});
+
+test('the sidebar badge opens the streak and its nudge', function () {
+ postingStreakBrowserWeeks($this->instagram, [0, 1, 2]);
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@posting-streak-badge');
+ $page->assertSeeIn('@posting-streak-count', '3')
+ ->click('@posting-streak-badge');
+ waitForOpen($page, '@posting-streak-popover');
+
+ $page->assertSeeIn('@posting-streak-title', '3 week streak')
+ ->assertSeeIn('@posting-streak-nudge', 'Schedule a post for next week')
+ ->assertNoJavaScriptErrors();
+});
+
+test('opening the streak focuses the popover, never the rank and its tooltip', function () {
+ postingStreakBrowserWeeks($this->instagram, [0, 1, 2]);
+
+ foreach (range(1, RankPostingStreaks::MIN_RANKED - 1) as $_) {
+ subscribeAccount(Workspace::factory()->create()->account);
+ }
+
+ app(RankPostingStreaks::class)->execute();
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@posting-streak-badge');
+ $page->keys('@posting-streak-badge', 'Enter');
+ waitForOpen($page, '@posting-streak-popover');
+ waitFor($page, '@posting-streak-rank');
+ waitForState($page, '@posting-streak-popover', 'element === document.activeElement');
+ letPageRun($page, 500);
+
+ expect(elementsMap($page, '@posting-streak-rank-tooltip', 'element.dataset.testid'))->toBeEmpty();
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a streak without a post this week asks for one this week', function () {
+ postingStreakBrowserWeeks($this->instagram, [1, 2]);
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@posting-streak-badge');
+ $page->click('@posting-streak-badge');
+ waitForOpen($page, '@posting-streak-popover');
+
+ $page->assertSeeIn('@posting-streak-nudge', "You haven't posted this week yet")
+ ->assertNoJavaScriptErrors();
+});
+
+test('schedule post opens the composer', function () {
+ postingStreakBrowserWeeks($this->instagram, [0]);
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@posting-streak-badge');
+ $page->click('@posting-streak-badge');
+ waitForOpen($page, '@posting-streak-popover');
+ $page->click('@posting-streak-schedule');
+ waitForOpen($page, '@post-composer-dialog');
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('sharing the streak opens the composer with its post and image', function () {
+ postingStreakBrowserWeeks($this->instagram, [0, 1]);
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@posting-streak-badge');
+ $page->click('@posting-streak-badge');
+ waitForOpen($page, '@posting-streak-popover');
+ $page->click('@posting-streak-share');
+ waitForState($page, '@composer-base-content', "element.value === \"I've reached a 2-week posting streak with TryPost!\"");
+ waitForCount($page, '@composer-media-item', 1);
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('closing the streak while its image uploads leaves the page as it is', function (string $upload) {
+ postingStreakBrowserWeeks($this->instagram, [0, 1]);
+
+ $page = visit(route('app.insights'));
+ waitFor($page, '@posting-streak-badge');
+ $uploadPath = json_encode(route('app.media.store-chunked', absolute: false));
+ $page->script("(() => {
+ const uploadPath = {$uploadPath};
+ const open = XMLHttpRequest.prototype.open;
+ const send = XMLHttpRequest.prototype.send;
+ const held = [];
+ window.__heldUploads = held;
+ window.__releaseUploads = (outcome) => {
+ XMLHttpRequest.prototype.send = send;
+ held.forEach(({ request, body }) => {
+ if (outcome === 'fails') {
+ request.dispatchEvent(new ProgressEvent('error'));
+
+ return;
+ }
+
+ send.apply(request, body);
+ });
+ };
+ XMLHttpRequest.prototype.open = function (method, url, ...rest) {
+ this.heldUpload = String(url).includes(uploadPath);
+
+ return open.call(this, method, url, ...rest);
+ };
+ XMLHttpRequest.prototype.send = function (...body) {
+ if (!this.heldUpload) {
+ return send.apply(this, body);
+ }
+
+ held.push({ request: this, body });
+ };
+ })()");
+ $page->click('@posting-streak-badge');
+ waitForOpen($page, '@posting-streak-popover');
+ $page->click('@posting-streak-share');
+ waitForCondition($page, 'window.__heldUploads.length > 0');
+ $page->keys('@posting-streak-popover', 'Escape');
+ waitForGone($page, '@posting-streak-popover');
+ $page->script("window.__releaseUploads('{$upload}')");
+ letPageRun($page, 3000);
+
+ expect(elementsMap($page, '@post-composer-dialog, @posting-streak-share-error', 'element.dataset.testid'))->toBeEmpty();
+
+ $page->assertNoJavaScriptErrors();
+})->with(['the upload succeeds' => 'succeeds', 'the upload fails' => 'fails']);
+
+test('the badge hides while the sidebar is collapsed', function () {
+ postingStreakBrowserWeeks($this->instagram, [0]);
+
+ $page = visit(route('app.insights'))->resize(1280, 900);
+ waitFor($page, '@posting-streak-badge');
+ $page->click('@sidebar-footer-toggle');
+ waitForState($page, '[data-slot="sidebar"][data-state]', "element.dataset.state === 'collapsed'");
+ waitForState($page, '@posting-streak-badge', 'element.getBoundingClientRect().width === 0');
+
+ $page->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/PublishCardActionsTest.php b/tests/Browser/PublishCardActionsTest.php
index 516a7f42f..b49d0469c 100644
--- a/tests/Browser/PublishCardActionsTest.php
+++ b/tests/Browser/PublishCardActionsTest.php
@@ -168,9 +168,10 @@ test('move to drafts takes the card out of the queue and updates the tab counts'
waitForGone($page, "@post-card-{$queued->id}");
expect($queued->refresh()->status)->toBe(PostStatus::Draft);
+ letPageRun($page, 1000);
+ expect(elementsMap($page, '@flash-success-toast', 'element.dataset.testid'))->toBeEmpty();
$page->assertMissing("@post-card-{$queued->id}")
->assertSeeIn('@publish-tab-count-drafts', '1')
- ->assertMissing('@post-schedule-toast')
->assertNoJavaScriptErrors();
expect($page->script("document.querySelector('[data-testid=\"publish-tab-count-queue\"]')?.textContent.trim() ?? '0'"))->toBe('0');
});
diff --git a/tests/Browser/PublishQueueTest.php b/tests/Browser/PublishQueueTest.php
index ed59e4bc5..d7cbd7d27 100644
--- a/tests/Browser/PublishQueueTest.php
+++ b/tests/Browser/PublishQueueTest.php
@@ -902,3 +902,21 @@ test('a publishing post sits in its own queue group and moves to sent once it se
$page->assertVisible("@post-card-{$publishing->id}")
->assertNoJavaScriptErrors();
});
+
+test('moving a post to the top toasts with a link to its details, through the partial reload', function () {
+ [$user, , $channel] = publishQueueSetup();
+ $first = publishQueuePost($user, $channel);
+ $post = publishQueuePost($user, $channel);
+ $first->update(['content' => 'First in the queue']);
+ $post->update(['content' => 'Moved to the top']);
+ $this->actingAs($user);
+
+ $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
+ $page->click("@post-card-menu-{$post->id}");
+ waitFor($page, "@post-move-top-{$post->id}");
+ $page->click("@post-move-top-{$post->id}");
+ waitFor($page, '@flash-success-toast [data-button]');
+
+ $page->assertSeeIn('[data-testid="flash-success-toast"] [data-button]', 'View post')
+ ->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/WorkspaceInsightsTest.php b/tests/Browser/WorkspaceInsightsTest.php
index 99d5f666c..6cd5f1abf 100644
--- a/tests/Browser/WorkspaceInsightsTest.php
+++ b/tests/Browser/WorkspaceInsightsTest.php
@@ -200,7 +200,7 @@ test('workspace dashboard separates accounts and switches follower and post char
$page->assertVisible('@analytics-summary-followers');
- expect(workspaceInsightsSectionTitles($page))->toBe(['Summary', 'Top 5 Posts', 'Performance', 'Followers', 'Posts']);
+ expect(workspaceInsightsSectionTitles($page))->toBe(['Summary', 'Top 5 Posts', 'Performance', 'Followers', 'Posts', 'Posting activity']);
$page->assertSee('@first')
->assertSee('@second')
diff --git a/tests/Feature/Analytics/ChannelInsightsPageTest.php b/tests/Feature/Analytics/ChannelInsightsPageTest.php
index bfb653bd7..a54d647e0 100644
--- a/tests/Feature/Analytics/ChannelInsightsPageTest.php
+++ b/tests/Feature/Analytics/ChannelInsightsPageTest.php
@@ -6,6 +6,7 @@ use App\Actions\Analytics\ListChannelPublicationPerformance;
use App\Actions\Analytics\ResolveAnalyticsAccountKey;
use App\Dto\Analytics\DateRange;
use App\Enums\Analytics\PublicationAvailability;
+use App\Enums\Analytics\PublicationContentType;
use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
@@ -454,3 +455,26 @@ test('a publication the network deleted stays in the table without its link', fu
->where('publications.data.1.permalink', null)
->etc());
});
+
+test('the channel page defers its own posting activity and applies its post type filter', function () {
+ $other = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
+ $yesterday = now('UTC')->subDay()->setTime(12, 0)->toDateTimeString();
+ channelInsightsPublication($this->instagram, $yesterday, attributes: ['content_type' => PublicationContentType::Story]);
+ channelInsightsPublication($this->instagram, $yesterday, attributes: ['content_type' => PublicationContentType::Image]);
+ channelInsightsPublication($other, $yesterday);
+
+ $this->actingAs($this->user)
+ ->get(route('app.channels.insights', ['account' => $this->instagram]))
+ ->assertInertia(fn (Assert $page) => $page
+ ->missing('postingActivity')
+ ->loadDeferredProps(fn (Assert $reload) => $reload
+ ->where('postingActivity.total', 2)
+ ->where('postingActivity.current_streak', 1)
+ ->has('postingActivity.days', 365)));
+
+ $this->actingAs($this->user)
+ ->get(route('app.channels.insights', ['account' => $this->instagram, 'types' => ['instagram_story']]))
+ ->assertInertia(fn (Assert $page) => $page
+ ->loadDeferredProps(fn (Assert $reload) => $reload
+ ->where('postingActivity.total', 1)));
+});
diff --git a/tests/Feature/Analytics/InsightsControllerTest.php b/tests/Feature/Analytics/InsightsControllerTest.php
index 5d815136b..77b29d83c 100644
--- a/tests/Feature/Analytics/InsightsControllerTest.php
+++ b/tests/Feature/Analytics/InsightsControllerTest.php
@@ -6,6 +6,8 @@ use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsAccountDailySnapshot;
+use App\Models\AnalyticsPublication;
+use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -164,3 +166,43 @@ test('a workspace without connected channels shows no past analytics', function
->where('report.followers.accounts', [])
->etc());
});
+
+test('the dashboard defers the posting activity of the selected channels', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $user->update(['current_workspace_id' => $workspace->id]);
+ $picked = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);
+ $other = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);
+
+ foreach ([[$picked, 2], [$other, 1]] as [$account, $posts]) {
+ foreach (range(1, $posts) as $day) {
+ $publishedAt = now('UTC')->subDays($day)->setTime(12, 0);
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'network' => $account->platform->network(),
+ 'platform_user_id' => $account->platform_user_id,
+ 'platform' => $account->platform,
+ 'provider_published_at' => $publishedAt,
+ ]);
+ AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $publication->id, 'date' => $publishedAt->toDateString()]);
+ }
+ }
+
+ $this->actingAs($user)
+ ->get(route('app.insights', ['channels' => [$picked->id]]))
+ ->assertOk()
+ ->assertInertia(fn (Assert $page) => $page
+ ->missing('postingActivity')
+ ->loadDeferredProps(fn (Assert $reload) => $reload
+ ->where('postingActivity.total', 2)
+ ->where('postingActivity.current_streak', 2)
+ ->has('postingActivity.days', 365)));
+
+ $this->actingAs($user)
+ ->get(route('app.insights'))
+ ->assertInertia(fn (Assert $page) => $page
+ ->loadDeferredProps(fn (Assert $reload) => $reload
+ ->where('postingActivity.total', 3)));
+});
diff --git a/tests/Feature/Analytics/PostingActivityTest.php b/tests/Feature/Analytics/PostingActivityTest.php
new file mode 100644
index 000000000..5578bf6e5
--- /dev/null
+++ b/tests/Feature/Analytics/PostingActivityTest.php
@@ -0,0 +1,181 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Actions\Analytics\BuildPostingActivity;
+use App\Dto\Analytics\PublicationFilter;
+use App\Enums\SocialAccount\Platform;
+use App\Jobs\Analytics\BootstrapAccountAnalytics;
+use App\Jobs\Analytics\CollectAccountDailySnapshot;
+use App\Models\AnalyticsPublication;
+use App\Models\AnalyticsPublicationDailySnapshot;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\Workspace;
+use App\Models\WorkspaceLabel;
+use Carbon\CarbonImmutable;
+use Illuminate\Support\Facades\Bus;
+
+beforeEach(function () {
+ Bus::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
+ $this->travelTo(now('UTC')->startOfDay()->addHours(12));
+
+ $this->workspace = Workspace::factory()->create();
+ $this->account = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
+ $this->today = CarbonImmutable::now('UTC')->startOfDay();
+});
+
+function postingActivityPublication(SocialAccount $account, CarbonImmutable $instant, ?Post $post = null): AnalyticsPublication
+{
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'network' => $account->platform->network(),
+ 'platform_user_id' => $account->platform_user_id,
+ 'platform' => $account->platform,
+ 'post_id' => $post?->id,
+ 'provider_published_at' => $instant,
+ ]);
+ AnalyticsPublicationDailySnapshot::factory()->create([
+ 'publication_id' => $publication->id,
+ 'date' => $instant->toDateString(),
+ ]);
+
+ return $publication;
+}
+
+/**
+ * @param list<int> $daysAgo
+ */
+function postingActivityPostsOn(SocialAccount $account, CarbonImmutable $today, array $daysAgo): void
+{
+ foreach ($daysAgo as $days) {
+ postingActivityPublication($account, $today->subDays($days)->setTime(12, 0));
+ }
+}
+
+/**
+ * @param list<string>|null $accountKeys
+ * @return array<string, mixed>
+ */
+function postingActivity(Workspace $workspace, ?array $accountKeys = null, string $timezone = 'UTC', ?PublicationFilter $filter = null): array
+{
+ return app(BuildPostingActivity::class)->execute($workspace, $accountKeys, $timezone, $filter);
+}
+
+test('it returns one entry per day for the last 365 days, oldest first, zeros included', function () {
+ $activity = postingActivity($this->workspace);
+
+ expect($activity['days'])->toHaveCount(365)
+ ->and($activity['days'][364])->toBe(['date' => $this->today->toDateString(), 'count' => 0])
+ ->and($activity['days'][0]['date'])->toBe($this->today->subDays(364)->toDateString())
+ ->and($activity['start'])->toBe($this->today->subDays(364)->toDateString())
+ ->and($activity['end'])->toBe($this->today->toDateString());
+});
+
+test('it counts a post on the viewer local day', function () {
+ postingActivityPublication($this->account, $this->today->setTime(1, 0));
+
+ $activity = postingActivity($this->workspace, timezone: 'America/Sao_Paulo');
+ $counts = collect($activity['days'])->pluck('count', 'date');
+
+ expect($counts[$this->today->subDay()->toDateString()])->toBe(1)
+ ->and($counts[$this->today->toDateString()])->toBe(0);
+});
+
+test('it ignores publications outside the window', function () {
+ postingActivityPostsOn($this->account, $this->today, [365]);
+
+ expect(postingActivity($this->workspace)['total'])->toBe(0);
+});
+
+test('it keeps the current streak when today has no post yet', function () {
+ postingActivityPostsOn($this->account, $this->today, [1, 2, 3]);
+
+ expect(postingActivity($this->workspace)['current_streak'])->toBe(3);
+});
+
+test('it counts today in the current streak', function () {
+ postingActivityPostsOn($this->account, $this->today, [0, 1]);
+
+ expect(postingActivity($this->workspace)['current_streak'])->toBe(2);
+});
+
+test('it resets the current streak when yesterday and today are empty', function () {
+ postingActivityPostsOn($this->account, $this->today, [2, 3]);
+
+ $activity = postingActivity($this->workspace);
+
+ expect($activity['current_streak'])->toBe(0)
+ ->and($activity['best_streak'])->toBe(2);
+});
+
+test('it reports the longest run as the best streak and the busiest day', function () {
+ postingActivityPostsOn($this->account, $this->today, [10, 11, 12, 13, 20, 21, 21, 21]);
+
+ $activity = postingActivity($this->workspace);
+
+ expect($activity['best_streak'])->toBe(4)
+ ->and($activity['max_count'])->toBe(3)
+ ->and($activity['total'])->toBe(8);
+});
+
+test('it counts only the given accounts', function () {
+ $other = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
+ postingActivityPostsOn($this->account, $this->today, [1, 2]);
+ postingActivityPostsOn($other, $this->today, [1]);
+
+ expect(postingActivity($this->workspace, [$this->account->id])['total'])->toBe(2)
+ ->and(postingActivity($this->workspace)['total'])->toBe(3);
+});
+
+test('it applies the label filter', function () {
+ $label = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
+ $labelled = Post::factory()->forAccount($this->account)->published()->create();
+ $labelled->labels()->attach($label);
+ $plain = Post::factory()->forAccount($this->account)->published()->create();
+ postingActivityPublication($this->account, $this->today->subDays(1)->setTime(12, 0), $labelled);
+ postingActivityPublication($this->account, $this->today->subDays(2)->setTime(12, 0), $plain);
+
+ $activity = postingActivity($this->workspace, filter: new PublicationFilter(null, [$label->id]));
+
+ expect($activity['total'])->toBe(1)
+ ->and($activity['current_streak'])->toBe(1);
+});
+
+test('it leaves out networks outside insights', function () {
+ $linkedIn = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
+ postingActivityPostsOn($linkedIn, $this->today, [1]);
+
+ expect(postingActivity($this->workspace)['total'])->toBe(0);
+});
+
+test('it returns zeros and no streaks without publications', function () {
+ $activity = postingActivity($this->workspace);
+
+ expect($activity['total'])->toBe(0)
+ ->and($activity['max_count'])->toBe(0)
+ ->and($activity['current_streak'])->toBe(0)
+ ->and($activity['best_streak'])->toBe(0);
+});
+
+test('it counts the first day of the window', function () {
+ postingActivityPostsOn($this->account, $this->today, [364]);
+
+ $activity = postingActivity($this->workspace);
+
+ expect($activity['total'])->toBe(1)
+ ->and($activity['days'][0]['count'])->toBe(1);
+});
+
+test('a viewer ahead of utc gets their own today, which may be the next utc day', function () {
+ $this->travelTo($this->today->setTime(20, 0));
+ postingActivityPublication($this->account, $this->today->setTime(16, 0));
+
+ $activity = postingActivity($this->workspace, timezone: 'Asia/Tokyo');
+
+ expect($activity['end'])->toBe($this->today->addDay()->toDateString())
+ ->and($activity['days'][364])->toBe(['date' => $this->today->addDay()->toDateString(), 'count' => 1])
+ ->and($activity['current_streak'])->toBe(1);
+});
diff --git a/tests/Feature/Analytics/PostingStreakTest.php b/tests/Feature/Analytics/PostingStreakTest.php
new file mode 100644
index 000000000..e5f1e2009
--- /dev/null
+++ b/tests/Feature/Analytics/PostingStreakTest.php
@@ -0,0 +1,348 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Actions\Analytics\BuildPostingStreak;
+use App\Actions\Analytics\RankPostingStreaks;
+use App\Actions\Analytics\ShowPostingStreak;
+use App\Enums\Post\PublishStatus;
+use App\Enums\SocialAccount\Platform;
+use App\Enums\User\WeekStart;
+use App\Jobs\Analytics\BootstrapAccountAnalytics;
+use App\Jobs\Analytics\CollectAccountDailySnapshot;
+use App\Models\AnalyticsPublication;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use Carbon\CarbonImmutable;
+use Illuminate\Console\Scheduling\Event;
+use Illuminate\Console\Scheduling\Schedule;
+use Illuminate\Support\Facades\Bus;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\DB;
+
+beforeEach(function () {
+ Bus::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
+ $wednesday = now('UTC')->startOfWeek(CarbonImmutable::MONDAY)->addWeek()->addDays(2)->setTime(12, 0);
+ $this->travelTo($wednesday);
+
+ $this->workspace = Workspace::factory()->create();
+ $this->instagram = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
+ $this->linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
+ $this->thisWeek = CarbonImmutable::now('UTC')->startOfWeek(CarbonImmutable::MONDAY);
+});
+
+function postingStreakPublication(SocialAccount $account, CarbonImmutable $at, ?Post $post = null): AnalyticsPublication
+{
+ return AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'network' => $account->platform->network(),
+ 'platform_user_id' => $account->platform_user_id,
+ 'platform' => $account->platform,
+ 'post_id' => $post?->id,
+ 'provider_published_at' => $at,
+ ]);
+}
+
+function postingStreakPost(SocialAccount $account, CarbonImmutable $at, PublishStatus $status = PublishStatus::Published): Post
+{
+ $post = Post::factory()->forAccount($account)->published()->create();
+ $post->forceFill(['publish_status' => $status, 'published_at' => $at])->save();
+
+ return $post;
+}
+
+/**
+ * @return array{weeks: int, posted_this_week: bool}
+ */
+function postingStreak(Workspace $workspace, string $timezone = 'UTC', WeekStart $weekStart = WeekStart::Monday): array
+{
+ return app(BuildPostingStreak::class)->execute($workspace, $timezone, $weekStart);
+}
+
+test('it counts the weeks in a row with a post, this week included', function () {
+ foreach ([0, 1, 2] as $weeksAgo) {
+ postingStreakPublication($this->instagram, $this->thisWeek->subWeeks($weeksAgo)->addDay());
+ }
+
+ expect(postingStreak($this->workspace))->toBe(['weeks' => 3, 'posted_this_week' => true]);
+});
+
+test('a week without a post yet keeps the streak of the weeks before it', function () {
+ foreach ([1, 2] as $weeksAgo) {
+ postingStreakPublication($this->instagram, $this->thisWeek->subWeeks($weeksAgo)->addDay());
+ }
+
+ expect(postingStreak($this->workspace))->toBe(['weeks' => 2, 'posted_this_week' => false]);
+});
+
+test('a week without posts before last week ends the streak', function () {
+ postingStreakPublication($this->instagram, $this->thisWeek->subWeeks(2)->addDay());
+
+ expect(postingStreak($this->workspace))->toBe(['weeks' => 0, 'posted_this_week' => false]);
+});
+
+test('posts from networks outside insights count through trypost', function () {
+ postingStreakPost($this->linkedin, $this->thisWeek->addDay());
+ postingStreakPublication($this->instagram, $this->thisWeek->subWeek()->addDay());
+
+ expect(postingStreak($this->workspace)['weeks'])->toBe(2);
+});
+
+test('a linkedin post that did not go out does not count', function () {
+ postingStreakPost($this->linkedin, $this->thisWeek->addDay(), PublishStatus::Failed);
+
+ expect(postingStreak($this->workspace)['weeks'])->toBe(0);
+});
+
+test('weeks follow the user week start and zone', function () {
+ $sunday = $this->thisWeek->subDay()->setTime(12, 0);
+ postingStreakPublication($this->instagram, $sunday);
+
+ expect(postingStreak($this->workspace, 'UTC', WeekStart::Monday))->toBe(['weeks' => 1, 'posted_this_week' => false])
+ ->and(postingStreak($this->workspace, 'UTC', WeekStart::Sunday))->toBe(['weeks' => 1, 'posted_this_week' => true]);
+});
+
+test('another workspace does not count', function () {
+ $other = SocialAccount::factory()->create(['platform' => Platform::Instagram]);
+ postingStreakPublication($other, $this->thisWeek->addDay());
+
+ expect(postingStreak($this->workspace)['weeks'])->toBe(0);
+});
+
+test('the ranking places a streak among the workspaces with app access', function () {
+ foreach (range(0, 3) as $weeksAgo) {
+ postingStreakPublication($this->instagram, $this->thisWeek->subWeeks($weeksAgo)->addDay());
+ }
+
+ foreach (range(1, 9) as $_) {
+ $workspace = Workspace::factory()->create();
+ subscribeAccount($workspace->account);
+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);
+ postingStreakPublication($account, $this->thisWeek->addDay());
+ }
+
+ subscribeAccount($this->workspace->account);
+ app(RankPostingStreaks::class)->execute();
+
+ expect(RankPostingStreaks::topPercent(4))->toBe(10)
+ ->and(RankPostingStreaks::topPercent(1))->toBeNull();
+});
+
+test('the sidebar gets nothing without a streak and the streak with its rank otherwise', function () {
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+
+ expect(ShowPostingStreak::cached($user, $this->workspace))->toBeNull();
+
+ Cache::flush();
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+
+ expect(ShowPostingStreak::cached($user, $this->workspace))->toBe(['weeks' => 1, 'posted_this_week' => true, 'top_percent' => null]);
+});
+
+test('every app page shares the streak of the current workspace', function () {
+ $user = User::factory()->create(['timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+ $this->workspace->update(['user_id' => $user->id, 'account_id' => $user->account_id]);
+ $this->workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $this->workspace->id]);
+ subscribeAccount($user->account);
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+
+ $this->actingAs($user)
+ ->get(route('app.insights'))
+ ->assertInertia(fn ($page) => $page->where('postingStreak.weeks', 1)->etc());
+});
+
+test('the sidebar streak names its rank once the workspaces are ranked', function () {
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+ subscribeAccount($this->workspace->account);
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+
+ foreach (range(1, 9) as $_) {
+ subscribeAccount(Workspace::factory()->create()->account);
+ }
+
+ app(RankPostingStreaks::class)->execute();
+
+ expect(ShowPostingStreak::cached($user, $this->workspace))->toBe(['weeks' => 1, 'posted_this_week' => true, 'top_percent' => 10]);
+});
+
+test('a member sees the workspace streak once the account has app access', function () {
+ config(['trypost.self_hosted' => false]);
+ $owner = User::factory()->create();
+ $this->workspace->update(['user_id' => $owner->id, 'account_id' => $owner->account_id]);
+ subscribeAccount($owner->account);
+ $member = workspaceMember($this->workspace->fresh(), 'member', ['timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+
+ $this->actingAs($member)
+ ->get(route('app.insights'))
+ ->assertInertia(fn ($page) => $page->where('postingStreak.weeks', 1)->etc());
+});
+
+test('the ranking leaves out workspaces without app access', function () {
+ config(['trypost.self_hosted' => false]);
+ subscribeAccount($this->workspace->account);
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+
+ foreach (range(1, 9) as $_) {
+ subscribeAccount(Workspace::factory()->create()->account);
+ }
+
+ $unsubscribed = SocialAccount::factory()->create(['platform' => Platform::Instagram]);
+
+ foreach (range(0, 5) as $weeksAgo) {
+ postingStreakPublication($unsubscribed, $this->thisWeek->subWeeks($weeksAgo)->addDay());
+ }
+
+ app(RankPostingStreaks::class)->execute();
+
+ expect(RankPostingStreaks::topPercent(1))->toBe(10);
+});
+
+test('workspaces tied at the top share the same rank', function () {
+ foreach (range(1, 2) as $_) {
+ $workspace = Workspace::factory()->create();
+ subscribeAccount($workspace->account);
+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);
+
+ foreach (range(0, 2) as $weeksAgo) {
+ postingStreakPublication($account, $this->thisWeek->subWeeks($weeksAgo)->addDay());
+ }
+ }
+
+ foreach (range(1, 8) as $_) {
+ subscribeAccount(Workspace::factory()->create()->account);
+ }
+
+ app(RankPostingStreaks::class)->execute();
+
+ expect(RankPostingStreaks::topPercent(3))->toBe(25);
+});
+
+test('a streak longer than the window reads as the window', function () {
+ foreach (range(0, BuildPostingStreak::WEEKS + 5) as $weeksAgo) {
+ postingStreakPublication($this->instagram, $this->thisWeek->subWeeks($weeksAgo)->addDay());
+ }
+
+ expect(postingStreak($this->workspace)['weeks'])->toBe(BuildPostingStreak::WEEKS);
+});
+
+test('the ranking runs every day', function () {
+ $ranking = collect(app(Schedule::class)->events())
+ ->first(fn (Event $event): bool => str_contains((string) $event->command, 'analytics:rank-posting-streaks'));
+
+ expect($ranking?->expression)->toBe('0 0 * * *');
+});
+
+test('the sidebar reads the streak from the cache on the next page, with or without a streak', function (bool $posted) {
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+
+ if ($posted) {
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+ }
+
+ ShowPostingStreak::cached($user, $this->workspace);
+ DB::enableQueryLog();
+ ShowPostingStreak::cached($user, $this->workspace);
+
+ expect(DB::getQueryLog())->toBeEmpty();
+})->with(['without a streak' => false, 'with a streak' => true]);
+
+test('the sidebar streak counts a post as soon as it goes out on a network outside insights', function () {
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+ $post = Post::factory()->forAccount($this->linkedin)->create();
+
+ expect(ShowPostingStreak::cached($user, $this->workspace))->toBeNull();
+
+ $post->forceFill(['publish_status' => PublishStatus::Published, 'published_at' => $this->thisWeek->addDay()])->save();
+
+ expect(data_get(ShowPostingStreak::cached($user, $this->workspace), 'weeks'))->toBe(1);
+});
+
+test('the sidebar streak counts a publication as soon as insights finds it', function () {
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+
+ expect(ShowPostingStreak::cached($user, $this->workspace))->toBeNull();
+
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+
+ expect(data_get(ShowPostingStreak::cached($user, $this->workspace), 'weeks'))->toBe(1);
+});
+
+test('a post going out in another workspace leaves this streak cached', function () {
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+ ShowPostingStreak::cached($user, $this->workspace);
+
+ postingStreakPublication(SocialAccount::factory()->create(['platform' => Platform::Instagram]), $this->thisWeek->addDay());
+ DB::enableQueryLog();
+ ShowPostingStreak::cached($user, $this->workspace);
+
+ expect(DB::getQueryLog())->toBeEmpty();
+});
+
+test('a handful of workspaces ranks nothing, so a small install never ranks itself', function () {
+ subscribeAccount($this->workspace->account);
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+
+ foreach (range(1, RankPostingStreaks::MIN_RANKED - 2) as $_) {
+ subscribeAccount(Workspace::factory()->create()->account);
+ }
+
+ app(RankPostingStreaks::class)->execute();
+
+ expect(RankPostingStreaks::topPercent(1))->toBeNull()
+ ->and(RankPostingStreaks::topPercent(50))->toBeNull();
+});
+
+test('a post moving between steps that do not count keeps the streak cached', function () {
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+ $post = Post::factory()->forAccount($this->linkedin)->create();
+ ShowPostingStreak::cached($user, $this->workspace);
+
+ $post->forceFill(['publish_status' => PublishStatus::Publishing])->save();
+ DB::enableQueryLog();
+ ShowPostingStreak::cached($user, $this->workspace);
+
+ expect(DB::getQueryLog())->toBeEmpty();
+});
+
+test('the sidebar streak follows a publication insights re-dates or drops', function () {
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+ $publication = postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+
+ expect(data_get(ShowPostingStreak::cached($user, $this->workspace), 'weeks'))->toBe(1);
+
+ $publication->update(['provider_published_at' => $this->thisWeek->subWeeks(3)]);
+
+ expect(ShowPostingStreak::cached($user, $this->workspace))->toBeNull();
+
+ $publication->update(['provider_published_at' => $this->thisWeek->addDay()]);
+ ShowPostingStreak::cached($user, $this->workspace);
+ $publication->delete();
+
+ expect(ShowPostingStreak::cached($user, $this->workspace))->toBeNull();
+});
+
+test('a post on a network insights reads counts through its publication only', function () {
+ postingStreakPost($this->instagram, $this->thisWeek->addDay());
+
+ expect(postingStreak($this->workspace)['weeks'])->toBe(0);
+});
+
+test('the sidebar gets no streak without a current workspace or without app access', function () {
+ config(['trypost.self_hosted' => false]);
+ postingStreakPublication($this->instagram, $this->thisWeek->addDay());
+ $user = User::factory()->create(['current_workspace_id' => $this->workspace->id, 'timezone' => 'UTC', 'week_starts_on' => WeekStart::Monday]);
+
+ expect(ShowPostingStreak::forSidebar(null))->toBeNull()
+ ->and(ShowPostingStreak::forSidebar(User::factory()->create(['current_workspace_id' => null])))->toBeNull()
+ ->and(ShowPostingStreak::forSidebar($user))->toBeNull();
+
+ subscribeAccount($this->workspace->account);
+
+ expect(data_get(ShowPostingStreak::forSidebar($user->fresh()), 'weeks'))->toBe(1);
+});
diff --git a/tests/Feature/Posts/PostQueueTest.php b/tests/Feature/Posts/PostQueueTest.php
index d9397a84e..0dd726a3e 100644
--- a/tests/Feature/Posts/PostQueueTest.php
+++ b/tests/Feature/Posts/PostQueueTest.php
@@ -684,3 +684,45 @@ test('a member who needs approval editing a queued post without queue keeps its
->and(postQueueSlot($queued))->toBe('Mon 09:00')
->and(postQueueSlot($next))->toBe('Wed 09:00');
});
+
+test('storing into the queue toasts that the posts were added, with a link to the first one', function () {
+ $post = postQueueStore($this, $this->channel);
+
+ expect(session('flash.success'))->toBe(trans_choice('posts.composer.queue.added', 1, ['count' => 1]))
+ ->and(session('flash.link'))->toBe([
+ 'label' => __('posts.actions.view'),
+ 'url' => route('app.posts.index', ['post' => $post->id]),
+ ]);
+});
+
+test('storing a draft toasts nothing', function () {
+ $this->actingAs($this->user)
+ ->post(route('app.posts.store'), postQueuePayload([$this->channel], ['status' => 'draft']))
+ ->assertSessionMissing('flash.success')
+ ->assertSessionMissing('flash.link');
+});
+
+test('a member who needs approval is told the queue request awaits approval, not that it was added', function () {
+ $member = workspaceMember($this->workspace, 'approval');
+
+ $this->actingAs($member)
+ ->post(route('app.posts.store'), postQueuePayload([$this->channel], ['queue' => 'next']))
+ ->assertSessionHasNoErrors()
+ ->assertSessionHas('flash.success', __('posts.approvals.requested'));
+});
+
+test('storing into the queue for several channels says how many were added and links the first one', function () {
+ $other = SocialAccount::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'platform' => Platform::LinkedIn,
+ 'timezone' => 'UTC',
+ 'posting_schedule' => PostingSchedule::empty()->withTime(2, '10:00'),
+ ]);
+
+ $this->actingAs($this->user)
+ ->post(route('app.posts.store'), postQueuePayload([$this->channel, $other]))
+ ->assertSessionHasNoErrors();
+
+ expect(session('flash.success'))->toBe(trans_choice('posts.composer.queue.added', 2, ['count' => 2]))
+ ->and(session('flash.link.url'))->toBe(route('app.posts.index', ['post' => data_get(session('created_post_ids'), 0)]));
+});
diff --git a/tests/Feature/Posts/PostScheduleActionTest.php b/tests/Feature/Posts/PostScheduleActionTest.php
index b14e14c86..7358ecae9 100644
--- a/tests/Feature/Posts/PostScheduleActionTest.php
+++ b/tests/Feature/Posts/PostScheduleActionTest.php
@@ -265,3 +265,59 @@ test('adding a draft to the queue from its card stays on the tab it was added fr
'the drafts tab' => false,
'a channel drafts tab' => true,
]);
+
+test('queue next toasts that the post was added, with a link to its details', function () {
+ $draft = scheduleActionPost($this->channel, $this->user);
+
+ $this->actingAs($this->user)
+ ->put(route('app.posts.schedule.update', $draft), ['action' => 'queue_next'])
+ ->assertSessionHas('flash.success', trans_choice('posts.composer.queue.added', 1, ['count' => 1]))
+ ->assertSessionHas('flash.link', [
+ 'label' => __('posts.actions.view'),
+ 'url' => route('app.posts.index', ['post' => $draft->id]),
+ ]);
+});
+
+test('moving a post to drafts toasts nothing', function () {
+ $queued = scheduleActionQueued($this->channel, $this->user);
+
+ $this->actingAs($this->user)
+ ->put(route('app.posts.schedule.update', $queued), ['action' => 'draft'])
+ ->assertSessionMissing('flash.success')
+ ->assertSessionMissing('flash.link');
+});
+
+test('moving a queued post to the top toasts that it went to the top, not that it was added', function () {
+ scheduleActionQueued($this->channel, $this->user);
+ $second = scheduleActionQueued($this->channel, $this->user);
+
+ $this->actingAs($this->user)
+ ->put(route('app.posts.schedule.update', $second), ['action' => 'queue_top'])
+ ->assertSessionHas('flash.success', __('posts.composer.queue.moved_to_top'))
+ ->assertSessionHas('flash.link.url', route('app.posts.index', ['post' => $second->id]));
+});
+
+test('a member who needs approval is told the queue request awaits approval', function () {
+ $member = workspaceMember($this->workspace, 'approval');
+ $draft = scheduleActionPost($this->channel, $member);
+
+ $this->actingAs($member)
+ ->put(route('app.posts.schedule.update', $draft), ['action' => 'queue_next'])
+ ->assertSessionHas('flash.success', __('posts.approvals.requested'))
+ ->assertSessionHas('flash.link.url', route('app.posts.index', ['post' => $draft->id]));
+});
+
+test('the toast reaches a partial reload that does not ask for it', function () {
+ $page = $this->actingAs($this->user)->get(route('app.posts.index'))->assertOk()->viewData('page');
+
+ $this->withSession(['flash' => ['success' => 'Your post was added to the queue.']])
+ ->withHeaders([
+ 'X-Inertia' => 'true',
+ 'X-Inertia-Version' => (string) data_get($page, 'version'),
+ 'X-Inertia-Partial-Component' => data_get($page, 'component'),
+ 'X-Inertia-Partial-Data' => 'posts',
+ ])
+ ->get(route('app.posts.index'))
+ ->assertOk()
+ ->assertJsonPath('props.flash.success', 'Your post was added to the queue.');
+});
diff --git a/tests/Feature/Posts/PublishPageTest.php b/tests/Feature/Posts/PublishPageTest.php
index ccdd50560..4d7468add 100644
--- a/tests/Feature/Posts/PublishPageTest.php
+++ b/tests/Feature/Posts/PublishPageTest.php
@@ -18,6 +18,7 @@ use App\Models\Workspace;
use App\Models\WorkspaceLabel;
use App\Support\PostingSchedule;
use Carbon\CarbonImmutable;
+use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Inertia\Testing\AssertableInertia;
@@ -87,6 +88,7 @@ function publishPageQueryCount(object $test, string $tab, int $postsPerStatus):
$url = route('app.posts.index', ['tab' => $tab]);
+ Cache::flush();
DB::flushQueryLog();
DB::enableQueryLog();
diff --git a/tests/Pest.php b/tests/Pest.php
index 08a1e6a77..2a8e5f948 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -1116,6 +1116,17 @@ function elementsMap(mixed $page, string $selector, string $expression): array
return $page->script("[...document.querySelectorAll({$selector})].map((element) => ({$expression}))");
}
+/**
+ * Changes the element the selector matches the way the browser or the user
+ * would (scrolling it, resizing what holds it), with `element` in scope.
+ */
+function onElement(mixed $page, string $selector, string $statement): void
+{
+ $selector = jsSelector($selector);
+
+ $page->script("((element) => { {$statement}; })(document.querySelector({$selector}))");
+}
+
/**
* Lets the page run for a while without waiting on anything, to show that
* something stays as it is (a dialog left open across polls). Never a
diff --git a/tests/Unit/ShareCardArithmeticTest.php b/tests/Unit/ShareCardArithmeticTest.php
index 35ebabfd1..a241c8da4 100644
--- a/tests/Unit/ShareCardArithmeticTest.php
+++ b/tests/Unit/ShareCardArithmeticTest.php
@@ -82,3 +82,13 @@ test('line end labels move apart just enough and stay inside the plot', function
'atTheBottom' => [364, 388],
]);
});
+
+test('the card shades each day with the step d3 gives it on the page heatmap', function () {
+ expect(runShareCardHarness()['levels'])->toBe([
+ 'one' => [1],
+ 'four' => [1, 2, 3, 4],
+ 'ten' => [1, 4, 6, 8],
+ 'odd' => [1, 10, 19, 28],
+ 'busy' => [1, 64, 126, 188],
+ ]);
+});
diff --git a/tests/Unit/ToastLinkTest.php b/tests/Unit/ToastLinkTest.php
new file mode 100644
index 000000000..ad84eb0cb
--- /dev/null
+++ b/tests/Unit/ToastLinkTest.php
@@ -0,0 +1,24 @@
+<?php
+
+declare(strict_types=1);
+
+use Symfony\Component\Process\ExecutableFinder;
+use Symfony\Component\Process\Process;
+
+test('a toast link goes where it says, and a toast without one drops the link of the toast it replaces', function () {
+ $node = (new ExecutableFinder)->find('node');
+
+ if ($node === null) {
+ $this->markTestSkipped('node is unavailable');
+ }
+
+ $process = (new Process([$node, base_path('tests/fixtures/toast-link-harness.ts'), resource_path('js')]))->mustRun();
+
+ expect(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR))->toBe([
+ 'label' => 'View post',
+ 'visited' => ['/posts?post=1'],
+ 'widened' => true,
+ 'keysWithoutLink' => ['action', 'classes'],
+ 'mergedKeepsLink' => false,
+ ]);
+});
diff --git a/tests/fixtures/share-card-harness.ts b/tests/fixtures/share-card-harness.ts
index a23deb10b..ef5953981 100644
--- a/tests/fixtures/share-card-harness.ts
+++ b/tests/fixtures/share-card-harness.ts
@@ -27,7 +27,7 @@ registerHooks({
type Op = [string, ...number[]];
const load = (file: string) => import(pathToFileURL(path.join(root, file)).href);
-const { comboDates, evenDates, fittingColumns, linearTicks, valueAxis } = await load('lib/shareCard/scale.ts');
+const { comboDates, evenDates, fittingColumns, linearTicks, quantizeLevel, valueAxis } = await load('lib/shareCard/scale.ts');
const { traceMonotone } = await load('lib/shareCard/curve.ts');
const { spreadLabels } = await load('lib/labelLayout.ts');
@@ -55,6 +55,14 @@ const curve = (points: [number, number][]): Op[] => {
const axis = valueAxis([-26, 30], 5);
+/** The first count on each step, from one post to the busiest day, as the card shades them. */
+const levelStarts = (maxCount: number): number[] => {
+ const counts = Array.from({ length: Math.max(maxCount, 1) }, (_, index) => index + 1);
+ const levels = counts.map((count) => quantizeLevel(count, maxCount, 4));
+
+ return counts.filter((_, index) => index === 0 || levels[index] !== levels[index - 1]);
+};
+
console.log(
JSON.stringify({
ticks: {
@@ -72,6 +80,7 @@ console.log(
rising: curve([[0, 0], [10, 1], [20, 10], [30, 30]]),
two: curve([[0, 0], [10, 5]]),
},
+ levels: { one: levelStarts(1), four: levelStarts(4), ten: levelStarts(10), odd: levelStarts(37), busy: levelStarts(250) },
labels: {
apart: spreadLabels([100, 102, 300], { gap: 24, top: 0, bottom: 400 }),
atTheBottom: spreadLabels([390, 395], { gap: 24, top: 0, bottom: 400 }),
diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.php
index c1c5406d1..d18208fc2 100644
--- a/tests/fixtures/single-line-copy.php
+++ b/tests/fixtures/single-line-copy.php
@@ -42,6 +42,16 @@ return [
'analytics.channel.series.followers' => 11,
'analytics.channel.series.posts' => 13,
'analytics.channel.this_period' => 15,
+ 'analytics.posting_activity.best_streak' => 20,
+ 'analytics.posting_activity.current_streak' => 18,
+ 'analytics.posting_activity.days' => 13,
+ 'analytics.posting_activity.less' => 13,
+ 'analytics.posting_activity.more' => 12,
+ 'analytics.posting_activity.title' => 26,
+ 'analytics.posting_activity.total' => 13,
+ 'analytics.posting_streak.rank_tooltip' => 51,
+ 'analytics.posting_streak.schedule' => 21,
+ 'analytics.posting_streak.top' => 16,
'analytics.ranges.versus' => 13,
'analytics.share.copy' => 19,
'analytics.share.create_post' => 17,
@@ -114,6 +124,7 @@ return [
'notes.mention_everyone.description' => 35,
'notes.mention_everyone.word' => 8,
'notes.title' => 10,
+ 'posts.actions.view' => 19,
'posts.approvals.approve' => 10,
'posts.approvals.reject' => 9,
'posts.approvals.revert' => 32,
diff --git a/tests/fixtures/toast-link-harness.ts b/tests/fixtures/toast-link-harness.ts
new file mode 100644
index 000000000..1ad3dfc13
--- /dev/null
+++ b/tests/fixtures/toast-link-harness.ts
@@ -0,0 +1,45 @@
+/**
+ * Runs `toastLinkOptions()` of `resources/js/lib/toastLink.ts` with and
+ * without a link, and merges them the way vue-sonner updates a toast still on
+ * screen under the same id, so `ToastLinkTest.php` can check the link never
+ * outlives its message.
+ *
+ * Node strips type annotations on import; the resolve hook maps the `@/` alias
+ * onto `resources/js/**.ts`.
+ */
+import { registerHooks } from 'node:module';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const [resourcesDir] = process.argv.slice(2);
+const root = path.resolve(resourcesDir);
+
+registerHooks({
+ resolve: (specifier, context, nextResolve) => {
+ if (specifier.startsWith('@/')) {
+ return nextResolve(pathToFileURL(path.join(root, `${specifier.slice(2)}.ts`)).href, context);
+ }
+
+ return nextResolve(specifier, context);
+ },
+});
+
+const { toastLinkOptions } = await import(pathToFileURL(path.join(root, 'lib/toastLink.ts')).href);
+
+const visited: string[] = [];
+const withLink = toastLinkOptions({ label: 'View post', url: '/posts?post=1' }, (url: string) => visited.push(url));
+const withoutLink = toastLinkOptions(undefined, (url: string) => visited.push(url));
+
+withLink.action.onClick();
+
+const merged = { ...withLink, ...withoutLink };
+
+console.log(
+ JSON.stringify({
+ label: withLink.action.label,
+ visited,
+ widened: withLink.classes !== undefined,
+ keysWithoutLink: Object.keys(withoutLink),
+ mergedKeepsLink: merged.action !== undefined || merged.classes !== undefined,
+ }),
+);