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.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Share Insights charts and the Summary as an image (#458)
Paulo Castellanob13cca4d834b
diff --git a/AGENTS.md b/AGENTS.mdindex a72fd20d5..5c487ee2c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -205,6 +205,8 @@ Vue components must have a single root element.## Frontend (Vue/TypeScript)+- **TypeScript only, never JavaScript** (owner decision November 2026). Every script, config and test harness is a `.ts` file: `eslint.config.ts`, `vite.config.ts`, the Node harnesses in `tests/fixtures/*-harness.ts` (Node strips the types when it runs them, so they need no build step). Never add a `.js` or `.mjs` file. The one exception is the Maizzle email project (`maizzle/*.js`), which keeps its own JavaScript config.+- **Imports go through the `@/` alias** (`import { formatNumberCompact } from '@/lib/utils'`), never a relative path (`./`, `../`), even for a sibling file. ESLint refuses relative imports (`no-restricted-imports`), with no exception: the stylesheet is loaded by `@vite` in `app.blade.php`, not imported from `app.ts`. CI runs Prettier (`prettier-plugin-organize-imports` reorders imports) before ESLint, so never rely on an `eslint-disable-next-line` above an import.- Always use arrow functions in Vue components and TypeScript files. Never use `function` declarations.- Template event handlers call a named function (`@click="openCreateDialog"`), never an inline statement that mutates state (`@click="isCreateDialogOpen = true"`). Opening something usually grows a second step later (reset a form, focus, track an event), and a named function is where that goes. Passing an argument through is fine: `@click="openEditDialog(label)"`.- **A button that waits on a request shows it through the `Button` component's own `loading` prop whenever possible** (`<Button :loading="form.processing">`): it disables the button and swaps its label for the spinner, so every button waits the same way. Do not hand-roll a `<Spinner v-if>` inside the label or a separate disabled flag for this. When `loading` cannot fit (the label must stay visible next to the spinner, an `as-child` link, a control that is not our `Button`), keep the label and add the spinner next to it. Many existing buttons predate this rule; move them to `loading` when touching them, not in a sweep.@@ -825,10 +827,11 @@ with `Mail::to($user)`, run the Maizzle build, and cover it with a render test`tests/Feature/Mail/MailRenderingTest.php` exists because copy moving into theview turns a forgotten variable into a runtime-only failure.-## Icons (@tabler/icons-vue)+## Icons (@tabler/icons-vue and @thesvg/vue)+- **Icons and logos are always imported straight from their package into the component that draws them** (owner decision November 2026): `import { IconCheck } from '@tabler/icons-vue'`, `import Canva from '@thesvg/vue/canva'`. Never copy an icon's SVG or path into the code, never save it as a file under `public/`, and never wrap the packages in a helper of our own (`lib/brandLogos.ts` was removed for this). When a list needs a logo per item, a module may map items to the imported components (`lib/mcpClients.ts`).- This project uses `@tabler/icons-vue` for all icons. NEVER use `lucide-vue-next`.-- Brand logos come from `@thesvg/vue`, one import per logo (`import Canva from '@thesvg/vue/canva'`). A one-color logo that must follow the theme goes through `inTextColor()` (`resources/js/lib/brandLogos.ts`).+- Brand logos come from `@thesvg/vue`, one import per logo. A one-color logo that must follow the theme gets `fill-current` (or `[&_path]:fill-current` when its paths carry their own fill) next to a text color class. A canvas, which cannot draw a component, reads the paths from the imported Tabler component (`lib/shareCard/icons.ts`), never from a copy.- **Exception — card brand logos on billing** (owner decision October 2026): the full-color card artwork lives in `public/images/card-brands/*.svg`, mapped by Stripe's `card.brand` in `resources/js/lib/cardBrands.ts` (a brand without its own art uses `generic.svg`).- **Exception — competitor logos on the Welcome software step** (owner decision October 2026): each tool's symbol is a static SVG in `public/images/competitors/<PreviousSoftware value>.svg`, drawn by `logo()` in `resources/js/lib/welcomeOptions.ts`. Logos and the Tabler icons of "none" and "other" (`icon()`) sit on a white tile, selected or not, so dark logos stay readable in dark mode. A new `PreviousSoftware` brand needs its file (`PreviousSoftwareTest` fails without it).- All Tabler icons are prefixed with `Icon`, e.g. `IconCheck`, `IconChevronRight`, `IconMail`.@@ -840,6 +843,10 @@ view turns a forgotten variable into a runtime-only failure.- For date manipulation, always use `@/dayjs` (pre-configured dayjs instance with utc, timezone, relativeTime plugins).- For formatting dates for display (formatDate, formatDateTime, formatTime, diffForHumans), always use `@/date` which centralizes all formatting logic with proper timezone handling.- Never use raw `new Date()` for date calculations — use dayjs.+- **Never hard-code a date, in tests or in code** (owner decision November 2026). Derive it from the clock: Carbon (`now()`, `CarbonImmutable`) on the backend and in Pest tests, `@/dayjs` on the frontend. A test that needs a known day computes it (`now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(14)`) or freezes the clock on a computed one (`$this->travelTo(...)`); a literal like `'2026-09-01'` breaks the day the calendar moves past it. The one exception is the `2037-12-31` far-future sentinel (see "Database engines").+ - Write the year out in a relative date: `"first sunday of november {$year}"`. PHP reads `"first sunday of november next year"` as November 1 on any weekday, which broke the calendar's daylight saving tests on the day the clocks changed (November 2026). The calendar tests share `calendarDragNextDstSunday()` for this.+ - Never assume where a computed day falls: that next week is in this month, that tomorrow is in this year. When a test depends on it, pick a day that guarantees it (the middle of next month is never in this month's grid) and assert it, instead of hoping the run day cooperates.+ - Existing tests with literal dates move to computed ones when touched, not in a sweep.## Routing (Wayfinder)diff --git a/app/Actions/Analytics/BuildPublicationAnalyticsReport.php b/app/Actions/Analytics/BuildPublicationAnalyticsReport.phpindex fcb2daf6e..ae703ae39 100644--- a/app/Actions/Analytics/BuildPublicationAnalyticsReport.php+++ b/app/Actions/Analytics/BuildPublicationAnalyticsReport.php@@ -105,7 +105,7 @@ class BuildPublicationAnalyticsReport$bucket['accounts'][$key] = $count;}- $bucket['total'] = array_sum(data_get($bucket, 'accounts'));+ $bucket['total'] = collect(data_get($bucket, 'accounts'))->sum();}unset($bucket);@@ -116,6 +116,7 @@ class BuildPublicationAnalyticsReport'previous_totals' => $this->finalizeTotals($previousTotals),'posts' => ['resolution' => $this->buckets->resolution($current),+ 'total' => data_get($currentTotals, 'posts'),'accounts' => $postAccounts,'buckets' => $buckets,],@@ -315,8 +316,9 @@ class BuildPublicationAnalyticsReport*/private function top(array $rows, Collection $postMedia): array{- return collect($rows)->map(fn (object $row): array => [+ return collect($rows)->values()->map(fn (object $row, int $index): array => ['id' => $row->id,+ 'rank' => $index + 1,'post_id' => $row->post_id,'social_account_key' => $row->social_account_key,'platform' => $row->platform,diff --git a/eslint.config.js b/eslint.config.tssimilarity index 82%rename from eslint.config.jsrename to eslint.config.tsindex b92074a22..a2ac4e18a 100644--- a/eslint.config.js+++ b/eslint.config.ts@@ -36,6 +36,17 @@ export default defineConfigWithVueTs(rules: {'vue/multi-word-component-names': 'off','@typescript-eslint/no-explicit-any': 'off',+ 'no-restricted-imports': [+ 'error',+ {+ patterns: [+ {+ group: ['./*', '../*'],+ message: "Import through the '@/' alias, e.g. '@/lib/utils'.",+ },+ ],+ },+ ],'import/order': ['error',{diff --git a/lang/ar/analytics.php b/lang/ar/analytics.phpindex cbcedc87b..aafe6a164 100644--- a/lang/ar/analytics.php+++ b/lang/ar/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'ملخص','posts' => 'المنشورات','total_followers' => 'إجمالي المتابعين',+ 'total_posts' => 'إجمالي المنشورات','reactions' => 'التفاعلات','comments' => 'التعليقات','engagement_rate' => 'معدل التفاعل',@@ -63,7 +64,6 @@ return ['performance' => 'الأداء','top_posts' => 'أفضل 5 منشورات','channel' => 'القناة',- 'latest_snapshot_hint' => 'تستخدم مقاييس المنشورات أحدث قياس محفوظ للمنشورات المنشورة خلال هذه الفترة.','followers_chart_mode' => 'وضع مخطط المتابعين','posts_chart_mode' => 'وضع مخطط المنشورات','chart_line' => 'خطي',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'لا توجد بيانات متابعين للقنوات المحددة في هذه الفترة. جرّب نطاق تاريخ آخر أو امسح عامل تصفية القنوات.','filtered_no_data_title' => 'لا شيء يطابق عوامل التصفية هذه','filtered_no_data_body' => 'لا تحتوي القنوات المحددة على بيانات تحليلات بعد. اختر قنوات أخرى أو امسح عوامل التصفية.',- 'posts_sent_axis' => 'المنشورات المرسلة',- 'followers_gained_detail' => 'البداية :start · زيادة :change (:percent)',- 'followers_lost_detail' => 'البداية :start · خسارة :change (:percent)','followers_at_start' => 'في البداية','followers_gained_in_range' => 'المكتسبون',+ 'followers_lost_in_range' => 'المفقودون','no_excerpt' => 'لا تتوفر معاينة للنص.','published_via' => 'نُشر عبر','top_posts_sort' => 'ترتيب المنشورات حسب',- 'carried_forward' => 'آخر قيمة معروفة',- 'carried_forward_hint' => 'تعذّر الوصول إلى الخدمة؛ هذا هو آخر عدد معروف للمتابعين.','import_in_progress' => 'جارٍ استيراد سجل الحساب. ستظهر المنشورات الأقدم مع تقدم جمع البيانات.','no_data_title' => 'يجري إعداد سجل التحليلات لديك','no_data_body' => 'اربط حسابًا مدعومًا أو انتظر أول عملية جمع للبيانات في الخلفية. ستظهر المنشورات السابقة أثناء الاستيراد.',@@ -112,7 +108,8 @@ return ['30d' => '30 يومًا','mtd' => 'الشهر الحالي','custom' => 'مخصص',- 'compared_to' => ':current · مقارنةً بـ :previous',+ 'versus' => 'مقابل :range',+ 'versus_hint' => 'تقارن التغييرات هذه الفترة بالفترة :range.','label' => 'النطاق الزمني',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'فترة الرسم البياني','both' => 'كلاهما','comparison' => 'المقارنة',- 'comparison_axis' => ':metric (مقارنة)','not_enough_history' => 'لا يوجد سجل كافٍ بعد. يُسجَّل عدد المتابعين يوميًا، فعُد قريبًا.','date' => 'التاريخ','previous_value' => ':metric (الفترة السابقة)',@@ -416,4 +412,40 @@ return ['columns' => 'الأعمدة','channels_shown' => ':range · عرض :shown من :total قنوات. صفِّ حسب القناة لعرض مجموعة أخرى.',],+ 'share' => [+ 'channels_shown' => ':shown من :total قنوات',+ 'button' => 'مشاركة كصورة',+ 'title' => 'مشاركة كصورة',+ 'description' => 'نزّل الصورة أو حوّلها إلى منشور لقنواتك.',+ 'color' => 'اللون',+ 'download' => 'تنزيل',+ 'copy' => 'نسخ الصورة',+ 'copied' => 'تم نسخ الصورة',+ 'create_post' => 'إنشاء منشور',+ 'mark' => 'صُنع باستخدام TryPost',+ 'copy_failed' => 'تعذّر نسخ الصورة. نزّلها بدلًا من ذلك.',+ 'post_failed' => 'تعذّر تجهيز المنشور. حاول مرة أخرى.',+ 'caption_workspace' => ':metric عبر قنواتنا: :value (:range) 📈',+ 'caption_summary_workspace' => 'أرقامنا للفترة :range 📈 :metrics',+ 'caption_summary_channel' => 'أرقامنا على :channel للفترة :range 📈 :metrics',+ 'export_failed' => 'تعذّر إنشاء الصورة. حاول مرة أخرى.',+ 'colors' => [+ 'violet' => 'بنفسجي',+ 'blue' => 'أزرق',+ 'green' => 'أخضر',+ 'peach' => 'خوخي',+ 'yellow' => 'أصفر',+ 'cyan' => 'سماوي',+ 'teal' => 'أزرق مخضر',+ 'red' => 'أحمر',+ 'pink' => 'وردي',+ 'neutral' => 'محايد',+ 'indigo' => 'نيلي',+ 'lime' => 'ليموني',+ 'purple' => 'أرجواني',+ 'fuchsia' => 'فوشيا',+ 'orange' => 'برتقالي',+ 'slate' => 'أردوازي',+ ],+ ],];diff --git a/lang/ar/posts.php b/lang/ar/posts.phpindex f2f23f00b..0c015dfe7 100644--- a/lang/ar/posts.php+++ b/lang/ar/posts.php@@ -924,6 +924,7 @@ return ['title' => 'نشر','all_channels' => 'جميع القنوات','tabs' => [+ 'label' => 'الحالة','queue' => 'قائمة الانتظار','approvals' => 'الموافقات','drafts' => 'المسودات',diff --git a/lang/de/analytics.php b/lang/de/analytics.phpindex 032a95f9b..9f7e0c805 100644--- a/lang/de/analytics.php+++ b/lang/de/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Übersicht','posts' => 'Beiträge','total_followers' => 'Follower insgesamt',+ 'total_posts' => 'Beiträge insgesamt','reactions' => 'Reaktionen','comments' => 'Kommentare','engagement_rate' => 'Interaktionsrate',@@ -63,7 +64,6 @@ return ['performance' => 'Leistung','top_posts' => 'Top 5 Beiträge','channel' => 'Kanal',- 'latest_snapshot_hint' => 'Für Beiträge in diesem Zeitraum wird die zuletzt gespeicherte Messung verwendet.','followers_chart_mode' => 'Ansicht des Follower-Diagramms','posts_chart_mode' => 'Ansicht des Beitragsdiagramms','chart_line' => 'Linie',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Keine Follower-Daten der ausgewählten Kanäle in diesem Zeitraum. Versuche einen anderen Zeitraum oder setze den Kanalfilter zurück.','filtered_no_data_title' => 'Nichts entspricht diesen Filtern','filtered_no_data_body' => 'Die ausgewählten Kanäle haben noch keine Analysedaten. Wähle andere Kanäle oder setze die Filter zurück.',- 'posts_sent_axis' => 'Gesendete Beiträge',- 'followers_gained_detail' => 'Start bei :start · :change gewonnen (:percent)',- 'followers_lost_detail' => 'Start bei :start · :change verloren (:percent)','followers_at_start' => 'Zu Beginn','followers_gained_in_range' => 'Hinzugewonnen',+ 'followers_lost_in_range' => 'Verloren','no_excerpt' => 'Keine Textvorschau verfügbar.','published_via' => 'Veröffentlicht über','top_posts_sort' => 'Beiträge sortieren nach',- 'carried_forward' => 'Letzter bekannter Wert',- 'carried_forward_hint' => 'Der Anbieter war nicht verfügbar; dies ist die letzte bekannte Follower-Zahl.','import_in_progress' => 'Der Kontoverlauf wird importiert. Ältere Beiträge erscheinen, während die Erfassung fortschreitet.','no_data_title' => 'Dein Analyseverlauf wird vorbereitet','no_data_body' => 'Verbinde ein unterstütztes Konto oder warte auf die erste Erfassung im Hintergrund. Frühere Beiträge erscheinen während des Imports.',@@ -112,7 +108,8 @@ return ['30d' => '30 Tage','mtd' => 'Aktueller Monat','custom' => 'Benutzerdefiniert',- 'compared_to' => ':current · verglichen mit :previous',+ 'versus' => 'vs. :range',+ 'versus_hint' => 'Die Veränderungen vergleichen diesen Zeitraum mit :range.','label' => 'Zeitraum',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Diagrammzeitraum','both' => 'Beide','comparison' => 'Vergleich',- 'comparison_axis' => ':metric (Vergleich)','not_enough_history' => 'Noch nicht genug Verlauf. Follower werden täglich erfasst – schau bald wieder vorbei.','date' => 'Datum','previous_value' => ':metric (Vorzeitraum)',@@ -416,4 +412,40 @@ return ['columns' => 'Spalten','channels_shown' => ':range · :shown von :total Kanälen angezeigt. Filtere nach Kanal, um andere zu sehen.',],+ 'share' => [+ 'channels_shown' => ':shown von :total Kanälen',+ 'button' => 'Als Bild teilen',+ 'title' => 'Als Bild teilen',+ 'description' => 'Lade das Bild herunter oder mach daraus einen Post für deine Kanäle.',+ 'color' => 'Farbe',+ 'download' => 'Herunterladen',+ 'copy' => 'Bild kopieren',+ 'copied' => 'Bild kopiert',+ 'create_post' => 'Post erstellen',+ 'mark' => 'Erstellt mit TryPost',+ 'copy_failed' => 'Bild konnte nicht kopiert werden. Lade es stattdessen herunter.',+ 'post_failed' => 'Post konnte nicht vorbereitet werden. Versuche es erneut.',+ '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',+ 'export_failed' => 'Bild konnte nicht erstellt werden. Versuche es erneut.',+ 'colors' => [+ 'violet' => 'Violett',+ 'blue' => 'Blau',+ 'green' => 'Grün',+ 'peach' => 'Pfirsich',+ 'yellow' => 'Gelb',+ 'cyan' => 'Cyan',+ 'teal' => 'Petrol',+ 'red' => 'Rot',+ 'pink' => 'Rosa',+ 'neutral' => 'Neutral',+ 'indigo' => 'Indigo',+ 'lime' => 'Limette',+ 'purple' => 'Lila',+ 'fuchsia' => 'Fuchsia',+ 'orange' => 'Orange',+ 'slate' => 'Schiefer',+ ],+ ],];diff --git a/lang/de/posts.php b/lang/de/posts.phpindex e35f9df0c..ecc896a0c 100644--- a/lang/de/posts.php+++ b/lang/de/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Veröffentlichen','all_channels' => 'Alle Kanäle','tabs' => [+ 'label' => 'Status','queue' => 'Warteschlange','approvals' => 'Freigaben','drafts' => 'Entwürfe',diff --git a/lang/el/analytics.php b/lang/el/analytics.phpindex 62b5ac9f6..08ff913d1 100644--- a/lang/el/analytics.php+++ b/lang/el/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Σύνοψη','posts' => 'Δημοσιεύσεις','total_followers' => 'Σύνολο ακολούθων',+ 'total_posts' => 'Σύνολο δημοσιεύσεων','reactions' => 'Αντιδράσεις','comments' => 'Σχόλια','engagement_rate' => 'Ποσοστό αλληλεπίδρασης',@@ -63,7 +64,6 @@ return ['performance' => 'Απόδοση','top_posts' => '5 κορυφαίες δημοσιεύσεις','channel' => 'Κανάλι',- 'latest_snapshot_hint' => 'Οι μετρήσεις των δημοσιεύσεων χρησιμοποιούν την πιο πρόσφατη αποθηκευμένη μέτρηση για αυτή την περίοδο.','followers_chart_mode' => 'Τρόπος εμφάνισης γραφήματος ακολούθων','posts_chart_mode' => 'Τρόπος εμφάνισης γραφήματος δημοσιεύσεων','chart_line' => 'Γραμμή',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Δεν υπάρχουν δεδομένα ακολούθων για τα επιλεγμένα κανάλια σε αυτή την περίοδο. Δοκιμάστε άλλο εύρος ημερομηνιών ή καθαρίστε το φίλτρο καναλιών.','filtered_no_data_title' => 'Τίποτα δεν ταιριάζει με αυτά τα φίλτρα','filtered_no_data_body' => 'Τα επιλεγμένα κανάλια δεν έχουν ακόμη δεδομένα ανάλυσης. Επιλέξτε άλλα κανάλια ή καθαρίστε τα φίλτρα.',- 'posts_sent_axis' => 'Δημοσιεύσεις που στάλθηκαν',- 'followers_gained_detail' => 'Αρχή :start · κέρδος :change (:percent)',- 'followers_lost_detail' => 'Αρχή :start · απώλεια :change (:percent)','followers_at_start' => 'Στην αρχή','followers_gained_in_range' => 'Νέοι',+ 'followers_lost_in_range' => 'Απώλειες','no_excerpt' => 'Δεν υπάρχει διαθέσιμη προεπισκόπηση κειμένου.','published_via' => 'Δημοσιεύτηκε μέσω','top_posts_sort' => 'Ταξινόμηση δημοσιεύσεων κατά',- 'carried_forward' => 'Τελευταία γνωστή τιμή',- 'carried_forward_hint' => 'Η υπηρεσία δεν ήταν διαθέσιμη· αυτός είναι ο τελευταίος γνωστός αριθμός ακολούθων.','import_in_progress' => 'Γίνεται εισαγωγή του ιστορικού λογαριασμού. Οι παλαιότερες δημοσιεύσεις θα εμφανιστούν καθώς προχωρά η συλλογή.','no_data_title' => 'Προετοιμάζουμε το ιστορικό αναλυτικών στοιχείων','no_data_body' => 'Συνδέστε έναν υποστηριζόμενο λογαριασμό ή περιμένετε την πρώτη συλλογή στο παρασκήνιο. Οι παλαιότερες δημοσιεύσεις θα εμφανιστούν κατά την εισαγωγή.',@@ -112,7 +108,8 @@ return ['30d' => '30 ημέρες','mtd' => 'Τρέχων μήνας','custom' => 'Προσαρμοσμένο',- 'compared_to' => ':current · σε σύγκριση με :previous',+ 'versus' => 'έναντι :range',+ 'versus_hint' => 'Οι μεταβολές συγκρίνουν αυτή την περίοδο με :range.','label' => 'Εύρος ημερομηνιών',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Περίοδος γραφήματος','both' => 'Και τα δύο','comparison' => 'Σύγκριση',- 'comparison_axis' => ':metric (σύγκριση)','not_enough_history' => 'Δεν υπάρχει ακόμη αρκετό ιστορικό. Οι ακόλουθοι καταγράφονται καθημερινά, ελέγξτε σύντομα.','date' => 'Ημερομηνία','previous_value' => ':metric (προηγούμενη περίοδος)',@@ -416,4 +412,40 @@ return ['columns' => 'Στήλες','channels_shown' => ':range · Εμφανίζονται :shown από :total κανάλια. Φίλτραρε ανά κανάλι για να δεις άλλα.',],+ 'share' => [+ 'channels_shown' => ':shown από :total κανάλια',+ 'button' => 'Κοινοποίηση ως εικόνα',+ 'title' => 'Κοινοποίηση ως εικόνα',+ 'description' => 'Κατεβάστε την εικόνα ή κάντε την ανάρτηση για τα κανάλια σας.',+ 'color' => 'Χρώμα',+ 'download' => 'Λήψη',+ 'copy' => 'Αντιγραφή',+ 'copied' => 'Η εικόνα αντιγράφηκε',+ 'create_post' => 'Νέα ανάρτηση',+ 'mark' => 'Φτιαγμένο με το TryPost',+ 'copy_failed' => 'Η εικόνα δεν αντιγράφηκε. Κατεβάστε την.',+ 'post_failed' => 'Η ανάρτηση δεν ετοιμάστηκε. Δοκιμάστε ξανά.',+ 'caption_workspace' => ':metric στα κανάλια μας: :value (:range) 📈',+ 'caption_summary_workspace' => 'Τα νούμερά μας για :range 📈 :metrics',+ 'caption_summary_channel' => 'Τα νούμερά μας στο :channel για :range 📈 :metrics',+ 'export_failed' => 'Η εικόνα δεν δημιουργήθηκε. Δοκιμάστε ξανά.',+ 'colors' => [+ 'violet' => 'Βιολετί',+ 'blue' => 'Μπλε',+ 'green' => 'Πράσινο',+ 'peach' => 'Ροδακινί',+ 'yellow' => 'Κίτρινο',+ 'cyan' => 'Κυανό',+ 'teal' => 'Πετρόλ',+ 'red' => 'Κόκκινο',+ 'pink' => 'Ροζ',+ 'neutral' => 'Ουδέτερο',+ 'indigo' => 'Λουλακί',+ 'lime' => 'Λάιμ',+ 'purple' => 'Πορφυρό',+ 'fuchsia' => 'Φούξια',+ 'orange' => 'Πορτοκαλί',+ 'slate' => 'Σχιστόλιθος',+ ],+ ],];diff --git a/lang/el/posts.php b/lang/el/posts.phpindex 1ced4d237..e2439550f 100644--- a/lang/el/posts.php+++ b/lang/el/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Δημοσίευση','all_channels' => 'Όλα τα κανάλια','tabs' => [+ 'label' => 'Κατάσταση','queue' => 'Ουρά','approvals' => 'Εγκρίσεις','drafts' => 'Πρόχειρα',diff --git a/lang/en/analytics.php b/lang/en/analytics.phpindex 22337cd0d..fc63d2415 100644--- a/lang/en/analytics.php+++ b/lang/en/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Summary','posts' => 'Posts','total_followers' => 'Total Followers',+ 'total_posts' => 'Total Posts','reactions' => 'Reactions','comments' => 'Comments','engagement_rate' => 'Eng. Rate',@@ -63,7 +64,6 @@ return ['performance' => 'Performance','top_posts' => 'Top 5 Posts','channel' => 'Channel',- 'latest_snapshot_hint' => 'Post metrics use the latest saved observation for posts published in this range.','followers_chart_mode' => 'Follower chart mode','posts_chart_mode' => 'Post chart mode','chart_line' => 'Line',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'No follower data for the selected channels in this period. Try another date range or clear the channel filter.','filtered_no_data_title' => 'Nothing matches these filters','filtered_no_data_body' => 'The selected channels have no analytics data yet. Pick other channels or clear the filters.',- 'posts_sent_axis' => 'Posts sent',- 'followers_gained_detail' => 'Started at :start · gained :change (:percent)',- 'followers_lost_detail' => 'Started at :start · lost :change (:percent)','followers_at_start' => 'At range start','followers_gained_in_range' => 'Gained in range',+ 'followers_lost_in_range' => 'Lost in range','no_excerpt' => 'No text preview available.','published_via' => 'Published via','top_posts_sort' => 'Rank posts by',- 'carried_forward' => 'Last known',- 'carried_forward_hint' => 'The provider was unavailable; this is the last known follower count.','import_in_progress' => 'Importing account history. Older posts may appear as collection continues.','no_data_title' => 'Your analytics history is being prepared','no_data_body' => 'Connect a supported account or wait for the first background collection. Historical posts appear as they are imported.',@@ -112,7 +108,8 @@ return ['30d' => '30 days','mtd' => 'Month to date','custom' => 'Custom',- 'compared_to' => ':current · Compared to :previous',+ 'versus' => 'vs :range',+ 'versus_hint' => 'Changes compare this period with :range.','label' => 'Date range',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Chart period','both' => 'Both','comparison' => 'Comparison',- 'comparison_axis' => ':metric (comparison)','not_enough_history' => 'Not enough history yet. Follower counts build up day by day, so check back soon.','date' => 'Date','previous_value' => ':metric (previous period)',@@ -416,4 +412,40 @@ return ['columns' => 'Columns','channels_shown' => ':range · Showing :shown of :total channels. Filter by channel to see a different set.',],+ 'share' => [+ 'channels_shown' => ':shown of :total channels',+ 'button' => 'Share as image',+ 'title' => 'Share as image',+ 'description' => 'Download the image, or turn it into a post for your channels.',+ 'color' => 'Color',+ 'download' => 'Download',+ 'copy' => 'Copy image',+ 'copied' => 'Image copied',+ 'create_post' => 'Create post',+ 'mark' => 'Made with TryPost',+ 'copy_failed' => 'Couldn\'t copy the image. Download it instead.',+ 'post_failed' => 'Couldn\'t prepare the post. Try again.',+ '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',+ 'export_failed' => 'Couldn\'t create the image. Try again.',+ 'colors' => [+ 'violet' => 'Violet',+ 'blue' => 'Blue',+ 'green' => 'Green',+ 'peach' => 'Peach',+ 'yellow' => 'Yellow',+ 'cyan' => 'Cyan',+ 'teal' => 'Teal',+ 'red' => 'Red',+ 'pink' => 'Pink',+ 'neutral' => 'Neutral',+ 'indigo' => 'Indigo',+ 'lime' => 'Lime',+ 'purple' => 'Purple',+ 'fuchsia' => 'Fuchsia',+ 'orange' => 'Orange',+ 'slate' => 'Slate',+ ],+ ],];diff --git a/lang/en/posts.php b/lang/en/posts.phpindex 2d2728e7d..1e5c3b5dd 100644--- a/lang/en/posts.php+++ b/lang/en/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Publish','all_channels' => 'All channels','tabs' => [+ 'label' => 'Status','queue' => 'Queue','approvals' => 'Approvals','drafts' => 'Drafts',diff --git a/lang/es/analytics.php b/lang/es/analytics.phpindex 83c778fb7..fec3c232e 100644--- a/lang/es/analytics.php+++ b/lang/es/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Resumen','posts' => 'Publicaciones','total_followers' => 'Total de seguidores',+ 'total_posts' => 'Total de publicaciones','reactions' => 'Reacciones','comments' => 'Comentarios','engagement_rate' => 'Tasa de interacción',@@ -63,7 +64,6 @@ return ['performance' => 'Rendimiento','top_posts' => '5 publicaciones destacadas','channel' => 'Canal',- 'latest_snapshot_hint' => 'Las métricas de las publicaciones usan la última medición guardada para las publicaciones de este período.','followers_chart_mode' => 'Tipo de gráfico de seguidores','posts_chart_mode' => 'Tipo de gráfico de publicaciones','chart_line' => 'Línea',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'No hay datos de seguidores de los canales seleccionados en este período. Prueba otro rango de fechas o borra el filtro de canales.','filtered_no_data_title' => 'Nada coincide con estos filtros','filtered_no_data_body' => 'Los canales seleccionados aún no tienen datos de analítica. Elige otros canales o borra los filtros.',- 'posts_sent_axis' => 'Publicaciones enviadas',- 'followers_gained_detail' => 'Empezó con :start · ganó :change (:percent)',- 'followers_lost_detail' => 'Empezó con :start · perdió :change (:percent)','followers_at_start' => 'Al inicio','followers_gained_in_range' => 'Ganados en el periodo',+ 'followers_lost_in_range' => 'Perdidos en el periodo','no_excerpt' => 'No hay vista previa de texto disponible.','published_via' => 'Publicado vía','top_posts_sort' => 'Ordenar publicaciones por',- 'carried_forward' => 'Último valor conocido',- 'carried_forward_hint' => 'El proveedor no estaba disponible; este es el último número conocido de seguidores.','import_in_progress' => 'Importando el historial de la cuenta. Las publicaciones antiguas aparecerán a medida que avance la recopilación.','no_data_title' => 'Estamos preparando tu historial de estadísticas','no_data_body' => 'Conecta una cuenta compatible o espera a la primera recopilación en segundo plano. Las publicaciones anteriores aparecerán durante la importación.',@@ -112,7 +108,8 @@ return ['30d' => '30 días','mtd' => 'Mes actual','custom' => 'Personalizado',- 'compared_to' => ':current · comparado con :previous',+ 'versus' => 'vs. :range',+ 'versus_hint' => 'Las variaciones comparan este período con :range.','label' => 'Rango de fechas',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Periodo del gráfico','both' => 'Ambos','comparison' => 'Comparación',- 'comparison_axis' => ':metric (comparación)','not_enough_history' => 'Todavía no hay historial suficiente. Los seguidores se registran día a día; vuelve pronto.','date' => 'Fecha','previous_value' => ':metric (periodo anterior)',@@ -416,4 +412,40 @@ return ['columns' => 'Columnas','channels_shown' => ':range · Mostrando :shown de :total canales. Filtra por canal para ver otro conjunto.',],+ 'share' => [+ 'channels_shown' => ':shown de :total canales',+ 'button' => 'Compartir como imagen',+ 'title' => 'Compartir como imagen',+ 'description' => 'Descarga la imagen o conviértela en una publicación para tus canales.',+ 'color' => 'Color',+ 'download' => 'Descargar',+ 'copy' => 'Copiar imagen',+ 'copied' => 'Imagen copiada',+ 'create_post' => 'Crear publicación',+ 'mark' => 'Hecho con TryPost',+ 'copy_failed' => 'No se pudo copiar la imagen. Descárgala.',+ 'post_failed' => 'No se pudo preparar la publicación. Inténtalo de nuevo.',+ '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',+ 'export_failed' => 'No se pudo crear la imagen. Inténtalo de nuevo.',+ 'colors' => [+ 'violet' => 'Violeta',+ 'blue' => 'Azul',+ 'green' => 'Verde',+ 'peach' => 'Melocotón',+ 'yellow' => 'Amarillo',+ 'cyan' => 'Cian',+ 'teal' => 'Verde azulado',+ 'red' => 'Rojo',+ 'pink' => 'Rosa',+ 'neutral' => 'Neutro',+ 'indigo' => 'Índigo',+ 'lime' => 'Lima',+ 'purple' => 'Morado',+ 'fuchsia' => 'Fucsia',+ 'orange' => 'Naranja',+ 'slate' => 'Pizarra',+ ],+ ],];diff --git a/lang/es/posts.php b/lang/es/posts.phpindex c8e7c5cb9..2a75c3875 100644--- a/lang/es/posts.php+++ b/lang/es/posts.php@@ -925,6 +925,7 @@ return ['title' => 'Publicar','all_channels' => 'Todos los canales','tabs' => [+ 'label' => 'Estado','queue' => 'Cola','approvals' => 'Aprobaciones','drafts' => 'Borradores',diff --git a/lang/fr/analytics.php b/lang/fr/analytics.phpindex e32b11d35..04a551d00 100644--- a/lang/fr/analytics.php+++ b/lang/fr/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Résumé','posts' => 'Publications','total_followers' => 'Total des abonnés',+ 'total_posts' => 'Total des publications','reactions' => 'Réactions','comments' => 'Commentaires','engagement_rate' => 'Taux d’engagement',@@ -63,7 +64,6 @@ return ['performance' => 'Performances','top_posts' => 'Top 5 des publications','channel' => 'Canal',- 'latest_snapshot_hint' => 'Les métriques des publications utilisent la dernière mesure enregistrée pour les publications de cette période.','followers_chart_mode' => 'Type de graphique des abonnés','posts_chart_mode' => 'Type de graphique des publications','chart_line' => 'Courbe',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Aucune donnée d’abonnés pour les canaux sélectionnés sur cette période. Essayez une autre plage de dates ou effacez le filtre de canaux.','filtered_no_data_title' => 'Rien ne correspond à ces filtres','filtered_no_data_body' => 'Les canaux sélectionnés n’ont pas encore de données d’analyse. Choisissez d’autres canaux ou effacez les filtres.',- 'posts_sent_axis' => 'Publications envoyées',- 'followers_gained_detail' => 'Départ à :start · :change gagnés (:percent)',- 'followers_lost_detail' => 'Départ à :start · :change perdus (:percent)','followers_at_start' => 'Au début','followers_gained_in_range' => 'Gagnés',+ 'followers_lost_in_range' => 'Perdus','no_excerpt' => 'Aucun aperçu textuel disponible.','published_via' => 'Publié via','top_posts_sort' => 'Classer les publications par',- 'carried_forward' => 'Dernière valeur connue',- 'carried_forward_hint' => 'Le service était indisponible ; voici le dernier nombre connu d’abonnés.','import_in_progress' => 'Importation de l’historique du compte. Les anciennes publications apparaîtront au fil de la collecte.','no_data_title' => 'Nous préparons votre historique de statistiques','no_data_body' => 'Connectez un compte compatible ou attendez la première collecte en arrière-plan. Les publications historiques apparaîtront pendant l’importation.',@@ -112,7 +108,8 @@ return ['30d' => '30 jours','mtd' => 'Mois en cours','custom' => 'Personnalisé',- 'compared_to' => ':current · comparé à :previous',+ 'versus' => 'vs :range',+ 'versus_hint' => 'Les variations comparent cette période à :range.','label' => 'Période',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Période du graphique','both' => 'Les deux','comparison' => 'Comparaison',- 'comparison_axis' => ':metric (comparaison)','not_enough_history' => 'Pas encore assez d’historique. Les abonnés sont relevés jour après jour : revenez bientôt.','date' => 'Date','previous_value' => ':metric (période précédente)',@@ -416,4 +412,40 @@ return ['columns' => 'Colonnes','channels_shown' => ':range · :shown canaux affichés sur :total. Filtrez par canal pour en voir d\'autres.',],+ 'share' => [+ 'channels_shown' => ':shown canaux sur :total',+ 'button' => 'Partager en image',+ 'title' => 'Partager en image',+ 'description' => 'Téléchargez l’image ou transformez-la en publication pour vos canaux.',+ 'color' => 'Couleur',+ 'download' => 'Télécharger',+ 'copy' => 'Copier l’image',+ 'copied' => 'Image copiée',+ 'create_post' => 'Créer un post',+ 'mark' => 'Fait avec TryPost',+ 'copy_failed' => 'Impossible de copier l’image. Téléchargez-la.',+ 'post_failed' => 'Impossible de préparer le post. Réessayez.',+ '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',+ 'export_failed' => 'Impossible de créer l’image. Réessayez.',+ 'colors' => [+ 'violet' => 'Violet',+ 'blue' => 'Bleu',+ 'green' => 'Vert',+ 'peach' => 'Pêche',+ 'yellow' => 'Jaune',+ 'cyan' => 'Cyan',+ 'teal' => 'Bleu-vert',+ 'red' => 'Rouge',+ 'pink' => 'Rose',+ 'neutral' => 'Neutre',+ 'indigo' => 'Indigo',+ 'lime' => 'Citron vert',+ 'purple' => 'Pourpre',+ 'fuchsia' => 'Fuchsia',+ 'orange' => 'Orange',+ 'slate' => 'Ardoise',+ ],+ ],];diff --git a/lang/fr/posts.php b/lang/fr/posts.phpindex 0d01926fb..afcd6365f 100644--- a/lang/fr/posts.php+++ b/lang/fr/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Publier','all_channels' => 'Tous les canaux','tabs' => [+ 'label' => 'Statut','queue' => 'File d\'attente','approvals' => 'Approbations','drafts' => 'Brouillons',diff --git a/lang/it/analytics.php b/lang/it/analytics.phpindex ebdfe0988..2778310e4 100644--- a/lang/it/analytics.php+++ b/lang/it/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Riepilogo','posts' => 'Post','total_followers' => 'Follower totali',+ 'total_posts' => 'Post totali','reactions' => 'Reazioni','comments' => 'Commenti','engagement_rate' => 'Tasso di coinvolgimento',@@ -63,7 +64,6 @@ return ['performance' => 'Prestazioni','top_posts' => 'I 5 post migliori','channel' => 'Canale',- 'latest_snapshot_hint' => 'Le metriche dei post utilizzano l’ultima misurazione salvata per i post pubblicati in questo intervallo.','followers_chart_mode' => 'Tipo di grafico dei follower','posts_chart_mode' => 'Tipo di grafico dei post','chart_line' => 'Linea',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Nessun dato sui follower per i canali selezionati in questo periodo. Prova un altro intervallo di date o cancella il filtro dei canali.','filtered_no_data_title' => 'Nessun risultato per questi filtri','filtered_no_data_body' => 'I canali selezionati non hanno ancora dati di analisi. Scegli altri canali o cancella i filtri.',- 'posts_sent_axis' => 'Post inviati',- 'followers_gained_detail' => 'Partito da :start · guadagnati :change (:percent)',- 'followers_lost_detail' => 'Partito da :start · persi :change (:percent)','followers_at_start' => 'All’inizio','followers_gained_in_range' => 'Guadagnati',+ 'followers_lost_in_range' => 'Persi','no_excerpt' => 'Anteprima del testo non disponibile.','published_via' => 'Pubblicato tramite','top_posts_sort' => 'Ordina i post per',- 'carried_forward' => 'Ultimo valore noto',- 'carried_forward_hint' => 'Il servizio non era disponibile; questo è l’ultimo numero noto di follower.','import_in_progress' => 'Importazione della cronologia dell’account. I post meno recenti appariranno man mano che procede la raccolta.','no_data_title' => 'Stiamo preparando la cronologia delle statistiche','no_data_body' => 'Collega un account supportato o attendi la prima raccolta in background. I post precedenti appariranno durante l’importazione.',@@ -112,7 +108,8 @@ return ['30d' => '30 giorni','mtd' => 'Mese corrente','custom' => 'Personalizzato',- 'compared_to' => ':current · confrontato con :previous',+ 'versus' => 'vs :range',+ 'versus_hint' => 'Le variazioni confrontano questo periodo con :range.','label' => 'Intervallo di date',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Periodo del grafico','both' => 'Entrambi','comparison' => 'Confronto',- 'comparison_axis' => ':metric (confronto)','not_enough_history' => 'Non c’è ancora abbastanza storico. I follower vengono registrati giorno per giorno: torna presto.','date' => 'Data','previous_value' => ':metric (periodo precedente)',@@ -416,4 +412,40 @@ return ['columns' => 'Colonne','channels_shown' => ':range · Mostrati :shown canali su :total. Filtra per canale per vederne altri.',],+ 'share' => [+ 'channels_shown' => ':shown canali su :total',+ 'button' => 'Condividi come immagine',+ 'title' => 'Condividi come immagine',+ 'description' => 'Scarica l’immagine o trasformala in un post per i tuoi canali.',+ 'color' => 'Colore',+ 'download' => 'Scarica',+ 'copy' => 'Copia immagine',+ 'copied' => 'Immagine copiata',+ 'create_post' => 'Crea post',+ 'mark' => 'Fatto con TryPost',+ 'copy_failed' => 'Impossibile copiare l’immagine. Scaricala.',+ 'post_failed' => 'Impossibile preparare il post. Riprova.',+ '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',+ 'export_failed' => 'Impossibile creare l’immagine. Riprova.',+ 'colors' => [+ 'violet' => 'Viola',+ 'blue' => 'Blu',+ 'green' => 'Verde',+ 'peach' => 'Pesca',+ 'yellow' => 'Giallo',+ 'cyan' => 'Ciano',+ 'teal' => 'Verde acqua',+ 'red' => 'Rosso',+ 'pink' => 'Rosa',+ 'neutral' => 'Neutro',+ 'indigo' => 'Indaco',+ 'lime' => 'Lime',+ 'purple' => 'Viola scuro',+ 'fuchsia' => 'Fucsia',+ 'orange' => 'Arancione',+ 'slate' => 'Ardesia',+ ],+ ],];diff --git a/lang/it/posts.php b/lang/it/posts.phpindex 2a7635429..99460e6d1 100644--- a/lang/it/posts.php+++ b/lang/it/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Pubblica','all_channels' => 'Tutti i canali','tabs' => [+ 'label' => 'Stato','queue' => 'Coda','approvals' => 'Approvazioni','drafts' => 'Bozze',diff --git a/lang/ja/analytics.php b/lang/ja/analytics.phpindex 6c515a306..e36b289a7 100644--- a/lang/ja/analytics.php+++ b/lang/ja/analytics.php@@ -56,6 +56,7 @@ return ['summary' => '概要','posts' => '投稿','total_followers' => 'フォロワー合計',+ 'total_posts' => '投稿合計','reactions' => 'リアクション','comments' => 'コメント','engagement_rate' => 'エンゲージメント率',@@ -63,7 +64,6 @@ return ['performance' => 'パフォーマンス','top_posts' => '上位5件の投稿','channel' => 'チャンネル',- 'latest_snapshot_hint' => 'この期間の投稿指標には、保存済みの最新の測定値を使用します。','followers_chart_mode' => 'フォロワーグラフの表示方法','posts_chart_mode' => '投稿グラフの表示方法','chart_line' => '折れ線',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'この期間、選択したチャンネルのフォロワーデータはありません。別の期間を試すか、チャンネルフィルターをクリアしてください。','filtered_no_data_title' => 'このフィルターに一致するものはありません','filtered_no_data_body' => '選択したチャンネルにはまだ分析データがありません。別のチャンネルを選ぶか、フィルターをクリアしてください。',- 'posts_sent_axis' => '送信した投稿',- 'followers_gained_detail' => '開始時 :start · :change 増加 (:percent)',- 'followers_lost_detail' => '開始時 :start · :change 減少 (:percent)','followers_at_start' => '期間開始時','followers_gained_in_range' => '期間中の増加',+ 'followers_lost_in_range' => '期間中の減少','no_excerpt' => 'テキストのプレビューはありません。','published_via' => '公開元:','top_posts_sort' => '投稿の並べ替え基準',- 'carried_forward' => '最後に確認された値',- 'carried_forward_hint' => 'サービスに接続できなかったため、最後に確認されたフォロワー数を表示しています。','import_in_progress' => 'アカウント履歴を取り込んでいます。古い投稿は収集が進むにつれて表示されます。','no_data_title' => '分析履歴を準備しています','no_data_body' => '対応するアカウントを接続するか、最初のバックグラウンド収集をお待ちください。過去の投稿は取り込み中に表示されます。',@@ -112,7 +108,8 @@ return ['30d' => '30日間','mtd' => '今月','custom' => 'カスタム',- 'compared_to' => ':current · :previous と比較',+ 'versus' => ':rangeと比較',+ 'versus_hint' => '変化はこの期間を:rangeと比較しています。','label' => '期間',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'グラフの期間','both' => '両方','comparison' => '比較',- 'comparison_axis' => ':metric(比較)','not_enough_history' => 'まだ十分な履歴がありません。フォロワー数は毎日記録されるので、しばらくしてから確認してください。','date' => '日付','previous_value' => ':metric(前期間)',@@ -416,4 +412,40 @@ return ['columns' => '列','channels_shown' => ':range · :total チャンネル中 :shown 件を表示中。別のチャンネルを見るにはチャンネルで絞り込んでください。',],+ 'share' => [+ 'channels_shown' => ':total チャンネル中 :shown 件',+ 'button' => '画像で共有',+ 'title' => '画像で共有',+ 'description' => '画像をダウンロードするか、チャンネル用の投稿にできます。',+ 'color' => '色',+ 'download' => 'ダウンロード',+ 'copy' => '画像をコピー',+ 'copied' => '画像をコピーしました',+ 'create_post' => '投稿を作成',+ 'mark' => 'TryPost で作成',+ 'copy_failed' => '画像をコピーできませんでした。ダウンロードしてください。',+ 'post_failed' => '投稿を準備できませんでした。もう一度お試しください。',+ 'caption_workspace' => '全チャンネルの:metric: :value (:range) 📈',+ 'caption_summary_workspace' => ':rangeの数字 📈 :metrics',+ 'caption_summary_channel' => ':channelの:rangeの数字 📈 :metrics',+ 'export_failed' => '画像を作成できませんでした。もう一度お試しください。',+ 'colors' => [+ 'violet' => 'バイオレット',+ 'blue' => 'ブルー',+ 'green' => 'グリーン',+ 'peach' => 'ピーチ',+ 'yellow' => 'イエロー',+ 'cyan' => 'シアン',+ 'teal' => 'ティール',+ 'red' => 'レッド',+ 'pink' => 'ピンク',+ 'neutral' => 'ニュートラル',+ 'indigo' => 'インディゴ',+ 'lime' => 'ライム',+ 'purple' => 'パープル',+ 'fuchsia' => 'フクシア',+ 'orange' => 'オレンジ',+ 'slate' => 'スレート',+ ],+ ],];diff --git a/lang/ja/posts.php b/lang/ja/posts.phpindex b48daa800..2d166f5fe 100644--- a/lang/ja/posts.php+++ b/lang/ja/posts.php@@ -922,8 +922,9 @@ return [],'publish' => ['title' => '公開',- 'all_channels' => 'すべてのチャンネル',+ 'all_channels' => '全チャンネル','tabs' => [+ 'label' => 'ステータス','queue' => 'キュー','approvals' => '承認','drafts' => '下書き',diff --git a/lang/ko/analytics.php b/lang/ko/analytics.phpindex e7dd10381..143aeb334 100644--- a/lang/ko/analytics.php+++ b/lang/ko/analytics.php@@ -56,6 +56,7 @@ return ['summary' => '요약','posts' => '게시물','total_followers' => '총 팔로워',+ 'total_posts' => '총 게시물','reactions' => '반응','comments' => '댓글','engagement_rate' => '참여율',@@ -63,7 +64,6 @@ return ['performance' => '성과','top_posts' => '상위 게시물 5개','channel' => '채널',- 'latest_snapshot_hint' => '이 기간에 게시된 게시물의 지표는 마지막으로 저장된 측정값을 사용합니다.','followers_chart_mode' => '팔로워 차트 표시 방식','posts_chart_mode' => '게시물 차트 표시 방식','chart_line' => '선',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => '이 기간에 선택한 채널의 팔로워 데이터가 없습니다. 다른 기간을 선택하거나 채널 필터를 지우세요.','filtered_no_data_title' => '이 필터와 일치하는 항목이 없습니다','filtered_no_data_body' => '선택한 채널에 아직 분석 데이터가 없습니다. 다른 채널을 선택하거나 필터를 지우세요.',- 'posts_sent_axis' => '보낸 게시물',- 'followers_gained_detail' => '시작 :start · :change 증가 (:percent)',- 'followers_lost_detail' => '시작 :start · :change 감소 (:percent)','followers_at_start' => '기간 시작','followers_gained_in_range' => '기간 중 증가',+ 'followers_lost_in_range' => '기간 중 감소','no_excerpt' => '텍스트 미리보기가 없습니다.','published_via' => '게시 경로:','top_posts_sort' => '게시물 정렬 기준',- 'carried_forward' => '마지막으로 확인된 값',- 'carried_forward_hint' => '서비스를 사용할 수 없어 마지막으로 확인된 팔로워 수를 표시합니다.','import_in_progress' => '계정 기록을 가져오는 중입니다. 수집이 진행되면 이전 게시물이 표시됩니다.','no_data_title' => '분석 기록을 준비하고 있습니다','no_data_body' => '지원되는 계정을 연결하거나 첫 백그라운드 수집을 기다려 주세요. 가져오는 동안 이전 게시물이 표시됩니다.',@@ -112,7 +108,8 @@ return ['30d' => '30일','mtd' => '이번 달','custom' => '사용자 지정',- 'compared_to' => ':current · :previous 대비',+ 'versus' => ':range 대비',+ 'versus_hint' => '변화는 이 기간을 :range와 비교합니다.','label' => '기간',],@@ -156,7 +153,6 @@ return ['chart_mode' => '차트 기간','both' => '둘 다','comparison' => '비교',- 'comparison_axis' => ':metric (비교)','not_enough_history' => '아직 기록이 충분하지 않습니다. 팔로워 수는 매일 기록되니 곧 다시 확인해 주세요.','date' => '날짜','previous_value' => ':metric (이전 기간)',@@ -416,4 +412,40 @@ return ['columns' => '열','channels_shown' => ':range · 채널 :total개 중 :shown개 표시 중. 다른 채널을 보려면 채널로 필터링하세요.',],+ 'share' => [+ 'channels_shown' => '채널 :total개 중 :shown개',+ 'button' => '이미지로 공유',+ 'title' => '이미지로 공유',+ 'description' => '이미지를 다운로드하거나 채널용 게시물로 만드세요.',+ 'color' => '색상',+ 'download' => '다운로드',+ 'copy' => '이미지 복사',+ 'copied' => '이미지를 복사했어요',+ 'create_post' => '게시물 만들기',+ 'mark' => 'TryPost로 제작',+ 'copy_failed' => '이미지를 복사하지 못했어요. 대신 다운로드하세요.',+ 'post_failed' => '게시물을 준비하지 못했어요. 다시 시도하세요.',+ 'caption_workspace' => '전체 채널 :metric: :value (:range) 📈',+ 'caption_summary_workspace' => ':range 우리 숫자 📈 :metrics',+ 'caption_summary_channel' => ':channel의 :range 숫자 📈 :metrics',+ 'export_failed' => '이미지를 만들지 못했어요. 다시 시도하세요.',+ 'colors' => [+ 'violet' => '바이올렛',+ 'blue' => '파랑',+ 'green' => '초록',+ 'peach' => '피치',+ 'yellow' => '노랑',+ 'cyan' => '청록',+ 'teal' => '틸',+ 'red' => '빨강',+ 'pink' => '분홍',+ 'neutral' => '뉴트럴',+ 'indigo' => '인디고',+ 'lime' => '라임',+ 'purple' => '퍼플',+ 'fuchsia' => '푸크시아',+ 'orange' => '오렌지',+ 'slate' => '슬레이트',+ ],+ ],];diff --git a/lang/ko/posts.php b/lang/ko/posts.phpindex f08370fd8..0d0abc5a8 100644--- a/lang/ko/posts.php+++ b/lang/ko/posts.php@@ -924,6 +924,7 @@ return ['title' => '게시','all_channels' => '모든 채널','tabs' => [+ 'label' => '상태','queue' => '대기열','approvals' => '승인','drafts' => '임시 저장',diff --git a/lang/nl/analytics.php b/lang/nl/analytics.phpindex b0a7810a2..df949e005 100644--- a/lang/nl/analytics.php+++ b/lang/nl/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Overzicht','posts' => 'Berichten','total_followers' => 'Totaal aantal volgers',+ 'total_posts' => 'Totaal aantal berichten','reactions' => 'Reacties','comments' => 'Opmerkingen','engagement_rate' => 'Betrokkenheidspercentage',@@ -63,7 +64,6 @@ return ['performance' => 'Prestaties','top_posts' => 'Top 5 berichten','channel' => 'Kanaal',- 'latest_snapshot_hint' => 'Voor berichten in deze periode wordt de laatst opgeslagen meting gebruikt.','followers_chart_mode' => 'Weergave van de volgersgrafiek','posts_chart_mode' => 'Weergave van de berichtengrafiek','chart_line' => 'Lijn',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Geen volgersgegevens voor de geselecteerde kanalen in deze periode. Probeer een ander datumbereik of wis het kanaalfilter.','filtered_no_data_title' => 'Niets komt overeen met deze filters','filtered_no_data_body' => 'De geselecteerde kanalen hebben nog geen analysegegevens. Kies andere kanalen of wis de filters.',- 'posts_sent_axis' => 'Verzonden berichten',- 'followers_gained_detail' => 'Begonnen met :start · :change gewonnen (:percent)',- 'followers_lost_detail' => 'Begonnen met :start · :change verloren (:percent)','followers_at_start' => 'Bij de start','followers_gained_in_range' => 'Erbij gekomen',+ 'followers_lost_in_range' => 'Kwijtgeraakt','no_excerpt' => 'Geen tekstvoorbeeld beschikbaar.','published_via' => 'Gepubliceerd via','top_posts_sort' => 'Berichten rangschikken op',- 'carried_forward' => 'Laatst bekende waarde',- 'carried_forward_hint' => 'De aanbieder was niet beschikbaar; dit is het laatst bekende aantal volgers.','import_in_progress' => 'Accountgeschiedenis wordt geïmporteerd. Oudere berichten verschijnen naarmate het verzamelen vordert.','no_data_title' => 'Je statistiekgeschiedenis wordt voorbereid','no_data_body' => 'Koppel een ondersteund account of wacht op de eerste verzameling op de achtergrond. Eerdere berichten verschijnen tijdens de import.',@@ -112,7 +108,8 @@ return ['30d' => '30 dagen','mtd' => 'Huidige maand','custom' => 'Aangepast',- 'compared_to' => ':current · vergeleken met :previous',+ 'versus' => 'vs. :range',+ 'versus_hint' => 'De veranderingen vergelijken deze periode met :range.','label' => 'Datumbereik',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Grafiekperiode','both' => 'Beide','comparison' => 'Vergelijking',- 'comparison_axis' => ':metric (vergelijking)','not_enough_history' => 'Nog niet genoeg geschiedenis. Volgers worden dag voor dag bijgehouden, kom snel terug.','date' => 'Datum','previous_value' => ':metric (vorige periode)',@@ -416,4 +412,40 @@ return ['columns' => 'Kolommen','channels_shown' => ':range · :shown van :total kanalen getoond. Filter op kanaal om andere te zien.',],+ 'share' => [+ 'channels_shown' => ':shown van :total kanalen',+ 'button' => 'Delen als afbeelding',+ 'title' => 'Delen als afbeelding',+ 'description' => 'Download de afbeelding of maak er een post van voor je kanalen.',+ 'color' => 'Kleur',+ 'download' => 'Downloaden',+ 'copy' => 'Afbeelding kopiëren',+ 'copied' => 'Afbeelding gekopieerd',+ 'create_post' => 'Post maken',+ 'mark' => 'Gemaakt met TryPost',+ 'copy_failed' => 'Kan de afbeelding niet kopiëren. Download hem in plaats daarvan.',+ 'post_failed' => 'Kan de post niet voorbereiden. Probeer het opnieuw.',+ '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',+ 'export_failed' => 'Kan de afbeelding niet maken. Probeer het opnieuw.',+ 'colors' => [+ 'violet' => 'Violet',+ 'blue' => 'Blauw',+ 'green' => 'Groen',+ 'peach' => 'Perzik',+ 'yellow' => 'Geel',+ 'cyan' => 'Cyaan',+ 'teal' => 'Blauwgroen',+ 'red' => 'Rood',+ 'pink' => 'Roze',+ 'neutral' => 'Neutraal',+ 'indigo' => 'Indigo',+ 'lime' => 'Limoen',+ 'purple' => 'Paars',+ 'fuchsia' => 'Fuchsia',+ 'orange' => 'Oranje',+ 'slate' => 'Leisteen',+ ],+ ],];diff --git a/lang/nl/posts.php b/lang/nl/posts.phpindex f8d434fab..4d505f24e 100644--- a/lang/nl/posts.php+++ b/lang/nl/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Publiceren','all_channels' => 'Alle kanalen','tabs' => [+ 'label' => 'Status','queue' => 'Wachtrij','approvals' => 'Goedkeuringen','drafts' => 'Concepten',diff --git a/lang/pl/analytics.php b/lang/pl/analytics.phpindex a9737e118..940cab1d9 100644--- a/lang/pl/analytics.php+++ b/lang/pl/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Podsumowanie','posts' => 'Posty','total_followers' => 'Łączna liczba obserwujących',+ 'total_posts' => 'Łączna liczba postów','reactions' => 'Reakcje','comments' => 'Komentarze','engagement_rate' => 'Wskaźnik zaangażowania',@@ -63,7 +64,6 @@ return ['performance' => 'Wyniki','top_posts' => '5 najlepszych postów','channel' => 'Kanał',- 'latest_snapshot_hint' => 'Metryki postów korzystają z ostatniego zapisanego pomiaru dla postów opublikowanych w tym okresie.','followers_chart_mode' => 'Widok wykresu obserwujących','posts_chart_mode' => 'Widok wykresu postów','chart_line' => 'Liniowy',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Brak danych o obserwujących dla wybranych kanałów w tym okresie. Wybierz inny zakres dat lub wyczyść filtr kanałów.','filtered_no_data_title' => 'Nic nie pasuje do tych filtrów','filtered_no_data_body' => 'Wybrane kanały nie mają jeszcze danych analitycznych. Wybierz inne kanały lub wyczyść filtry.',- 'posts_sent_axis' => 'Wysłane posty',- 'followers_gained_detail' => 'Początkowo :start · zyskano :change (:percent)',- 'followers_lost_detail' => 'Początkowo :start · stracono :change (:percent)','followers_at_start' => 'Na starcie','followers_gained_in_range' => 'Zyskani',+ 'followers_lost_in_range' => 'Utraceni','no_excerpt' => 'Podgląd tekstu jest niedostępny.','published_via' => 'Opublikowano przez','top_posts_sort' => 'Sortuj posty według',- 'carried_forward' => 'Ostatnia znana wartość',- 'carried_forward_hint' => 'Dostawca był niedostępny; to ostatnia znana liczba obserwujących.','import_in_progress' => 'Trwa import historii konta. Starsze posty pojawią się w miarę pobierania.','no_data_title' => 'Przygotowujemy historię Twoich statystyk','no_data_body' => 'Połącz obsługiwane konto lub poczekaj na pierwsze pobranie w tle. Starsze posty pojawią się podczas importu.',@@ -112,7 +108,8 @@ return ['30d' => '30 dni','mtd' => 'Bieżący miesiąc','custom' => 'Niestandardowy',- 'compared_to' => ':current · w porównaniu z :previous',+ 'versus' => 'vs :range',+ 'versus_hint' => 'Zmiany porównują ten okres z okresem :range.','label' => 'Zakres dat',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Okres wykresu','both' => 'Oba','comparison' => 'Porównanie',- 'comparison_axis' => ':metric (porównanie)','not_enough_history' => 'Za mało historii. Liczba obserwujących zapisywana jest codziennie, wróć wkrótce.','date' => 'Data','previous_value' => ':metric (poprzedni okres)',@@ -416,4 +412,40 @@ return ['columns' => 'Kolumny','channels_shown' => ':range · Widoczne kanały: :shown z :total. Filtruj po kanale, aby zobaczyć inne.',],+ 'share' => [+ 'channels_shown' => 'Kanały: :shown z :total',+ 'button' => 'Udostępnij jako obraz',+ 'title' => 'Udostępnij jako obraz',+ 'description' => 'Pobierz obraz lub zrób z niego post na swoje kanały.',+ 'color' => 'Kolor',+ 'download' => 'Pobierz',+ 'copy' => 'Kopiuj obraz',+ 'copied' => 'Obraz skopiowany',+ 'create_post' => 'Utwórz post',+ 'mark' => 'Stworzone w TryPost',+ 'copy_failed' => 'Nie udało się skopiować obrazu. Pobierz go.',+ 'post_failed' => 'Nie udało się przygotować posta. Spróbuj ponownie.',+ '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',+ 'export_failed' => 'Nie udało się utworzyć obrazu. Spróbuj ponownie.',+ 'colors' => [+ 'violet' => 'Fioletowy',+ 'blue' => 'Niebieski',+ 'green' => 'Zielony',+ 'peach' => 'Brzoskwiniowy',+ 'yellow' => 'Żółty',+ 'cyan' => 'Cyjan',+ 'teal' => 'Morski',+ 'red' => 'Czerwony',+ 'pink' => 'Różowy',+ 'neutral' => 'Neutralny',+ 'indigo' => 'Indygo',+ 'lime' => 'Limonkowy',+ 'purple' => 'Purpurowy',+ 'fuchsia' => 'Fuksja',+ 'orange' => 'Pomarańczowy',+ 'slate' => 'Łupkowy',+ ],+ ],];diff --git a/lang/pl/posts.php b/lang/pl/posts.phpindex f6d465d75..c7bdf269a 100644--- a/lang/pl/posts.php+++ b/lang/pl/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Publikuj','all_channels' => 'Wszystkie kanały','tabs' => [+ 'label' => 'Status','queue' => 'Kolejka','approvals' => 'Zatwierdzenia','drafts' => 'Wersje robocze',diff --git a/lang/pt-BR/analytics.php b/lang/pt-BR/analytics.phpindex 6641f3679..daeb1ae6c 100644--- a/lang/pt-BR/analytics.php+++ b/lang/pt-BR/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Resumo','posts' => 'Posts','total_followers' => 'Total de seguidores',+ 'total_posts' => 'Total de posts','reactions' => 'Reações','comments' => 'Comentários','engagement_rate' => 'Taxa de engajamento',@@ -63,7 +64,6 @@ return ['performance' => 'Desempenho','top_posts' => 'Top 5 posts','channel' => 'Canal',- 'latest_snapshot_hint' => 'As métricas dos posts usam a última medição salva para posts publicados neste período.','followers_chart_mode' => 'Visualização dos seguidores','posts_chart_mode' => 'Visualização dos posts','chart_line' => 'Linha',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Nenhum dado de seguidores dos canais selecionados neste período. Tente outro intervalo de datas ou limpe o filtro de canais.','filtered_no_data_title' => 'Nada corresponde a estes filtros','filtered_no_data_body' => 'Os canais selecionados ainda não têm dados de analytics. Escolha outros canais ou limpe os filtros.',- 'posts_sent_axis' => 'Posts enviados',- 'followers_gained_detail' => 'Começou com :start · ganhou :change (:percent)',- 'followers_lost_detail' => 'Começou com :start · perdeu :change (:percent)','followers_at_start' => 'No início','followers_gained_in_range' => 'Ganhos no período',+ 'followers_lost_in_range' => 'Perdidos no período','no_excerpt' => 'Prévia de texto indisponível.','published_via' => 'Publicado via','top_posts_sort' => 'Ordenar posts por',- 'carried_forward' => 'Último valor',- 'carried_forward_hint' => 'A rede ficou indisponível; este é o último número conhecido de seguidores.','import_in_progress' => 'Importando o histórico das contas. Posts antigos aparecerão conforme a coleta avançar.','no_data_title' => 'Estamos preparando seu histórico de analytics','no_data_body' => 'Conecte uma conta compatível ou aguarde a primeira coleta em segundo plano. Os posts históricos aparecerão durante a importação.',@@ -112,7 +108,8 @@ return ['30d' => '30 dias','mtd' => 'Mês atual','custom' => 'Personalizado',- 'compared_to' => ':current · comparado com :previous',+ 'versus' => 'vs. :range',+ 'versus_hint' => 'As variações comparam este período com :range.','label' => 'Período',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Período do gráfico','both' => 'Ambos','comparison' => 'Comparação',- 'comparison_axis' => ':metric (comparação)','not_enough_history' => 'Ainda não há histórico suficiente. A contagem de seguidores é registrada dia a dia; volte em breve.','date' => 'Data','previous_value' => ':metric (período anterior)',@@ -416,4 +412,40 @@ return ['columns' => 'Colunas','channels_shown' => ':range · Mostrando :shown de :total canais. Filtre por canal para ver outro conjunto.',],+ 'share' => [+ 'channels_shown' => ':shown de :total canais',+ 'button' => 'Compartilhar como imagem',+ 'title' => 'Compartilhar como imagem',+ 'description' => 'Baixe a imagem ou transforme-a em um post para seus canais.',+ 'color' => 'Cor',+ 'download' => 'Baixar',+ 'copy' => 'Copiar imagem',+ 'copied' => 'Imagem copiada',+ 'create_post' => 'Criar post',+ 'mark' => 'Feito com TryPost',+ 'copy_failed' => 'Não foi possível copiar a imagem. Baixe-a.',+ 'post_failed' => 'Não foi possível preparar o post. Tente de novo.',+ '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',+ 'export_failed' => 'Não foi possível criar a imagem. Tente de novo.',+ 'colors' => [+ 'violet' => 'Violeta',+ 'blue' => 'Azul',+ 'green' => 'Verde',+ 'peach' => 'Pêssego',+ 'yellow' => 'Amarelo',+ 'cyan' => 'Ciano',+ 'teal' => 'Verde-azulado',+ 'red' => 'Vermelho',+ 'pink' => 'Rosa',+ 'neutral' => 'Neutro',+ 'indigo' => 'Índigo',+ 'lime' => 'Lima',+ 'purple' => 'Roxo',+ 'fuchsia' => 'Fúcsia',+ 'orange' => 'Laranja',+ 'slate' => 'Ardósia',+ ],+ ],];diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.phpindex 9c309765a..4c2e791a8 100644--- a/lang/pt-BR/posts.php+++ b/lang/pt-BR/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Publicar','all_channels' => 'Todos os canais','tabs' => [+ 'label' => 'Status','queue' => 'Fila','approvals' => 'Aprovações','drafts' => 'Rascunhos',diff --git a/lang/ru/analytics.php b/lang/ru/analytics.phpindex 004dc373a..f54b501fd 100644--- a/lang/ru/analytics.php+++ b/lang/ru/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Сводка','posts' => 'Публикации','total_followers' => 'Всего подписчиков',+ 'total_posts' => 'Всего публикаций','reactions' => 'Реакции','comments' => 'Комментарии','engagement_rate' => 'Уровень вовлечённости',@@ -63,7 +64,6 @@ return ['performance' => 'Результаты','top_posts' => '5 лучших публикаций','channel' => 'Канал',- 'latest_snapshot_hint' => 'Для публикаций за этот период используются последние сохранённые показатели.','followers_chart_mode' => 'Режим графика подписчиков','posts_chart_mode' => 'Режим графика публикаций','chart_line' => 'Линия',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Нет данных о подписчиках выбранных каналов за этот период. Выберите другой диапазон дат или сбросьте фильтр каналов.','filtered_no_data_title' => 'Ничего не найдено по этим фильтрам','filtered_no_data_body' => 'У выбранных каналов пока нет данных аналитики. Выберите другие каналы или сбросьте фильтры.',- 'posts_sent_axis' => 'Отправлено публикаций',- 'followers_gained_detail' => 'Начало: :start · прирост :change (:percent)',- 'followers_lost_detail' => 'Начало: :start · потеря :change (:percent)','followers_at_start' => 'На старте','followers_gained_in_range' => 'Прирост',+ 'followers_lost_in_range' => 'Убыль','no_excerpt' => 'Текстовое превью недоступно.','published_via' => 'Опубликовано через','top_posts_sort' => 'Сортировать публикации по',- 'carried_forward' => 'Последнее известное значение',- 'carried_forward_hint' => 'Сервис был недоступен; показано последнее известное число подписчиков.','import_in_progress' => 'Импортируем историю аккаунта. Более старые публикации появятся по мере сбора данных.','no_data_title' => 'Подготавливаем историю аналитики','no_data_body' => 'Подключите поддерживаемый аккаунт или дождитесь первого фонового сбора данных. Исторические публикации появятся во время импорта.',@@ -112,7 +108,8 @@ return ['30d' => '30 дней','mtd' => 'Текущий месяц','custom' => 'Свой период',- 'compared_to' => ':current · по сравнению с :previous',+ 'versus' => 'vs :range',+ 'versus_hint' => 'Изменения сравнивают этот период с периодом :range.','label' => 'Период',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Период графика','both' => 'Оба','comparison' => 'Сравнение',- 'comparison_axis' => ':metric (сравнение)','not_enough_history' => 'Пока мало истории. Подписчики учитываются каждый день — загляните позже.','date' => 'Дата','previous_value' => ':metric (прошлый период)',@@ -416,4 +412,40 @@ return ['columns' => 'Столбцы','channels_shown' => ':range · Показано каналов: :shown из :total. Отфильтруйте по каналу, чтобы увидеть другие.',],+ 'share' => [+ 'channels_shown' => 'Каналов: :shown из :total',+ 'button' => 'Поделиться картинкой',+ 'title' => 'Поделиться картинкой',+ 'description' => 'Скачайте изображение или превратите его в пост для своих каналов.',+ 'color' => 'Цвет',+ 'download' => 'Скачать',+ 'copy' => 'Копировать',+ 'copied' => 'Изображение скопировано',+ 'create_post' => 'Создать пост',+ 'mark' => 'Сделано в TryPost',+ 'copy_failed' => 'Не удалось скопировать изображение. Скачайте его.',+ 'post_failed' => 'Не удалось подготовить пост. Попробуйте ещё раз.',+ 'caption_workspace' => ':metric в наших каналах: :value (:range) 📈',+ 'caption_summary_workspace' => 'Наши цифры за :range 📈 :metrics',+ 'caption_summary_channel' => 'Наши цифры в :channel за :range 📈 :metrics',+ 'export_failed' => 'Не удалось создать изображение. Попробуйте ещё раз.',+ 'colors' => [+ 'violet' => 'Фиолетовый',+ 'blue' => 'Синий',+ 'green' => 'Зелёный',+ 'peach' => 'Персиковый',+ 'yellow' => 'Жёлтый',+ 'cyan' => 'Голубой',+ 'teal' => 'Бирюзовый',+ 'red' => 'Красный',+ 'pink' => 'Розовый',+ 'neutral' => 'Нейтральный',+ 'indigo' => 'Индиго',+ 'lime' => 'Лаймовый',+ 'purple' => 'Пурпурный',+ 'fuchsia' => 'Фуксия',+ 'orange' => 'Оранжевый',+ 'slate' => 'Сланцевый',+ ],+ ],];diff --git a/lang/ru/posts.php b/lang/ru/posts.phpindex 881163038..3382abe01 100644--- a/lang/ru/posts.php+++ b/lang/ru/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Публикация','all_channels' => 'Все каналы','tabs' => [+ 'label' => 'Статус','queue' => 'Очередь','approvals' => 'Одобрение','drafts' => 'Черновики',diff --git a/lang/tr/analytics.php b/lang/tr/analytics.phpindex 9c575ce3d..3e9f6d84b 100644--- a/lang/tr/analytics.php+++ b/lang/tr/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Özet','posts' => 'Gönderiler','total_followers' => 'Toplam takipçi',+ 'total_posts' => 'Toplam gönderi','reactions' => 'Tepkiler','comments' => 'Yorumlar','engagement_rate' => 'Etkileşim oranı',@@ -63,7 +64,6 @@ return ['performance' => 'Performans','top_posts' => 'En iyi 5 gönderi','channel' => 'Kanal',- 'latest_snapshot_hint' => 'Bu dönemde yayınlanan gönderiler için son kaydedilen ölçümler kullanılır.','followers_chart_mode' => 'Takipçi grafiği modu','posts_chart_mode' => 'Gönderi grafiği modu','chart_line' => 'Çizgi',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Bu dönemde seçili kanallar için takipçi verisi yok. Başka bir tarih aralığı deneyin veya kanal filtresini temizleyin.','filtered_no_data_title' => 'Bu filtrelerle eşleşen bir şey yok','filtered_no_data_body' => 'Seçili kanalların henüz analiz verisi yok. Başka kanallar seçin veya filtreleri temizleyin.',- 'posts_sent_axis' => 'Gönderilen gönderiler',- 'followers_gained_detail' => 'Başlangıç :start · :change kazanıldı (:percent)',- 'followers_lost_detail' => 'Başlangıç :start · :change kaybedildi (:percent)','followers_at_start' => 'Başlangıçta','followers_gained_in_range' => 'Kazanılan',+ 'followers_lost_in_range' => 'Kaybedilen','no_excerpt' => 'Metin önizlemesi mevcut değil.','published_via' => 'Yayın kaynağı:','top_posts_sort' => 'Gönderileri şuna göre sırala',- 'carried_forward' => 'Bilinen son değer',- 'carried_forward_hint' => 'Sağlayıcı kullanılamıyordu; bu, bilinen son takipçi sayısıdır.','import_in_progress' => 'Hesap geçmişi içe aktarılıyor. Veri toplama ilerledikçe eski gönderiler görünecek.','no_data_title' => 'Analiz geçmişiniz hazırlanıyor','no_data_body' => 'Desteklenen bir hesap bağlayın veya arka plandaki ilk veri toplamayı bekleyin. Geçmiş gönderiler içe aktarma sırasında görünecek.',@@ -112,7 +108,8 @@ return ['30d' => '30 gün','mtd' => 'Bu ay','custom' => 'Özel',- 'compared_to' => ':current · :previous ile karşılaştırıldı',+ 'versus' => 'vs :range',+ 'versus_hint' => 'Değişimler bu dönemi :range dönemiyle karşılaştırır.','label' => 'Tarih aralığı',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Grafik dönemi','both' => 'İkisi','comparison' => 'Karşılaştırma',- 'comparison_axis' => ':metric (karşılaştırma)','not_enough_history' => 'Henüz yeterli geçmiş yok. Takipçiler her gün kaydedilir, yakında tekrar bakın.','date' => 'Tarih','previous_value' => ':metric (önceki dönem)',@@ -416,4 +412,40 @@ return ['columns' => 'Sütunlar','channels_shown' => ':range · :total kanaldan :shown tanesi gösteriliyor. Başka kanalları görmek için kanala göre filtreleyin.',],+ 'share' => [+ 'channels_shown' => ':total kanaldan :shown',+ 'button' => 'Görsel olarak paylaş',+ 'title' => 'Görsel olarak paylaş',+ 'description' => 'Görseli indir ya da kanalların için bir gönderiye dönüştür.',+ 'color' => 'Renk',+ 'download' => 'İndir',+ 'copy' => 'Görseli kopyala',+ 'copied' => 'Görsel kopyalandı',+ 'create_post' => 'Gönderi oluştur',+ 'mark' => 'TryPost ile yapıldı',+ 'copy_failed' => 'Görsel kopyalanamadı. Bunun yerine indir.',+ 'post_failed' => 'Gönderi hazırlanamadı. Tekrar dene.',+ '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',+ 'export_failed' => 'Görsel oluşturulamadı. Tekrar dene.',+ 'colors' => [+ 'violet' => 'Menekşe',+ 'blue' => 'Mavi',+ 'green' => 'Yeşil',+ 'peach' => 'Şeftali',+ 'yellow' => 'Sarı',+ 'cyan' => 'Camgöbeği',+ 'teal' => 'Deniz mavisi',+ 'red' => 'Kırmızı',+ 'pink' => 'Pembe',+ 'neutral' => 'Nötr',+ 'indigo' => 'Çivit',+ 'lime' => 'Limon yeşili',+ 'purple' => 'Mor',+ 'fuchsia' => 'Fuşya',+ 'orange' => 'Turuncu',+ 'slate' => 'Arduvaz',+ ],+ ],];diff --git a/lang/tr/posts.php b/lang/tr/posts.phpindex ec4f183f3..852691262 100644--- a/lang/tr/posts.php+++ b/lang/tr/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Yayınla','all_channels' => 'Tüm kanallar','tabs' => [+ 'label' => 'Durum','queue' => 'Kuyruk','approvals' => 'Onaylar','drafts' => 'Taslaklar',diff --git a/lang/uk/analytics.php b/lang/uk/analytics.phpindex 69d7c1850..3fe554be8 100644--- a/lang/uk/analytics.php+++ b/lang/uk/analytics.php@@ -56,6 +56,7 @@ return ['summary' => 'Підсумок','posts' => 'Дописи','total_followers' => 'Усього підписників',+ 'total_posts' => 'Усього дописів','reactions' => 'Реакції','comments' => 'Коментарі','engagement_rate' => 'Рівень залученості',@@ -63,7 +64,6 @@ return ['performance' => 'Результати','top_posts' => '5 найкращих дописів','channel' => 'Канал',- 'latest_snapshot_hint' => 'Для дописів за цей період використовуються останні збережені показники.','followers_chart_mode' => 'Режим графіка підписників','posts_chart_mode' => 'Режим графіка дописів','chart_line' => 'Лінія',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => 'Немає даних про підписників вибраних каналів за цей період. Виберіть інший діапазон дат або скиньте фільтр каналів.','filtered_no_data_title' => 'Нічого не відповідає цим фільтрам','filtered_no_data_body' => 'Вибрані канали ще не мають даних аналітики. Виберіть інші канали або скиньте фільтри.',- 'posts_sent_axis' => 'Надіслано дописів',- 'followers_gained_detail' => 'Початок: :start · приріст :change (:percent)',- 'followers_lost_detail' => 'Початок: :start · втрата :change (:percent)','followers_at_start' => 'На старті','followers_gained_in_range' => 'Приріст',+ 'followers_lost_in_range' => 'Убуток','no_excerpt' => 'Попередній перегляд тексту недоступний.','published_via' => 'Опубліковано через','top_posts_sort' => 'Сортувати дописи за',- 'carried_forward' => 'Останнє відоме значення',- 'carried_forward_hint' => 'Сервіс був недоступний; показано останню відому кількість підписників.','import_in_progress' => 'Імпортуємо історію облікового запису. Старіші дописи з’являться в міру збирання даних.','no_data_title' => 'Готуємо історію аналітики','no_data_body' => 'Підключіть підтримуваний обліковий запис або дочекайтеся першого фонового збирання даних. Історичні дописи з’являться під час імпорту.',@@ -112,7 +108,8 @@ return ['30d' => '30 днів','mtd' => 'Поточний місяць','custom' => 'Власний період',- 'compared_to' => ':current · порівняно з :previous',+ 'versus' => 'vs :range',+ 'versus_hint' => 'Зміни порівнюють цей період із періодом :range.','label' => 'Період',],@@ -156,7 +153,6 @@ return ['chart_mode' => 'Період графіка','both' => 'Обидва','comparison' => 'Порівняння',- 'comparison_axis' => ':metric (порівняння)','not_enough_history' => 'Поки замало історії. Підписників враховують щодня — зазирніть пізніше.','date' => 'Дата','previous_value' => ':metric (попередній період)',@@ -416,4 +412,40 @@ return ['columns' => 'Стовпці','channels_shown' => ':range · Показано каналів: :shown з :total. Фільтруйте за каналом, щоб побачити інші.',],+ 'share' => [+ 'channels_shown' => 'Каналів: :shown з :total',+ 'button' => 'Поділитися зображенням',+ 'title' => 'Поділитися зображенням',+ 'description' => 'Завантажте зображення або перетворіть його на пост для своїх каналів.',+ 'color' => 'Колір',+ 'download' => 'Завантажити',+ 'copy' => 'Копіювати',+ 'copied' => 'Зображення скопійовано',+ 'create_post' => 'Створити пост',+ 'mark' => 'Зроблено в TryPost',+ 'copy_failed' => 'Не вдалося скопіювати зображення. Завантажте його.',+ 'post_failed' => 'Не вдалося підготувати пост. Спробуйте ще раз.',+ 'caption_workspace' => ':metric у наших каналах: :value (:range) 📈',+ 'caption_summary_workspace' => 'Наші цифри за :range 📈 :metrics',+ 'caption_summary_channel' => 'Наші цифри в :channel за :range 📈 :metrics',+ 'export_failed' => 'Не вдалося створити зображення. Спробуйте ще раз.',+ 'colors' => [+ 'violet' => 'Фіолетовий',+ 'blue' => 'Синій',+ 'green' => 'Зелений',+ 'peach' => 'Персиковий',+ 'yellow' => 'Жовтий',+ 'cyan' => 'Блакитний',+ 'teal' => 'Бірюзовий',+ 'red' => 'Червоний',+ 'pink' => 'Рожевий',+ 'neutral' => 'Нейтральний',+ 'indigo' => 'Індиго',+ 'lime' => 'Лаймовий',+ 'purple' => 'Пурпуровий',+ 'fuchsia' => 'Фуксія',+ 'orange' => 'Помаранчевий',+ 'slate' => 'Сланцевий',+ ],+ ],];diff --git a/lang/uk/posts.php b/lang/uk/posts.phpindex fc7d746c8..86ebcc6f3 100644--- a/lang/uk/posts.php+++ b/lang/uk/posts.php@@ -924,6 +924,7 @@ return ['title' => 'Публікація','all_channels' => 'Усі канали','tabs' => [+ 'label' => 'Статус','queue' => 'Черга','approvals' => 'Схвалення','drafts' => 'Чернетки',diff --git a/lang/zh/analytics.php b/lang/zh/analytics.phpindex cccbcf1f3..33b308b60 100644--- a/lang/zh/analytics.php+++ b/lang/zh/analytics.php@@ -56,6 +56,7 @@ return ['summary' => '概览','posts' => '帖子','total_followers' => '粉丝总数',+ 'total_posts' => '帖子总数','reactions' => '回应','comments' => '评论','engagement_rate' => '互动率',@@ -63,7 +64,6 @@ return ['performance' => '表现','top_posts' => '前5条帖子','channel' => '频道',- 'latest_snapshot_hint' => '此时间段内的帖子指标使用最近一次保存的测量值。','followers_chart_mode' => '粉丝图表模式','posts_chart_mode' => '帖子图表模式','chart_line' => '折线',@@ -79,16 +79,12 @@ return ['filtered_no_followers' => '此期间所选频道没有粉丝数据。请尝试其他日期范围或清除频道筛选。','filtered_no_data_title' => '没有符合这些筛选条件的内容','filtered_no_data_body' => '所选频道还没有分析数据。请选择其他频道或清除筛选条件。',- 'posts_sent_axis' => '已发送帖子',- 'followers_gained_detail' => '起始 :start · 增加 :change(:percent)',- 'followers_lost_detail' => '起始 :start · 减少 :change(:percent)','followers_at_start' => '期初','followers_gained_in_range' => '期内新增',+ 'followers_lost_in_range' => '期内减少','no_excerpt' => '没有可用的文字预览。','published_via' => '发布来源:','top_posts_sort' => '帖子排序依据',- 'carried_forward' => '最近已知值',- 'carried_forward_hint' => '服务暂时不可用;这里显示最近已知的粉丝数。','import_in_progress' => '正在导入账号历史记录。采集过程中会逐步显示更早的帖子。','no_data_title' => '正在准备你的分析历史数据','no_data_body' => '连接受支持的账号,或等待首次后台采集。导入过程中会显示历史帖子。',@@ -112,7 +108,8 @@ return ['30d' => '30 天','mtd' => '本月至今','custom' => '自定义',- 'compared_to' => ':current · 对比 :previous',+ 'versus' => '对比 :range',+ 'versus_hint' => '变化是将此期间与 :range 进行比较。','label' => '日期范围',],@@ -156,7 +153,6 @@ return ['chart_mode' => '图表时段','both' => '两者','comparison' => '对比',- 'comparison_axis' => ':metric(对比)','not_enough_history' => '历史数据还不够。粉丝数每天记录一次,请稍后再来查看。','date' => '日期','previous_value' => ':metric(上一时段)',@@ -416,4 +412,40 @@ return ['columns' => '列','channels_shown' => ':range · 显示 :total 个频道中的 :shown 个。按频道筛选以查看其他频道。',],+ 'share' => [+ 'channels_shown' => ':total 个频道中的 :shown 个',+ 'button' => '分享为图片',+ 'title' => '分享为图片',+ 'description' => '下载图片,或把它做成发到你各个频道的帖子。',+ 'color' => '颜色',+ 'download' => '下载',+ 'copy' => '复制图片',+ 'copied' => '图片已复制',+ 'create_post' => '创建帖子',+ 'mark' => '由 TryPost 制作',+ 'copy_failed' => '无法复制图片,请改为下载。',+ 'post_failed' => '无法准备帖子,请重试。',+ 'caption_workspace' => '我们所有频道的:metric::value(:range)📈',+ 'caption_summary_workspace' => '我们 :range 的数据 📈 :metrics',+ 'caption_summary_channel' => '我们在 :channel 上 :range 的数据 📈 :metrics',+ 'export_failed' => '无法生成图片,请重试。',+ 'colors' => [+ 'violet' => '紫罗兰色',+ 'blue' => '蓝色',+ 'green' => '绿色',+ 'peach' => '桃色',+ 'yellow' => '黄色',+ 'cyan' => '青色',+ 'teal' => '蓝绿色',+ 'red' => '红色',+ 'pink' => '粉色',+ 'neutral' => '中性色',+ 'indigo' => '靛蓝色',+ 'lime' => '青柠色',+ 'purple' => '紫色',+ 'fuchsia' => '品红色',+ 'orange' => '橙色',+ 'slate' => '石板色',+ ],+ ],];diff --git a/lang/zh/posts.php b/lang/zh/posts.phpindex 8540b5e1a..7b27afc9a 100644--- a/lang/zh/posts.php+++ b/lang/zh/posts.php@@ -924,6 +924,7 @@ return ['title' => '发布','all_channels' => '所有频道','tabs' => [+ 'label' => '状态','queue' => '队列','approvals' => '审批','drafts' => '草稿',diff --git a/package-lock.json b/package-lock.jsonindex 2c8a40dd2..86030c153 100644--- a/package-lock.json+++ b/package-lock.json@@ -8,9 +8,9 @@"@atlaskit/pragmatic-drag-and-drop": "^4.0.0","@atlaskit/pragmatic-drag-and-drop-hitbox": "^3.0.0","@inertiajs/vue3": "^3.8.0",- "@tabler/icons-vue": "^3.49.0",+ "@tabler/icons-vue": "^3.50.0","@tailwindcss/typography": "^0.5.19",- "@thesvg/vue": "^3.4.0",+ "@thesvg/vue": "^4.0.0","@unovis/ts": "^1.7.0","@unovis/vue": "^1.7.0","@vueuse/core": "^12.8.2",@@ -1557,9 +1557,9 @@}},"node_modules/@tabler/icons": {- "version": "3.49.0",- "resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.49.0.tgz",- "integrity": "sha512-l+GnSkFETx0U26icxv1VUFnxxiTqXfCcVRiRAnyMwibupM2S2L/hSaZ9gmSgz01rkrsH/93NvLsxykqdanc6lw==",+ "version": "3.50.0",+ "resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.50.0.tgz",+ "integrity": "sha512-HflLxyrH1cqC7s7jzQGSjpsTAVIoaf7+/yHjbdM59rJQBMjliibp+LYhDPFxOMcwa1M8DNpOk6ENzQiWn9a1Dg==","license": "MIT","funding": {"type": "github",@@ -1567,12 +1567,12 @@}},"node_modules/@tabler/icons-vue": {- "version": "3.49.0",- "resolved": "https://registry.npmjs.org/@tabler/icons-vue/-/icons-vue-3.49.0.tgz",- "integrity": "sha512-p/g2/aVsUTdGaLwgV+X/E3vc+j8XkXWV2NgXAVT31/6sMf/CFAI3uvJ1r6YCi/UT8U2ctaF5fXUWr18bNVVr7g==",+ "version": "3.50.0",+ "resolved": "https://registry.npmjs.org/@tabler/icons-vue/-/icons-vue-3.50.0.tgz",+ "integrity": "sha512-4ELHNkbNXMyeUEx43FUk+AoRCEz9zqVoxlOwngr1Vx374ySBUCBBCfTuQGYQGctMFhKAVZVlK2yZOnzmJ5Qr5g==","license": "MIT","dependencies": {- "@tabler/icons": "3.49.0"+ "@tabler/icons": "3.50.0"},"funding": {"type": "github",@@ -1904,9 +1904,9 @@}},"node_modules/@thesvg/vue": {- "version": "3.4.0",- "resolved": "https://registry.npmjs.org/@thesvg/vue/-/vue-3.4.0.tgz",- "integrity": "sha512-qKf/O0XQp4KIGYaf7rTRf1rYhdV1gN5mafnuVbMGS3P698K+v6o9/t2JKqM3jMcH1WF9mmCaEiBQ7rZWbsDZHw==",+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@thesvg/vue/-/vue-4.0.0.tgz",+ "integrity": "sha512-ZIZtzrK9BVSPW8FU9LB1zbsLn69WNkaC3vUBseBf8ePxLRIFMD3/21n73d7QS81491BBMbd7VtstPG+xlWzODw==","license": "MIT","engines": {"node": ">=18"diff --git a/package.json b/package.jsonindex 9835b6b7c..fc896aa56 100644--- a/package.json+++ b/package.json@@ -40,9 +40,9 @@"@atlaskit/pragmatic-drag-and-drop": "^4.0.0","@atlaskit/pragmatic-drag-and-drop-hitbox": "^3.0.0","@inertiajs/vue3": "^3.8.0",- "@tabler/icons-vue": "^3.49.0",+ "@tabler/icons-vue": "^3.50.0","@tailwindcss/typography": "^0.5.19",- "@thesvg/vue": "^3.4.0",+ "@thesvg/vue": "^4.0.0","@unovis/ts": "^1.7.0","@unovis/vue": "^1.7.0","@vueuse/core": "^12.8.2",diff --git a/public/images/ai/claude-color.svg b/public/images/ai/claude-color.svgdeleted file mode 100644index 1df84178f..000000000--- a/public/images/ai/claude-color.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Claude</title><path fill="#D97757" fill-rule="evenodd" d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"/></svg>diff --git a/public/images/ai/claude-mono.svg b/public/images/ai/claude-mono.svgdeleted file mode 100644index 4722aff5c..000000000--- a/public/images/ai/claude-mono.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Claude</title><path fill="#000" fill-rule="evenodd" d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"/></svg>diff --git a/public/images/ai/mcp.svg b/public/images/ai/mcp.svgdeleted file mode 100644index fd49dba8b..000000000--- a/public/images/ai/mcp.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#000" fill-rule="evenodd"><title>ModelContextProtocol</title><path d="M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"></path><path d="M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"></path></svg>diff --git a/public/images/ai/openai.svg b/public/images/ai/openai.svgdeleted file mode 100644index cd0d8ce56..000000000--- a/public/images/ai/openai.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>OpenAI</title><path fill="#000" fill-rule="evenodd" d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"/></svg>diff --git a/public/images/social/github.svg b/public/images/social/github.svgdeleted file mode 100644index 77e010662..000000000--- a/public/images/social/github.svg+++ /dev/null@@ -1,10 +0,0 @@-<svg- xmlns="http://www.w3.org/2000/svg"- width="24"- height="24"- viewBox="0 0 24 24"->- <path- d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"- />-</svg>diff --git a/public/images/social/google.svg b/public/images/social/google.svgdeleted file mode 100644index 710f7ae42..000000000--- a/public/images/social/google.svg+++ /dev/null@@ -1,22 +0,0 @@-<svg- viewBox="0 0 25 25"- fill="none"- xmlns="http://www.w3.org/2000/svg"->- <path- d="M5.54053 15.1078L4.67031 18.3565L1.4897 18.4237C0.53916 16.6607 0 14.6436 0 12.5C0 10.4272 0.504102 8.47252 1.39766 6.75137H1.39834L4.22998 7.27051L5.47041 10.0852C5.21079 10.842 5.06929 11.6545 5.06929 12.5C5.06938 13.4176 5.2356 14.2967 5.54053 15.1078Z"- fill="#FBBB00"- ></path>- <path- d="M24.7816 10.1648C24.9251 10.921 25 11.7019 25 12.5C25 13.3949 24.9059 14.2679 24.7266 15.1099C24.1181 17.9753 22.5282 20.4773 20.3256 22.2479L20.3249 22.2473L16.7583 22.0653L16.2535 18.9142C17.715 18.057 18.8572 16.7157 19.4589 15.1099H12.7748V10.1648H19.5564H24.7816Z"- fill="#518EF8"- ></path>- <path- d="M20.3249 22.2473L20.3256 22.248C18.1834 23.9698 15.4622 25 12.5 25C7.73972 25 3.601 22.3393 1.48972 18.4238L5.54055 15.1079C6.59616 17.9251 9.31389 19.9307 12.5 19.9307C13.8695 19.9307 15.1525 19.5605 16.2534 18.9142L20.3249 22.2473Z"- fill="#28B446"- ></path>- <path- d="M20.4787 2.87773L16.4293 6.19297C15.2899 5.48076 13.943 5.06934 12.5 5.06934C9.24177 5.06934 6.47321 7.16685 5.47048 10.0852L1.39836 6.75137H1.39767C3.47805 2.74038 7.66896 0 12.5 0C15.533 0 18.3139 1.08037 20.4787 2.87773Z"- fill="#F14336"- ></path>-</svg>diff --git a/resources/css/app.css b/resources/css/app.cssindex e60e2125e..e8e887cb1 100644--- a/resources/css/app.css+++ b/resources/css/app.css@@ -8,7 +8,8 @@@custom-variant dark (&:is(.dark *));-:root {+:root,+[data-light-theme] {--background: #ffffff;--foreground: #292928;--card: #ffffff;diff --git a/resources/js/app.ts b/resources/js/app.tsindex 8111e9625..d030941d3 100644--- a/resources/js/app.ts+++ b/resources/js/app.ts@@ -1,5 +1,4 @@-import '../css/app.css';-import './echo';+import '@/echo';import { createInertiaApp, router } from '@inertiajs/vue3';import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';@@ -8,13 +7,13 @@ import { ConfigProvider } from 'reka-ui';import type { DefineComponent } from 'vue';import { createApp, h } from 'vue';-import { initializeDataLayer } from './datalayer';-import { bootLocale, i18nConfig, syncLocale, textDirection } from './language';-import { syncContentTypeMediaRules } from './lib/contentTypeMediaRules';-import { trackInAppPushes } from './lib/inAppHistory';-import { capturePageview, initializePostHog, syncPostHogContext } from './posthog';-import { syncPreferences } from './preferences';-import type { Auth } from './types';+import { initializeDataLayer } from '@/datalayer';+import { bootLocale, i18nConfig, syncLocale, textDirection } from '@/language';+import { syncContentTypeMediaRules } from '@/lib/contentTypeMediaRules';+import { trackInAppPushes } from '@/lib/inAppHistory';+import { capturePageview, initializePostHog, syncPostHogContext } from '@/posthog';+import { syncPreferences } from '@/preferences';+import type { Auth } from '@/types';const appName = import.meta.env.VITE_APP_NAME || 'TryPost.it';diff --git a/resources/js/components/AppHeader.vue b/resources/js/components/AppHeader.vueindex ac4e082a2..6305f17cf 100644--- a/resources/js/components/AppHeader.vue+++ b/resources/js/components/AppHeader.vue@@ -1,6 +1,7 @@<template><headerclass="flex shrink-0 items-center justify-between gap-2 bg-card px-4 pt-4 md:px-8 md:pt-6"+ data-testid="app-header"><div class="flex h-12 min-w-0 flex-1 items-center gap-2"><slot name="left" />diff --git a/resources/js/components/BottomSheet.vue b/resources/js/components/BottomSheet.vueindex d6b78150f..c5ceb8462 100644--- a/resources/js/components/BottomSheet.vue+++ b/resources/js/components/BottomSheet.vue@@ -14,9 +14,11 @@ withDefaults(title: string;testId: string;showHeader?: boolean;+ /** The drag handle at the top, for a sheet that has no header. */+ handle?: boolean;contentClass?: string;}>(),- { showHeader: true, contentClass: '' },+ { showHeader: true, handle: false, contentClass: '' },);const open = defineModel<boolean>('open', { required: true });@@ -51,6 +53,11 @@ const open = defineModel<boolean>('open', { required: true });</SheetClose></div><SheetTitle v-else class="sr-only">{{ title }}</SheetTitle>+ <div+ v-if="handle"+ class="mx-auto mt-3 mb-2 h-1 w-10 shrink-0 rounded-full bg-border-strong"+ aria-hidden="true"+ /><slot /></SheetContent></Sheet>diff --git a/resources/js/components/ResponsivePopover.vue b/resources/js/components/ResponsivePopover.vueindex a6db12f2c..01fca4acc 100644--- a/resources/js/components/ResponsivePopover.vue+++ b/resources/js/components/ResponsivePopover.vue@@ -24,11 +24,15 @@ const open = defineModel<boolean>('open', { default: false });const [DefineContent, ReuseContent] = createReusableTemplate();const asSheet = useBelowBreakpoint('sm');++const close = (): void => {+ open.value = false;+};</script><template><DefineContent>- <slot :sheet="asSheet" />+ <slot :sheet="asSheet" :close="close" /></DefineContent><Popover v-model:open="open">@@ -50,13 +54,10 @@ const asSheet = useBelowBreakpoint('sm');v-model:open="open":title="title":show-header="false"+ handle:test-id="testId":content-class="sheetClass">- <div- class="mx-auto mt-3 mb-2 h-1 w-10 shrink-0 rounded-full bg-border-strong"- aria-hidden="true"- /><ReuseContent /></BottomSheet></template>diff --git a/resources/js/components/analytics/AnalyticsRangePresets.vue b/resources/js/components/analytics/AnalyticsRangePresets.vueindex 4e363ab1d..c16054ddd 100644--- a/resources/js/components/analytics/AnalyticsRangePresets.vue+++ b/resources/js/components/analytics/AnalyticsRangePresets.vue@@ -1,26 +1,28 @@<script setup lang="ts">import { router } from '@inertiajs/vue3';import { IconCheck, IconChevronDown } from '@tabler/icons-vue';-import { ref, watch } from 'vue';+import { nextTick, ref, watch } from 'vue';import { DateRangePicker } from '@/components/ui/date-range-picker';import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuSeparator,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';import dayjs from '@/dayjs';import type {AnalyticsFilters,AnalyticsRangePreset,+ DateRange,} from '@/types/analytics';const props = defineProps<{filters: AnalyticsFilters;bounds: { min: string | null; max: string | null };url: string;- range: { start: string; end: string };+ range: DateRange;keep?: Record<string, string | string[]>;}>();@@ -39,6 +41,7 @@ const toDates = (start: string, end: string): { start: Date; end: Date } => ({});const mobileTriggerLabelKey = (): string => `analytics.ranges.${props.filters.range}`;const selectedRange = ref(toDates(props.range.start, props.range.end));+const customOpen = ref(false);watch(() => [props.range.start, props.range.end],@@ -51,6 +54,12 @@ const choose = (preset: AnalyticsRangePreset): void => {router.get(props.url, { ...props.keep, range: preset });};+/** On a phone, Custom is the menu's last option and opens the calendar sheet once the menu has closed. */+const openCustom = async (): Promise<void> => {+ await nextTick();+ customOpen.value = true;+};+const changeRange = (range: { start: Date; end: Date }): void => {selectedRange.value = range;const start = dayjs(range.start).format('YYYY-MM-DD');@@ -102,28 +111,30 @@ const changeRange = (range: { start: Date; end: Date }): void => {class="ms-auto size-4 text-primary-text"/></DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ data-testid="insights-range-mobile-custom"+ :aria-checked="filters.range === 'custom'"+ :disabled="!bounds.min"+ @select="openCustom"+ >+ {{ $t('analytics.ranges.custom') }}+ <IconCheck+ v-if="filters.range === 'custom'"+ class="ms-auto size-4 text-primary-text"+ />+ </DropdownMenuItem></DropdownMenuContent></DropdownMenu><DateRangePicker+ v-model:open="customOpen":model-value="selectedRange":min-date="bounds.min ? dayjs(bounds.min).toDate() : undefined":max-date="bounds.max ? dayjs(bounds.max).toDate() : undefined"sheet-below-sm+ without-trigger@update:model-value="changeRange"- >- <template #trigger>- <button- type="button"- data-testid="insights-range-mobile-custom"- class="inline-flex h-8 shrink-0 items-center rounded-lg border border-border-strong px-3 text-sm font-medium whitespace-nowrap transition-control disabled:cursor-not-allowed disabled:text-subtle-foreground disabled:hover:bg-transparent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"- :class="buttonClass('custom')"- :aria-pressed="filters.range === 'custom'"- :disabled="!bounds.min"- >- {{ $t('analytics.ranges.custom') }}- </button>- </template>- </DateRangePicker>+ /></div><divclass="hidden max-w-full flex-wrap items-center gap-1 rounded-lg border border-border-strong p-1 sm:inline-flex sm:flex-nowrap"diff --git a/resources/js/components/analytics/ComparedRange.vue b/resources/js/components/analytics/ComparedRange.vuenew file mode 100644index 000000000..a63814ee1--- /dev/null+++ b/resources/js/components/analytics/ComparedRange.vue@@ -0,0 +1,50 @@+<script setup lang="ts">+import { computed } from 'vue';++import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from '@/components/ui/tooltip';+import date from '@/date';+import type { DateRange } from '@/types/analytics';++const props = defineProps<{+ range: DateRange;+ /** The period the changes are measured against. */+ previous: DateRange;+}>();++const previousLabel = computed(() =>+ date.formatComparedRange(props.previous, props.range),+);+</script>++<template>+ <span class="inline-flex flex-wrap items-center gap-x-2 gap-y-1">+ <span data-testid="analytics-range-current">{{+ date.formatDayMonthYearRange(range)+ }}</span>+ <TooltipProvider :delay-duration="200">+ <Tooltip>+ <TooltipTrigger as-child>+ <span+ tabindex="0"+ class="inline-flex items-center rounded-md bg-muted px-1.5 py-0.5 text-[11px] leading-4 font-medium whitespace-nowrap text-muted-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"+ data-testid="analytics-range-previous"+ >+ {{ $t('analytics.ranges.versus', { range: previousLabel }) }}+ </span>+ </TooltipTrigger>+ <TooltipContent class="max-w-64">+ {{+ $t('analytics.ranges.versus_hint', {+ range: date.formatDayMonthYearRange(previous),+ })+ }}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </span>+</template>diff --git a/resources/js/components/analytics/InsightsExportMenu.vue b/resources/js/components/analytics/InsightsExportMenu.vueindex 0f50b50fa..317773617 100644--- a/resources/js/components/analytics/InsightsExportMenu.vue+++ b/resources/js/components/analytics/InsightsExportMenu.vue@@ -51,13 +51,15 @@ const formats = computed(() => [<DropdownMenuTrigger as-child><Buttonvariant="outline"- class="data-[state=open]:bg-accent"+ class="data-[state=open]:bg-accent max-sm:size-8 max-sm:px-0"data-testid="insights-export"><IconDownload aria-hidden="true" />- {{ $t('analytics.insights.export.button') }}+ <span class="max-sm:sr-only">{{+ $t('analytics.insights.export.button')+ }}</span><IconChevronDown- class="text-muted-foreground"+ class="text-muted-foreground max-sm:hidden"aria-hidden="true"/></Button>diff --git a/resources/js/components/analytics/InsightsSyncStatus.vue b/resources/js/components/analytics/InsightsSyncStatus.vueindex ee43f632f..6ace9a28a 100644--- a/resources/js/components/analytics/InsightsSyncStatus.vue+++ b/resources/js/components/analytics/InsightsSyncStatus.vue@@ -39,7 +39,7 @@ const lastSyncedAt = computed<string | null>(() =><PopoverTrigger as-child><buttontype="button"- class="inline-flex size-8 cursor-pointer items-center justify-center rounded-full bg-primary-subtle text-primary-strong transition-control hover:brightness-95 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[state=open]:brightness-95"+ class="inline-flex size-8 cursor-pointer items-center justify-center rounded-full bg-primary-subtle text-primary-strong transition-control hover:brightness-95 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[state=open]:brightness-95 max-sm:hidden":aria-label="$t('analytics.insights.sync.button')":title="$t('analytics.insights.sync.button')"data-testid="insights-sync-status"diff --git a/resources/js/components/analytics/RankBadge.vue b/resources/js/components/analytics/RankBadge.vuenew file mode 100644index 000000000..8547f5855--- /dev/null+++ b/resources/js/components/analytics/RankBadge.vue@@ -0,0 +1,13 @@+<script setup lang="ts">+defineProps<{+ /** The post's place in the ranking, from 1. */+ rank: number;+}>();+</script>++<template>+ <span+ class="inline-flex h-6 min-w-7 shrink-0 items-center justify-center rounded-md bg-primary-selected px-1.5 text-xs font-semibold text-primary-text tabular-nums"+ >#{{ rank }}</span+ >+</template>diff --git a/resources/js/components/analytics/ShareChartButton.vue b/resources/js/components/analytics/ShareChartButton.vuenew file mode 100644index 000000000..c78279323--- /dev/null+++ b/resources/js/components/analytics/ShareChartButton.vue@@ -0,0 +1,85 @@+<script setup lang="ts">+import { usePage } from '@inertiajs/vue3';+import { IconShare2 } from '@tabler/icons-vue';+import { computed, onMounted, ref, shallowRef } from 'vue';++import ShareChartDialog from '@/components/analytics/ShareChartDialog.vue';+import { Button } from '@/components/ui/button';+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from '@/components/ui/tooltip';+import {+ prepareShareCard,+ type ShareMetricOption,+} from '@/lib/shareCard';+import { whenIdle } from '@/lib/utils';++const props = defineProps<{+ /** The channel the numbers belong to; the current workspace when left out. */+ subject?: string;+ range: string;+ /** Builds what the card shows; runs on open, so its labels read the loaded locale. */+ build: () => ShareMetricOption;+ testId: string;+}>();++const page = usePage();+/** Whose numbers the card shows: the channel, else the current workspace. */+const shareSubject = computed((): string => {+ if (props.subject) {+ return props.subject;+ }++ return page.props.auth.currentWorkspace?.name ?? '';+});+const open = ref(false);+const option = shallowRef<ShareMetricOption | null>(null);++/** The card's fonts and channel photos load while the page is idle, so the first preview paints at once. */+const preloaded = ref(false);++onMounted(() => {+ whenIdle(async () => {+ await prepareShareCard(props.build());+ preloaded.value = true;+ });+});++const openDialog = (): void => {+ option.value = props.build();+ open.value = true;+};+</script>++<template>+ <div class="contents">+ <TooltipProvider :delay-duration="300">+ <Tooltip>+ <TooltipTrigger as-child>+ <Button+ type="button"+ variant="outline"+ size="icon"+ class="shrink-0"+ :aria-label="$t('analytics.share.button')"+ :data-testid="testId"+ :data-state="preloaded ? 'ready' : 'loading'"+ @click="openDialog"+ >+ <IconShare2 aria-hidden="true" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>{{ $t('analytics.share.button') }}</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ <ShareChartDialog+ v-model:open="open"+ :subject="shareSubject"+ :range="range"+ :option="option"+ />+ </div>+</template>diff --git a/resources/js/components/analytics/ShareChartDialog.vue b/resources/js/components/analytics/ShareChartDialog.vuenew file mode 100644index 000000000..903216ca4--- /dev/null+++ b/resources/js/components/analytics/ShareChartDialog.vue@@ -0,0 +1,285 @@+<script setup lang="ts">+import {+ IconCopy,+ IconDownload,+} from '@tabler/icons-vue';+import { useResizeObserver } from '@vueuse/core';+import { trans, wTrans } from 'laravel-vue-i18n';+import { computed, nextTick, ref, useTemplateRef, watch } from 'vue';+import { toast } from 'vue-sonner';++import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { openPostComposer } from '@/composables/useGlobalPostComposer';+import {+ drawShareCard,+ prepareShareCard,+ SHARE_CARD_SIZE,+ SHARE_TINTS,+ shareCardFile,+ type ShareCardOptions,+ type ShareMetricOption,+ type ShareTint,+} from '@/lib/shareCard';+import { copyImageToClipboard, downloadFile } from '@/lib/utils';+import { storeChunked } from '@/routes/app/media';+import { uploadChunked } from '@/utils/chunkedUpload';++const props = defineProps<{+ subject: string;+ range: string;+ option: ShareMetricOption | null;+}>();++const open = defineModel<boolean>('open', { default: false });++const tint = ref<ShareTint>(SHARE_TINTS[0]);+const posting = ref(false);+const painted = ref(false);+const canvas = useTemplateRef<HTMLCanvasElement>('canvas');++const previewDescription = computed((): string =>+ [props.option?.label, props.option?.figure].filter(Boolean).join(' '),+);++/** The signature, kept up to date as the locale loads (see `.ai/rules/js.md`). */+const mark = wTrans('analytics.share.mark');++const card = computed((): ShareCardOptions | null => {+ if (!props.option) {+ return null;+ }++ return {+ ...props.option,+ tint: tint.value,+ subject: props.subject,+ range: props.range,+ mark: mark.value,+ };+});++/** Below this the preview would get no pixels while its canvas is not laid out yet. */+const MIN_PREVIEW_SCALE = 0.25;++/**+ * The preview is drawn at the size it is shown, times the screen density, so+ * the browser never shrinks a bigger card into it and blurs the text.+ */+const previewScale = (preview: HTMLCanvasElement): number => {+ const shownWidth = preview.clientWidth * window.devicePixelRatio;++ return Math.max(shownWidth / SHARE_CARD_SIZE.width, MIN_PREVIEW_SCALE);+};++/** Whether this opening's preview already failed to draw, so its error is told once, not on every repaint. */+let paintFailed = false;++/** Draws the preview, and says whether it could: not before the dialog has its card and canvas. */+const drawPreview = async (): Promise<boolean> => {+ await nextTick();++ if (!card.value) {+ return false;+ }++ const images = await prepareShareCard(card.value);++ if (!canvas.value || !card.value) {+ return false;+ }++ drawShareCard(canvas.value, card.value, images, previewScale(canvas.value));++ return true;+};++/** Draws the preview; a browser that cannot draw the card stops loading and is told so once. */+const paint = async (): Promise<void> => {+ try {+ if (await drawPreview()) {+ painted.value = true;+ }+ } catch {+ if (!paintFailed) {+ toast.error(trans('analytics.share.export_failed'));+ }++ paintFailed = true;+ painted.value = true;+ }+};++/** The image uploading for Create post, stopped when the dialog closes so the composer never opens later. */+let postUpload: AbortController | null = null;++watch(open, (isOpen) => {+ if (!isOpen) {+ postUpload?.abort();++ return;+ }++ posting.value = false;+ painted.value = false;+ paintFailed = false;+ paint();+});++useResizeObserver(canvas, () => paint());++watch(card, () => {+ paint();+});++/** The card as a PNG file, at download resolution. */+const exportFile = async (): Promise<File> => {+ if (!card.value) {+ throw new Error('Nothing to share');+ }++ return shareCardFile(card.value);+};++const download = async (): Promise<void> => {+ try {+ downloadFile(await exportFile());+ } catch {+ toast.error(trans('analytics.share.export_failed'));+ }+};++const copyImage = async (): Promise<void> => {+ try {+ await copyImageToClipboard(exportFile());+ toast.success(trans('analytics.share.copied'));+ } catch {+ toast.error(trans('analytics.share.copy_failed'));+ }+};++const chooseTint = (swatch: ShareTint): void => {+ tint.value = swatch;+};++const createPost = async (): Promise<void> => {+ postUpload = new AbortController();+ const { signal } = postUpload;+ posting.value = true;++ try {+ const media = await uploadChunked({+ file: await exportFile(),+ url: storeChunked.url(),+ signal,+ });++ open.value = false;+ openPostComposer({+ draft: {+ content: props.option?.caption ?? '',+ media: [media],+ scheduled_at: null,+ label_ids: [],+ },+ });+ } catch {+ if (!signal.aborted) {+ toast.error(trans('analytics.share.post_failed'));+ }+ } finally {+ if (postUpload?.signal === signal) {+ posting.value = false;+ }+ }+};+</script>++<template>+ <Dialog v-model:open="open">+ <DialogContent class="sm:max-w-2xl" data-testid="share-chart-dialog">+ <DialogHeader>+ <DialogTitle>{{ $t('analytics.share.title') }}</DialogTitle>+ <DialogDescription>+ {{ $t('analytics.share.description') }}+ </DialogDescription>+ </DialogHeader>++ <canvas+ ref="canvas"+ class="aspect-video w-full rounded-lg"+ :class="{ 'animate-pulse bg-muted': !painted }"+ role="img"+ :aria-label="previewDescription"+ :data-state="painted ? 'ready' : 'loading'"+ :data-shape="option?.shape"+ data-testid="share-chart-preview"+ />++ <div class="grid w-full gap-2">+ <span class="text-sm font-medium text-foreground">{{+ $t('analytics.share.color')+ }}</span>+ <div+ class="grid grid-cols-8 gap-2.5 sm:grid-cols-16"+ role="radiogroup"+ :aria-label="$t('analytics.share.color')"+ >+ <button+ v-for="swatch in SHARE_TINTS"+ :key="swatch.key"+ type="button"+ role="radio"+ :aria-checked="tint.key === swatch.key"+ :aria-label="$t(`analytics.share.colors.${swatch.key}`)"+ class="aspect-square w-full cursor-pointer rounded-md bg-(--swatch) inset-ring inset-ring-black/6 ring-offset-background transition-[box-shadow] focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring aria-checked:inset-ring-0 aria-checked:ring-[1.5px] aria-checked:ring-offset-2 aria-checked:ring-(--swatch-ring)"+ :style="{+ '--swatch': swatch.ground,+ '--swatch-ring': swatch.strong,+ }"+ :data-testid="`share-chart-color-${swatch.key}`"+ @click="chooseTint(swatch)"+ />+ </div>+ </div>++ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ class="max-sm:flex-1"+ data-testid="share-chart-download"+ @click="download"+ >+ <IconDownload aria-hidden="true" />+ {{ $t('analytics.share.download') }}+ </Button>+ <Button+ type="button"+ variant="outline"+ class="max-sm:flex-1"+ data-testid="share-chart-copy"+ @click="copyImage"+ >+ <IconCopy aria-hidden="true" />+ {{ $t('analytics.share.copy') }}+ </Button>+ <Button+ type="button"+ :loading="posting"+ data-testid="share-chart-post"+ @click="createPost"+ >+ {{ $t('analytics.share.create_post') }}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+</template>diff --git a/resources/js/components/analytics/channel/ChannelMetricsCard.vue b/resources/js/components/analytics/channel/ChannelMetricsCard.vueindex 10497e39c..3b92ba342 100644--- a/resources/js/components/analytics/channel/ChannelMetricsCard.vue+++ b/resources/js/components/analytics/channel/ChannelMetricsCard.vue@@ -18,8 +18,12 @@ import {IconWorld,} from '@tabler/icons-vue';import { wTrans } from 'laravel-vue-i18n';-import { computed, ref, type Component } from 'vue';+import { computed, type Component, reactive, ref } from 'vue';+import ChannelMetricsChart from '@/components/analytics/channel/ChannelMetricsChart.vue';+import ComparedRange from '@/components/analytics/ComparedRange.vue';+import MetricChange from '@/components/analytics/MetricChange.vue';+import ShareChartButton from '@/components/analytics/ShareChartButton.vue';import AnalyticsModeToggle from '@/components/analytics/workspace/AnalyticsModeToggle.vue';import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';import { Button } from '@/components/ui/button';@@ -40,6 +44,7 @@ import date from '@/date';import {availablePresets,bucketLabel,+ definedValues,formatSeriesValue,growthRateSeries,hasEnoughHistory,@@ -48,18 +53,30 @@ import {metricInsight,monthLabel,POST_TOTAL_METRICS,+ type MetricDelta,+ seriesDelta,+ shownPeriod,seriesFor,type ChartMode,type PresetKey,type Selection,type SeriesSpec,} from '@/lib/channelMetrics';-import type { ChannelMetricSeries, SeriesMetric } from '@/types/analytics';+import {+ channelChartShareOption,+} from '@/lib/insightsShare';+import type { ShareMetricOption } from '@/lib/shareCard';+import type {+ ChannelMetricSeries,+ DateRange,+ FollowerGrowthRate,+ SeriesMetric,+} from '@/types/analytics';-import ChannelMetricsChart from './ChannelMetricsChart.vue';const props = defineProps<{series?: ChannelMetricSeries;+ channel: string;}>();const METRIC_ICONS: Record<SeriesMetric, Component> = {@@ -99,29 +116,17 @@ const modes = [] as const;const SELECTED = 'border-transparent bg-primary-selected text-primary-text hover:bg-primary-selected hover:text-primary-text';-const translatedLabels = Object.fromEntries(- (- [- 'posts',- 'followers',- 'net_followers',- 'reach',- 'views',- 'impressions',- 'profile_visits',- 'growth_rate',- ] as SeriesMetric[]- ).map((metric) => [metric, wTrans(`analytics.channel.series.${metric}`)]),-);-const comparisonAxis = wTrans('analytics.channel.metrics_card.comparison_axis');-const seriesLabels = computed<Partial<Record<SeriesMetric, string>>>(() =>- Object.fromEntries(- Object.entries(translatedLabels).map(([metric, label]) => [- metric,- label.value,- ]),- ),-);+/** Every series metric's name, kept up to date as the locale loads (see `.ai/rules/js.md`); `reactive` reads each through. */+const seriesLabels: Record<SeriesMetric, string> = reactive({+ posts: wTrans('analytics.channel.series.posts'),+ followers: wTrans('analytics.channel.series.followers'),+ net_followers: wTrans('analytics.channel.series.net_followers'),+ reach: wTrans('analytics.channel.series.reach'),+ views: wTrans('analytics.channel.series.views'),+ impressions: wTrans('analytics.channel.series.impressions'),+ profile_visits: wTrans('analytics.channel.series.profile_visits'),+ growth_rate: wTrans('analytics.channel.series.growth_rate'),+});const primaryMetric = ref<SeriesMetric>('posts');const selection = ref<Selection>({ kind: 'preset', preset: 'content_impact' });@@ -163,10 +168,25 @@ const chartSeries = computed<ChannelMetricSeries | undefined>(() =>? growthRateSeries(props.series.growth): props.series,);-const chartMode = computed<ChartMode>(() =>- growthRate.value ? 'current' : mode.value,-);const specs = computed<SeriesSpec[]>(() => seriesFor(activeSelection.value));+/** Whether any metric the chart shows has data in the previous period; without it there is nothing to compare. */+const hasComparison = computed(() => {+ const series = chartSeries.value;++ if (!series) {+ return false;+ }++ return specs.value.some((spec) => definedValues(series.previous, spec.metric).length > 0);+});+/** The periods the chart shows: only this period for the growth rate or when nothing can be compared. */+const chartMode = computed<ChartMode>(() => {+ if (growthRate.value || !hasComparison.value) {+ return 'current';+ }++ return mode.value;+});const enoughHistory = computed(() =>chartSeries.value? hasEnoughHistory(chartSeries.value, specs.value, chartMode.value)@@ -192,42 +212,81 @@ const insightIcon = computed(() => {const showsPostTotals = computed(() =>specs.value.some((spec) => POST_TOTAL_METRICS.includes(spec.metric)),);+/** The growth rate's twelve months, as the card names them: "Nov 2025 – Oct 2026". */+const growthMonths = (growth: FollowerGrowthRate): string =>+ `${monthLabel(growth.range.start)} – ${monthLabel(growth.range.end)}`;+const rangeCaption = computed(() => {if (!props.series) {return null;}if (growthRate.value && props.series.growth) {- const { start, end } = props.series.growth.range;-- return `${monthLabel(start)} – ${monthLabel(end)}`;+ return growthMonths(props.series.growth);}- return `${date.formatDayMonthYear(props.series.range.start)} – ${date.formatDayMonthYear(props.series.range.end)}`;+ return date.formatDayMonthYearRange(props.series.range);});-const previousCaption = computed(() =>- props.series- ? `${date.formatDayMonthYear(props.series.previous_range.start)} – ${date.formatDayMonthYear(props.series.previous_range.end)}`- : '',+/** The period the chart shows: the previous one in the Comparison view. */+const shownRange = (series: ChannelMetricSeries): DateRange => {+ if (chartMode.value === 'previous') {+ return series.previous_range;+ }++ return series.range;+};++/** The period the share card names, as the page's subtitle does: the growth rate's months, else the days shown. */+const shareRange = (series: ChannelMetricSeries): string => {+ if (growthRate.value && props.series?.growth) {+ return growthMonths(props.series.growth);+ }++ return date.formatDayMonthYearRange(shownRange(series));+};++/** What the Share button needs: the chart as it is drawn now, or null while there is nothing to share. */+const share = computed(+ (): { range: string; build: () => ShareMetricOption } | null => {+ const series = chartSeries.value;++ if (!series || specs.value.length === 0 || !enoughHistory.value) {+ return null;+ }++ const range = shareRange(series);++ return {+ range,+ build: () =>+ channelChartShareOption(+ series,+ specs.value,+ chartMode.value,+ seriesLabels,+ props.channel,+ range,+ ),+ };+ },);-const shownTotals = computed(() =>- chartMode.value === 'previous'- ? chartSeries.value?.totals.previous- : chartSeries.value?.totals.current,+const shownTotals = computed(+ () => chartSeries.value?.totals[shownPeriod(chartMode.value)],);-const axisLabels = computed<Partial<Record<SeriesSpec['axis'], string>>>(() =>- Object.fromEntries(- specs.value.map((spec) => {- const label = seriesLabels.value[spec.metric] ?? '';-- return [- spec.axis,- chartMode.value === 'previous'- ? comparisonAxis.value.replace(':metric', label)- : label,- ];- }),- ),+/** How each shown metric moved since the previous period; the Comparison view shows the previous period itself. */+const deltaOf = (metric: SeriesMetric): MetricDelta | null => {+ const series = props.series;++ if (!series || chartMode.value === 'previous') {+ return null;+ }++ return seriesDelta(series, metric);+};++/** Each metric of the legend with its change, so the template reads a change it has already checked. */+const legend = computed((): { spec: SeriesSpec; delta: MetricDelta | null }[] =>+ specs.value.map((spec) => ({ spec, delta: deltaOf(spec.metric) })),);const isMetricActive = computed(@@ -267,6 +326,14 @@ const changeMode = (value: string): void => {:title="$t('analytics.channel.metrics_card.title')"subtitle-testid="insights-metrics-caption">+ <template v-if="share" #actions>+ <ShareChartButton+ :subject="channel"+ :range="share.range"+ :build="share.build"+ test-id="share-channel-metrics"+ />+ </template><template v-if="rangeCaption" #subtitle><template v-if="growthRate">{{ rangeCaption }} ·@@ -278,14 +345,11 @@ const changeMode = (value: string): void => {}}</span></template>- <template v-else>- {{- $t('analytics.ranges.compared_to', {- current: rangeCaption,- previous: previousCaption,- })- }}- </template>+ <ComparedRange+ v-else-if="series"+ :range="series.range"+ :previous="series.previous_range"+ /></template><div data-testid="insights-metrics">@@ -464,7 +528,7 @@ const changeMode = (value: string): void => {data-testid="insights-metrics-legend"><div- v-for="spec in specs"+ v-for="{ spec, delta } in legend":key="spec.metric"class="flex min-w-0 flex-col gap-1":data-testid="`insights-metrics-legend-${spec.metric}`"@@ -525,10 +589,17 @@ const changeMode = (value: string): void => {></span></span>+ <MetricChange+ v-if="delta"+ class="self-start"+ :data-testid="`insights-metrics-legend-${spec.metric}-change`"+ :change="delta.value"+ :label="delta.label"+ /></div></div><AnalyticsModeToggle- v-if="!growthRate"+ v-if="!growthRate && hasComparison":model-value="mode"label="analytics.channel.metrics_card.chart_mode":options="modes"@@ -544,7 +615,6 @@ const changeMode = (value: string): void => {:specs="specs":mode="chartMode":labels="seriesLabels"- :axis-labels="axisLabels"/><divv-elsediff --git a/resources/js/components/analytics/channel/ChannelMetricsChart.vue b/resources/js/components/analytics/channel/ChannelMetricsChart.vueindex f413ec749..9841b6cbc 100644--- a/resources/js/components/analytics/channel/ChannelMetricsChart.vue+++ b/resources/js/components/analytics/channel/ChannelMetricsChart.vue@@ -1,6 +1,7 @@<script setup lang="ts">import {VisAxis,+ VisAxisSelectors,VisGroupedBar,VisGroupedBarSelectors,VisLine,@@ -10,35 +11,36 @@ import {} from '@unovis/vue';import { computed } from 'vue';+import ChannelMetricsTooltip from '@/components/analytics/channel/ChannelMetricsTooltip.vue';import {+ type ChartConfig,ChartContainer,ChartCrosshair,ChartTooltip,componentToString,- type ChartConfig,+ numericTick,} from '@/components/ui/chart';-import date from '@/date';+import { useChartAppContext } from '@/composables/analytics/useChartAppContext';import {AXIS_STEPS,+ axisBucketLabel,+ axisDomain,+ axisTickLabels,bucketLabel,+ chartPeriods,definedValues,- formatSeriesValue,- isPercentMetric,- monthLabel,- niceDomain,+ shownPeriod,type ChartMode,type SeriesSpec,} from '@/lib/channelMetrics';-import { formatNumberCompact } from '@/lib/utils';import type {ChannelMetricSeries,MetricSeriesPoint,+ PublicationPeriod,SeriesMetric,} from '@/types/analytics';-import ChannelMetricsTooltip from './ChannelMetricsTooltip.vue';-type Period = 'current' | 'previous';type ChartPoint = {index: number;current: MetricSeriesPoint;@@ -50,8 +52,7 @@ const props = defineProps<{series: ChannelMetricSeries;specs: SeriesSpec[];mode: ChartMode;- labels: Partial<Record<SeriesMetric, string>>;- axisLabels: Partial<Record<SeriesSpec['axis'], string>>;+ labels: Record<SeriesMetric, string>;}>();const DASH = [5, 4];@@ -60,35 +61,22 @@ const tickValues = Array.from((_, index) => index / AXIS_STEPS,);-const shownPeriods = computed<Period[]>(() =>- props.mode === 'both'- ? ['current', 'previous']- : [props.mode === 'previous' ? 'previous' : 'current'],-);+const shownPeriods = computed((): PublicationPeriod[] => chartPeriods(props.mode));-const domains = computed(() => {- const domainFor = (axis: SeriesSpec['axis']) => {- const specs = props.specs.filter((spec) => spec.axis === axis);+/** The metrics drawn on an axis. */+const axisMetrics = (axis: SeriesSpec['axis']): SeriesMetric[] =>+ props.specs.filter((spec) => spec.axis === axis).map((spec) => spec.metric);- if (specs.length === 0) {- return null;- }+const domainFor = (axis: SeriesSpec['axis']): { min: number; max: number } | null => {+ const metrics = axisMetrics(axis);+ const values = metrics.flatMap((metric) =>+ shownPeriods.value.flatMap((period) => definedValues(props.series[period], metric)),+ );- const values = specs.flatMap((spec) =>- shownPeriods.value.flatMap((period) =>- definedValues(props.series[period], spec.metric),- ),- );-- return niceDomain(- values,- specs.some((spec) => spec.metric !== 'followers'),- specs.some((spec) => isPercentMetric(spec.metric)),- );- };+ return axisDomain(metrics, values);+};- return { left: domainFor('left'), right: domainFor('right') };-});+const domains = computed(() => ({ left: domainFor('left'), right: domainFor('right') }));const normalise = (value: number | null | undefined,@@ -124,14 +112,14 @@ const chartData = computed<ChartPoint[]>(() =>);const accessor =- (period: Period, metric: SeriesMetric) =>+ (period: PublicationPeriod, metric: SeriesMetric) =>(point: ChartPoint): number | undefined => {const value = point[`${period}_${metric}`];return typeof value === 'number' ? value : undefined;};const barAccessor =- (period: Period, metric: SeriesMetric) =>+ (period: PublicationPeriod, metric: SeriesMetric) =>(point: ChartPoint): number =>accessor(period, metric)(point) ?? 0;const xAccessor = (point: ChartPoint): number => point.index;@@ -143,7 +131,7 @@ type Layer = {key: string;spec: SeriesSpec;kind: 'grouped' | 'bar' | 'line';- period: Period;+ period: PublicationPeriod;dashed: boolean;};@@ -191,38 +179,42 @@ const svgDefs = computed(() =>.join(''),);-const tickLabel =- (axis: SeriesSpec['axis']) =>- (tick: number | Date): string => {- const domain = domains.value[axis];+/** Each axis' tick labels, bottom up, read by the axis' tick position. */+const axisLabels = computed((): Record<SeriesSpec['axis'], string[]> => ({+ left: tickLabelsFor('left'),+ right: tickLabelsFor('right'),+}));- if (!domain || typeof tick !== 'number') {- return '';- }+const tickLabelsFor = (axis: SeriesSpec['axis']): string[] => {+ const domain = domains.value[axis];- const spec = props.specs.find((candidate) => candidate.axis === axis);- const value = domain.min + tick * (domain.max - domain.min);+ if (!domain) {+ return [];+ }- return spec && isPercentMetric(spec.metric)- ? formatSeriesValue(value, spec.metric)- : formatNumberCompact(value, 2);- };+ return axisTickLabels(domain, axisMetrics(axis));+};++const tickLabel = (axis: SeriesSpec['axis']) =>+ numericTick(+ (tick): string =>+ axisLabels.value[axis][Math.round(tick * AXIS_STEPS)] ?? '',+ );++/** Names each value tick by its axis, so a test reads the labels the axis prints. */+const axisTickAttributes = (axis: SeriesSpec['axis']): Record<string, Record<string, string>> => ({+ [VisAxisSelectors.tick]: { 'data-testid': `insights-metrics-${axis}-tick` },+});-const xTick = (tick: number | Date): string => {- const index = typeof tick === 'number' ? Math.round(tick) : 0;- const point =- props.mode === 'previous'- ? props.series.previous[index]- : props.series.current[index];+const xTick = numericTick((tick): string => {+ const point = props.series[shownPeriod(props.mode)][Math.round(tick)];if (!point) {return '';}- return props.series.resolution === 'monthly'- ? monthLabel(point.start)- : date.formatMonthDay(point.start);-};+ return axisBucketLabel(point, props.series.resolution);+});const dateLabel = (point: MetricSeriesPoint | undefined): string =>bucketLabel(point, props.series.resolution);@@ -231,18 +223,19 @@ const config = computed<ChartConfig>(() =>Object.fromEntries(props.specs.map((spec) => [spec.metric,- { label: props.labels[spec.metric] ?? '', color: spec.color },+ { label: props.labels[spec.metric], color: spec.color },]),),);+const appContext = useChartAppContext();const tooltipTemplate = computed(() =>componentToString(config.value, ChannelMetricsTooltip, {specs: props.specs,labels: props.labels,mode: props.mode,dateLabel,- }),+ }, appContext),);const xDomain = computed<[number, number]>(() => [@@ -256,11 +249,22 @@ const barAttributes = {const groupedBarAttributes = {[VisGroupedBarSelectors.bar]: { 'data-testid': 'insights-metrics-bar' },};+/** Room for an axis' tick labels, and the plain edge on the right when no metric uses that axis. */+const MARGIN = { top: 12, bottom: 28, axis: 56, edge: 12 };++const rightMargin = (): number => {+ if (domains.value.right) {+ return MARGIN.axis;+ }++ return MARGIN.edge;+};+const margin = computed(() => ({- top: 12,- right: domains.value.right ? 64 : 12,- bottom: 28,- left: 64,+ top: MARGIN.top,+ right: rightMargin(),+ bottom: MARGIN.bottom,+ left: MARGIN.axis,}));const numTicks = computed(() =>Math.min(props.series.current.length, 6),@@ -334,9 +338,7 @@ const numTicks = computed(() =>type="y":tick-format="tickLabel('left')":tick-values="tickValues"- :label="axisLabels.left"- label-font-size="11px"- label-color="var(--muted-foreground)"+ :attributes="axisTickAttributes('left')":grid-line="true":domain-line="false":tick-line="false"@@ -367,9 +369,7 @@ const numTicks = computed(() =>position="right":tick-format="tickLabel('right')":tick-values="tickValues"- :label="axisLabels.right"- label-font-size="11px"- label-color="var(--muted-foreground)"+ :attributes="axisTickAttributes('right')":grid-line="false":domain-line="false":tick-line="false"diff --git a/resources/js/components/analytics/channel/ChannelMetricsTooltip.vue b/resources/js/components/analytics/channel/ChannelMetricsTooltip.vueindex 6f3f6959e..d6526c293 100644--- a/resources/js/components/analytics/channel/ChannelMetricsTooltip.vue+++ b/resources/js/components/analytics/channel/ChannelMetricsTooltip.vue@@ -1,13 +1,12 @@<script setup lang="ts">import { computed } from 'vue';-import { activeLocale } from '@/language';import {isPercentMetric,type ChartMode,type SeriesSpec,} from '@/lib/channelMetrics';-import { formatPercent } from '@/lib/utils';+import { formatFullNumber, formatPercent } from '@/lib/utils';import type { MetricSeriesPoint, SeriesMetric } from '@/types/analytics';const props = withDefaults(@@ -16,7 +15,7 @@ const props = withDefaults(config?: Record<string, unknown>;x?: number | Date;specs: SeriesSpec[];- labels: Partial<Record<SeriesMetric, string>>;+ labels: Record<SeriesMetric, string>;mode: ChartMode;dateLabel: (point: MetricSeriesPoint | undefined) => string;}>(),@@ -43,13 +42,11 @@ const display = (value: number | null | undefined,metric: SeriesMetric,): string => {- if (value === null || value === undefined) {- return '—';+ if (isPercentMetric(metric)) {+ return formatPercent(value);}- return isPercentMetric(metric)- ? formatPercent(value)- : value.toLocaleString(activeLocale.value);+ return formatFullNumber(value);};</script>diff --git a/resources/js/components/analytics/channel/ChannelPublicationTable.vue b/resources/js/components/analytics/channel/ChannelPublicationTable.vueindex d2693849b..1ffa1d115 100644--- a/resources/js/components/analytics/channel/ChannelPublicationTable.vue+++ b/resources/js/components/analytics/channel/ChannelPublicationTable.vue@@ -14,6 +14,7 @@ import {import { computed, ref, watch } from 'vue';import PublicationTypeBadge from '@/components/analytics/PublicationTypeBadge.vue';+import RankBadge from '@/components/analytics/RankBadge.vue';import AnalyticsModeToggle from '@/components/analytics/workspace/AnalyticsModeToggle.vue';import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';import PostDetailsDialog from '@/components/publish/PostDetailsDialog.vue';@@ -209,7 +210,6 @@ const pages = computed<PageItem[]>(() => {return items;});-const isReloading = ref(false);const reload = (@@ -302,17 +302,12 @@ const openRow = (row: ChannelPublicationRow): void => {openPublication(row.id);};-const display = (row: ChannelPublicationRow, key: SummaryMetric): string => {- const value = row.metrics[key];-- if (value === null || value === undefined) {- return '—';+ if (key === 'engagement_rate') {+ return formatPercent(row.metrics[key]);}- return key === 'engagement_rate'- ? formatPercent(value)- : formatNumberCompact(value);+ return formatNumberCompact(row.metrics[key]);};</script>@@ -475,11 +470,10 @@ const display = (row: ChannelPublicationRow, key: SummaryMetric): string => {:data-testid="`insights-posts-link-${row.id}`"@click="openRow(row)">- <span- class="inline-flex h-6 min-w-7 shrink-0 items-center justify-center rounded-md bg-accent px-1.5 text-xs font-medium text-foreground tabular-nums"+ <RankBadge+ :rank="row.rank":data-testid="`insights-posts-rank-${row.id}`"- >#{{ row.rank }}</span- >+ /><spanclass="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground">diff --git a/resources/js/components/analytics/channel/PostTypeFilter.vue b/resources/js/components/analytics/channel/PostTypeFilter.vueindex e25b30af2..d0ccc3da8 100644--- a/resources/js/components/analytics/channel/PostTypeFilter.vue+++ b/resources/js/components/analytics/channel/PostTypeFilter.vue@@ -33,6 +33,7 @@ const clear = (): void => {:empty-message="$t('analytics.channel.filters.no_post_types')":select-all-label="$t('posts.composer.select_all')":deselect-all-label="$t('posts.composer.deselect_all')"+ sheet-below-sm:test-id="testId":show-header="false"compactdiff --git a/resources/js/components/analytics/workspace/AccountIdentity.vue b/resources/js/components/analytics/workspace/AccountIdentity.vueindex fedc56f77..df29482d9 100644--- a/resources/js/components/analytics/workspace/AccountIdentity.vue+++ b/resources/js/components/analytics/workspace/AccountIdentity.vue@@ -6,6 +6,7 @@ import {getPlatformLabel,getPlatformLogo,} from '@/composables/usePlatformLogo';+import { accountLabel } from '@/lib/analyticsAccounts';import type { AccountIdentityData } from '@/types/analytics';const props = defineProps<{@@ -16,16 +17,7 @@ const props = defineProps<{/** The name on top and the @handle below it. */withName?: boolean;}>();-const label = computed(() =>- props.account.username- ? `@${props.account.username}`- : props.account.name || getPlatformLabel(props.account.platform),-);-const name = computed(- () =>- props.account.name ||- label.value,-);+const label = computed(() => accountLabel(props.account));const handle = computed(() =>props.account.name && props.account.username? `@${props.account.username}`@@ -48,7 +40,7 @@ const handle = computed(() =>v-if="withAvatar":platform="account.platform":src="account.avatar_url"- :name="withName ? name : label"+ :name="label"ring="card":size="avatarSize ?? 32":status="account.status"@@ -63,7 +55,7 @@ const handle = computed(() =>/><span v-if="withName" class="flex min-w-0 flex-col"><span class="truncate text-xs font-emphasis text-foreground">{{- name+ label}}</span><spanv-if="handle"diff --git a/resources/js/components/analytics/workspace/AnalyticsModeToggle.vue b/resources/js/components/analytics/workspace/AnalyticsModeToggle.vueindex 3f9642996..bcffe5136 100644--- a/resources/js/components/analytics/workspace/AnalyticsModeToggle.vue+++ b/resources/js/components/analytics/workspace/AnalyticsModeToggle.vue@@ -18,7 +18,7 @@ const emit = defineEmits<{ 'update:modelValue': [value: string] }>();<template><div- class="inline-flex items-center gap-1 rounded-lg border border-border-strong p-1"+ class="inline-flex items-center gap-1 rounded-lg border border-border-strong p-1 max-sm:flex max-sm:w-full"role="group":aria-label="trans(label)">@@ -27,7 +27,7 @@ const emit = defineEmits<{ 'update:modelValue': [value: string] }>();:key="option.mode"type="button":data-testid="option.test"- class="inline-flex h-6 shrink-0 items-center gap-1 rounded-md px-2 text-sm font-medium whitespace-nowrap transition-control focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"+ class="inline-flex h-6 shrink-0 items-center gap-1 rounded-md px-2 text-sm font-medium whitespace-nowrap transition-control max-sm:flex-1 max-sm:justify-center max-sm:px-1.5 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring":class="modelValue === option.mode? 'bg-primary-selected text-primary-text'@@ -39,7 +39,7 @@ const emit = defineEmits<{ 'update:modelValue': [value: string] }>();<component:is="option.icon"v-if="option.icon"- class="size-3.5"+ class="size-3.5 max-sm:hidden"aria-hidden="true"/>{{ trans(option.label) }}diff --git a/resources/js/components/analytics/workspace/AnalyticsSection.vue b/resources/js/components/analytics/workspace/AnalyticsSection.vueindex 212384456..493fdf7a3 100644--- a/resources/js/components/analytics/workspace/AnalyticsSection.vue+++ b/resources/js/components/analytics/workspace/AnalyticsSection.vue@@ -1,8 +1,9 @@<script setup lang="ts">+import ComparedRange from '@/components/analytics/ComparedRange.vue';+import InfoTip from '@/components/analytics/workspace/InfoTip.vue';import date from '@/date';import type { WorkspaceAnalyticsReport } from '@/types/analytics';-import InfoTip from './InfoTip.vue';defineProps<{title: string;@@ -11,6 +12,8 @@ defineProps<{subtitle?: string;subtitleTestid?: string;range?: WorkspaceAnalyticsReport['range'];+ /** The period the section's changes compare against, shown next to `range`. */+ previousRange?: WorkspaceAnalyticsReport['range'];flush?: boolean;}>();</script>@@ -23,7 +26,7 @@ defineProps<{<divclass="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 px-4 pt-4 pb-4 sm:px-5">- <div class="flex min-w-0 flex-col gap-1">+ <div class="flex min-w-0 flex-1 basis-48 flex-col gap-1"><div class="-my-0.5 flex min-w-0 items-center gap-1"><h2class="font-heading text-base leading-6 font-medium text-foreground"@@ -33,21 +36,30 @@ defineProps<{</h2><InfoTip v-if="info" :text="info" :test-id="infoTestid" /></div>- <p+ <divv-if="subtitle || range || $slots.subtitle"class="text-xs text-muted-foreground":data-testid="subtitleTestid"><slot name="subtitle">- {{- range- ? `${date.formatDayMonthYear(range.start)} – ${date.formatDayMonthYear(range.end)}`- : subtitle- }}+ <ComparedRange+ v-if="range && previousRange"+ :range="range"+ :previous="previousRange"+ />+ <template v-else-if="range">+ {{ date.formatDayMonthYearRange(range) }}+ </template>+ <template v-else>{{ subtitle }}</template></slot>- </p>+ </div>+ </div>+ <div+ v-if="$slots.actions"+ class="flex items-center justify-end gap-2 max-sm:flex-1 sm:ms-auto"+ >+ <slot name="actions" /></div>- <slot name="actions" /></div><div :class="flush ? 'min-w-0' : 'min-w-0 px-4 pb-4 sm:px-5 sm:pb-5'"><slot />diff --git a/resources/js/components/analytics/workspace/FollowersChart.vue b/resources/js/components/analytics/workspace/FollowersChart.vueindex a8ecaf603..4ef45a1f3 100644--- a/resources/js/components/analytics/workspace/FollowersChart.vue+++ b/resources/js/components/analytics/workspace/FollowersChart.vue@@ -2,17 +2,34 @@import { trans } from 'laravel-vue-i18n';import { computed, ref } from 'vue';+import MetricChange from '@/components/analytics/MetricChange.vue';+import ShareChartButton from '@/components/analytics/ShareChartButton.vue';+import AnalyticsModeToggle from '@/components/analytics/workspace/AnalyticsModeToggle.vue';+import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';+import FollowerHistoryLineChart from '@/components/analytics/workspace/charts/FollowerHistoryLineChart.vue';+import SocialAccountMetricBarChart from '@/components/analytics/workspace/charts/SocialAccountMetricBarChart.vue';+import type { ChartTooltipDetail } from '@/components/ui/chart';import date from '@/date';-import { activeLocale } from '@/language';-import { accountColor } from '@/lib/analyticsColors';-import { formatNumberCompact, formatPercentChange } from '@/lib/utils';-import type { WorkspaceAnalyticsReport } from '@/types/analytics';+import {+ FOLLOWERS_ROWS,+ followersNet,+ followersShareOption,+ shareRangeLabel,+} from '@/lib/insightsShare';+import type { ShareMetricOption } from '@/lib/shareCard';+import {+ formatCountChange,+ formatFullNumber,+ formatNumberCompact,+ formatPercentChange,+ formatSignedNumber,+} from '@/lib/utils';+import type {+ AccountMetricRow,+ FollowersChartMode,+ WorkspaceAnalyticsReport,+} from '@/types/analytics';-import AccountIdentity from './AccountIdentity.vue';-import AnalyticsModeToggle from './AnalyticsModeToggle.vue';-import AnalyticsSection from './AnalyticsSection.vue';-import FollowerHistoryLineChart from './charts/FollowerHistoryLineChart.vue';-import SocialAccountMetricBarChart from './charts/SocialAccountMetricBarChart.vue';const props = defineProps<{followers: WorkspaceAnalyticsReport['followers'];@@ -22,7 +39,7 @@ const props = defineProps<{channelFiltered?: boolean;totalChannels?: number;}>();-const mode = ref<'bar' | 'line' | 'growth'>('bar');+const mode = ref<FollowersChartMode>('bar');const buttons = [{mode: 'bar',@@ -41,45 +58,90 @@ const buttons = [},] as const;-const barDetail = (index: number): string | null => {+/** A change's tone in the tooltip: green for a gain, red for a loss, none when flat. */+const changeTone = (change: number): ChartTooltipDetail['tone'] => {+ if (change > 0) {+ return 'up';+ }++ if (change < 0) {+ return 'down';+ }++ return undefined;+};++const changeLabel = (change: number): string => {+ if (change < 0) {+ return trans('analytics.dashboard.followers_lost_in_range');+ }++ return trans('analytics.dashboard.followers_gained_in_range');+};++/** What a channel gained or lost over the period, with its share of where it started when it started above zero. */+const changeDetail = (change: number, start: number): ChartTooltipDetail => {+ const label = changeLabel(change);+ const value = formatSignedNumber(change);++ if (start <= 0) {+ return { label, value, tone: changeTone(change) };+ }++ return {+ label,+ value: `${value} (${formatPercentChange((change / start) * 100)})`,+ tone: changeTone(change),+ };+};++/** The tooltip's rows under a channel in Bar view: where it started, and what it gained or lost. */+const barDetail = (index: number): ChartTooltipDetail[] => {const account = props.followers.accounts[index];const change = account?.net ?? null;- if (- mode.value !== 'bar' ||- !account ||- account.value === null ||- change === null- ) {- return null;+ if (mode.value !== 'bar' || !account || account.value === null || change === null) {+ return [];}const start = account.value - change;- const count = (value: number): string =>- value.toLocaleString(activeLocale.value);- return trans(- change < 0- ? 'analytics.dashboard.followers_lost_detail'- : 'analytics.dashboard.followers_gained_detail',+ return [{- start: count(start),- change: count(Math.abs(change)),- percent:- start > 0 ? formatPercentChange((change / start) * 100) : '—',+ label: trans('analytics.dashboard.followers_at_start'),+ value: formatFullNumber(start),},- );+ changeDetail(change, start),+ ];};-const hasGains = computed(() =>- props.followers.accounts.some((account) => (account.net ?? 0) > 0),-);-const legendColor = computed(() => {- const first = props.followers.accounts[0];+/** One bar per channel with its number: its followers (Bar) or its change over the period (Growth); none in Line. */+type BarChart = {+ rows: AccountMetricRow[];+ formatValue: (value: number | null) => string;+};++const barChart = computed((): BarChart | null => {+ if (mode.value === 'line') {+ return null;+ }++ const rows = FOLLOWERS_ROWS[mode.value];- return first- ? (props.colors[first.social_account_key] ?? accountColor(0))- : accountColor(0);+ return {+ rows: props.followers.accounts.map((account) => ({+ account,+ value: rows.value(account),+ })),+ formatValue: rows.format,+ };});+/** Whether the card has followers to share: channels with a reading, and their total. */+const canShare = computed(+ (): boolean =>+ props.followers.accounts.length > 0 && props.followers.total !== null,+);+/** What the period added or took away across every channel, as the share card shows it. */+const net = computed(() => followersNet(props.followers));const shownChannels = computed(() =>props.channelFiltered &&props.totalChannels &&@@ -87,10 +149,17 @@ const shownChannels = computed(() =>? props.followers.accounts.length: null,);-const rangeLabel = computed(- () =>- `${date.formatDayMonthYear(props.range.start)} – ${date.formatDayMonthYear(props.range.end)}`,-);+const rangeLabel = computed(() => date.formatDayMonthYearRange(props.range));+/** The period the share card names, with the channels it counts when filtered. */+const shareRange = (): string =>+ shareRangeLabel(rangeLabel.value, shownChannels.value, props.totalChannels);+const buildShareOption = (): ShareMetricOption =>+ followersShareOption(+ props.followers,+ shareRange(),+ mode.value,+ props.colors,+ );</script><template>@@ -116,6 +185,12 @@ const rangeLabel = computed(label="analytics.dashboard.followers_chart_mode":options="buttons"/>+ <ShareChartButton+ v-if="canShare"+ :range="shareRange()"+ :build="buildShareOption"+ test-id="share-followers"+ /></template><div@@ -132,18 +207,23 @@ const rangeLabel = computed(}}</div><div v-else class="min-w-0">- <div class="mb-5 flex flex-wrap items-baseline gap-2">- <span- class="font-heading text-[28px] leading-[35px] font-medium text-foreground tabular-nums"- >{{- followers.total === null- ? '—'- : formatNumberCompact(followers.total)- }}</span- >- <span class="text-sm text-muted-foreground">{{- $t('analytics.dashboard.total_followers')- }}</span>+ <div class="mb-5 grid gap-1">+ <div class="flex flex-wrap items-baseline gap-2">+ <span+ class="font-heading text-[28px] leading-[35px] font-medium text-foreground tabular-nums"+ >{{ formatNumberCompact(followers.total) }}</span+ >+ <span class="text-sm text-muted-foreground">{{+ $t('analytics.dashboard.total_followers')+ }}</span>+ </div>+ <MetricChange+ v-if="net !== null"+ class="justify-self-start"+ data-testid="analytics-followers-change"+ :change="net"+ :label="formatCountChange(net)"+ /></div><div class="min-w-0"><FollowerHistoryLineChart@@ -153,83 +233,13 @@ const rangeLabel = computed(:colors="colors"/><SocialAccountMetricBarChart- v-else- :rows="- followers.accounts.map((account) =>- mode === 'growth'- ? { account, value: account.growth }- : {- account,- value: account.value,- gained: Math.max(account.net ?? 0, 0),- },- )- "+ v-else-if="barChart"+ :rows="barChart.rows":colors="colors":detail="barDetail"+ :format-value="barChart.formatValue"/></div>- <div- v-if="mode === 'bar' && hasGains"- class="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground"- data-testid="analytics-followers-split-legend"- >- <span class="inline-flex items-center gap-1.5 whitespace-nowrap">- <span- class="size-2.5 rounded-[3px]"- :style="{- backgroundColor: `color-mix(in srgb, ${legendColor} 40%, var(--card))`,- }"- />- {{ $t('analytics.dashboard.followers_at_start') }}- </span>- <span class="inline-flex items-center gap-1.5 whitespace-nowrap">- <span- class="size-2.5 rounded-[3px]"- :style="{ backgroundColor: legendColor }"- />- {{ $t('analytics.dashboard.followers_gained_in_range') }}- </span>- </div>- <div- class="mt-5 grid gap-x-8 gap-y-1 border-t border-border pt-4 sm:grid-cols-2 xl:grid-cols-3"- >- <div- v-for="account in followers.accounts"- :key="account.social_account_key"- class="-mx-2 flex min-h-9 min-w-0 items-center justify-between gap-2 rounded-md px-2 transition-control hover:bg-accent/60"- >- <AccountIdentity- :account="account"- :color="colors[account.social_account_key]"- with-avatar- :avatar-size="24"- />- <span class="flex shrink-0 items-center gap-2">- <span class="text-sm font-medium text-foreground tabular-nums">- {{- mode === 'growth'- ? account.growth === null- ? '—'- : `${account.growth > 0 ? '+' : ''}${formatNumberCompact(account.growth)}`- : account.value === null- ? '—'- : formatNumberCompact(account.value)- }}- </span>- <span- v-if="account.provenance === 'carried_forward'"- class="text-[11px] text-muted-foreground"- :title="- $t('analytics.dashboard.carried_forward_hint')- "- >{{- $t('analytics.dashboard.carried_forward')- }}</span- >- </span>- </div>- </div></div></AnalyticsSection></template>diff --git a/resources/js/components/analytics/workspace/InsightsEmptyState.vue b/resources/js/components/analytics/workspace/InsightsEmptyState.vueindex 24bd92aa6..9a8fcbbc1 100644--- a/resources/js/components/analytics/workspace/InsightsEmptyState.vue+++ b/resources/js/components/analytics/workspace/InsightsEmptyState.vue@@ -6,12 +6,12 @@ import {IconTrendingUp,} from '@tabler/icons-vue';+import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';import { Button } from '@/components/ui/button';import { useConnectChannelDialog } from '@/composables/useConnectChannelDialog';import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';import date from '@/date';-import AnalyticsSection from './AnalyticsSection.vue';defineProps<{hasChannels: boolean;diff --git a/resources/js/components/analytics/workspace/PerformanceTable.vue b/resources/js/components/analytics/workspace/PerformanceTable.vueindex 051aecb45..71570a906 100644--- a/resources/js/components/analytics/workspace/PerformanceTable.vue+++ b/resources/js/components/analytics/workspace/PerformanceTable.vue@@ -7,6 +7,8 @@ import {import { computed, ref } from 'vue';import MetricChange from '@/components/analytics/MetricChange.vue';+import AccountIdentity from '@/components/analytics/workspace/AccountIdentity.vue';+import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';import { Checkbox } from '@/components/ui/checkbox';import {DropdownMenu,@@ -28,19 +30,14 @@ import {type PerformanceMetric,usePerformanceColumns,} from '@/composables/usePerformanceColumns';-import date from '@/date';+import { accountLabel } from '@/lib/analyticsAccounts';import {formatNumberCompact,formatPercent,formatPercentChange,} from '@/lib/utils';-import type {- PerformanceRow,- WorkspaceAnalyticsReport,-} from '@/types/analytics';+import type { PerformanceRow, WorkspaceAnalyticsReport } from '@/types/analytics';-import AccountIdentity from './AccountIdentity.vue';-import AnalyticsSection from './AnalyticsSection.vue';const props = defineProps<{rows: WorkspaceAnalyticsReport['performance'];@@ -48,8 +45,6 @@ const props = defineProps<{previousRange: WorkspaceAnalyticsReport['previous_range'];filtered?: boolean;}>();-const span = (range: { start: string; end: string }): string =>- `${date.formatDayMonthYear(range.start)} – ${date.formatDayMonthYear(range.end)}`;const { columns, toggleColumn } = usePerformanceColumns();type SortKey = PerformanceMetric | 'channel';type SortDirection = 'asc' | 'desc';@@ -61,13 +56,11 @@ const sortKey = computed<SortKey>(() =>? sortBy.value: columns.value[0],);-const channelName = (row: PerformanceRow): string =>- row.username ?? row.name ?? row.platform;const compareRows = (a: PerformanceRow, b: PerformanceRow): number => {const key = sortKey.value;if (key === 'channel') {- return channelName(a).localeCompare(channelName(b));+ return accountLabel(a).localeCompare(accountLabel(b));}const left = a[key].value;@@ -106,17 +99,14 @@ const ariaSort = (key: SortKey): 'ascending' | 'descending' | 'none' =>: 'descending': 'none';const display = (row: PerformanceRow, key: PerformanceMetric): string => {- const value = row[key].value;- return value === null- ? '—'- : key === 'engagement_rate'- ? formatPercent(value)- : formatNumberCompact(value);-};-const change = (row: PerformanceRow, key: PerformanceMetric): string => {- const value = row[key].change;- return value === null ? '—' : formatPercentChange(value);+ if (key === 'engagement_rate') {+ return formatPercent(row[key].value);+ }++ return formatNumberCompact(row[key].value);};+const change = (row: PerformanceRow, key: PerformanceMetric): string =>+ formatPercentChange(row[key].change);</script><template>@@ -124,12 +114,8 @@ const change = (row: PerformanceRow, key: PerformanceMetric): string => {:title="$t('analytics.dashboard.performance')":info="$t('analytics.insights.about.performance')"info-testid="analytics-performance-about"- :subtitle="- $t('analytics.ranges.compared_to', {- current: span(range),- previous: span(previousRange),- })- "+ :range="range"+ :previous-range="previousRange"subtitle-testid="analytics-performance-caption"flush>diff --git a/resources/js/components/analytics/workspace/PostsChart.vue b/resources/js/components/analytics/workspace/PostsChart.vueindex 34942821a..0a13c7598 100644--- a/resources/js/components/analytics/workspace/PostsChart.vue+++ b/resources/js/components/analytics/workspace/PostsChart.vue@@ -1,15 +1,26 @@<script setup lang="ts">import { computed, ref } from 'vue';+import ShareChartButton from '@/components/analytics/ShareChartButton.vue';+import AccountIdentity from '@/components/analytics/workspace/AccountIdentity.vue';+import AnalyticsModeToggle from '@/components/analytics/workspace/AnalyticsModeToggle.vue';+import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';+import PostsOverTimeStackedBarChart from '@/components/analytics/workspace/charts/PostsOverTimeStackedBarChart.vue';+import SocialAccountMetricBarChart from '@/components/analytics/workspace/charts/SocialAccountMetricBarChart.vue';import date from '@/date';+import {+ POSTS_ROWS,+ postsShareOption,+ shareRangeLabel,+} from '@/lib/insightsShare';+import type { ShareMetricOption } from '@/lib/shareCard';import { formatNumberCompact } from '@/lib/utils';-import type { WorkspaceAnalyticsReport } from '@/types/analytics';+import type {+ AccountMetricRow,+ PostsChartMode,+ WorkspaceAnalyticsReport,+} from '@/types/analytics';-import AccountIdentity from './AccountIdentity.vue';-import AnalyticsModeToggle from './AnalyticsModeToggle.vue';-import AnalyticsSection from './AnalyticsSection.vue';-import PostsOverTimeStackedBarChart from './charts/PostsOverTimeStackedBarChart.vue';-import SocialAccountMetricBarChart from './charts/SocialAccountMetricBarChart.vue';const props = defineProps<{posts: WorkspaceAnalyticsReport['posts'];@@ -19,7 +30,7 @@ const props = defineProps<{channelFiltered?: boolean;totalChannels?: number;}>();-const mode = ref<'bar' | 'stacked'>('bar');+const mode = ref<PostsChartMode>('bar');const buttons = [{ mode: 'bar', label: 'analytics.dashboard.chart_bar', test: 'posts-bar' },{@@ -35,10 +46,19 @@ const shownChannels = computed(() =>? props.posts.accounts.length: null,);-const rangeLabel = computed(- () =>- `${date.formatDayMonthYear(props.range.start)} – ${date.formatDayMonthYear(props.range.end)}`,+/** One bar per channel with the posts it sent. */+const barRows = computed((): AccountMetricRow[] =>+ props.posts.accounts.map((account) => ({+ account,+ value: POSTS_ROWS.value(account),+ })),);+const rangeLabel = computed(() => date.formatDayMonthYearRange(props.range));+/** The period the share card names, with the channels it counts when filtered. */+const shareRange = (): string =>+ shareRangeLabel(rangeLabel.value, shownChannels.value, props.totalChannels);+const buildShareOption = (): ShareMetricOption =>+ postsShareOption(props.posts, shareRange(), mode.value, props.colors);</script><template>@@ -64,6 +84,12 @@ const rangeLabel = computed(label="analytics.dashboard.posts_chart_mode":options="buttons"/>+ <ShareChartButton+ v-if="posts.accounts.length > 0"+ :range="shareRange()"+ :build="buildShareOption"+ test-id="share-posts"+ /></template><div@@ -80,17 +106,22 @@ const rangeLabel = computed(}}</div><div v-else class="min-w-0">+ <div class="mb-5 flex flex-wrap items-baseline gap-2">+ <span+ class="font-heading text-[28px] leading-[35px] font-medium text-foreground tabular-nums"+ data-testid="analytics-posts-total"+ >{{ formatNumberCompact(posts.total) }}</span+ >+ <span class="text-sm text-muted-foreground">{{+ $t('analytics.dashboard.total_posts')+ }}</span>+ </div><div class="min-w-0"><SocialAccountMetricBarChartv-if="mode === 'bar'"- :rows="- posts.accounts.map((account) => ({- account,- value: account.count,- }))- "+ :rows="barRows"+ :format-value="POSTS_ROWS.format":colors="colors"- :value-label="$t('analytics.dashboard.posts_sent_axis')"/><PostsOverTimeStackedBarChartv-else@@ -98,10 +129,11 @@ const rangeLabel = computed(:buckets="posts.buckets":resolution="posts.resolution":colors="colors"- :value-label="$t('analytics.dashboard.posts')"/></div><div+ v-if="mode === 'stacked'"+ data-testid="analytics-posts-legend"class="mt-5 grid gap-x-8 gap-y-1 border-t border-border pt-4 sm:grid-cols-2 xl:grid-cols-3"><divdiff --git a/resources/js/components/analytics/workspace/SummaryCards.vue b/resources/js/components/analytics/workspace/SummaryCards.vueindex f1d2551b7..c1b7b2057 100644--- a/resources/js/components/analytics/workspace/SummaryCards.vue+++ b/resources/js/components/analytics/workspace/SummaryCards.vue@@ -1,26 +1,44 @@<script setup lang="ts">+import { trans } from 'laravel-vue-i18n';import { computed } from 'vue';import MetricChange from '@/components/analytics/MetricChange.vue';+import ShareChartButton from '@/components/analytics/ShareChartButton.vue';+import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';+import InfoTip from '@/components/analytics/workspace/InfoTip.vue';+import date from '@/date';import {- formatNumberCompact,- formatPercent,- formatPercentChange,-} from '@/lib/utils';-import type { AnalyticsReport, SummaryMetric } from '@/types/analytics';+ countDelta,+ type MetricDelta,+ percentDelta,+} from '@/lib/channelMetrics';+import { summaryShareOption } from '@/lib/insightsShare';+import type { ShareMetricOption } from '@/lib/shareCard';+import { formatNumberCompact, formatPercent } from '@/lib/utils';+import type {+ AnalyticsReport,+ Comparison,+ SummaryMetric,+} from '@/types/analytics';-import AnalyticsSection from './AnalyticsSection.vue';-import InfoTip from './InfoTip.vue';const props = defineProps<{report: AnalyticsReport;availableMetrics?: SummaryMetric[];- subtitle?: string;subtitleTestid?: string;network?: string;+ channel?: string;}>();-const defaultCards = computed(() => [+/** A Summary card: which metric, its label key, its numbers and whether it reads as a percentage. */+type SummaryCard = {+ key: SummaryMetric;+ label: string;+ metric: Comparison;+ percent: boolean;+};++const defaultCards = computed((): SummaryCard[] => [{key: 'posts',label: 'analytics.dashboard.posts',@@ -53,15 +71,42 @@ const defaultCards = computed(() => [},]);+/** A card's change as the page and the share card label it: followers as a count, the rest as a percentage. */+const cardChange = (key: SummaryMetric, change: number | null): MetricDelta | null => {+ if (change === null) {+ return null;+ }++ if (key === 'followers') {+ return countDelta(change);+ }++ return percentDelta(change);+};++const listedCards = computed((): SummaryCard[] => {+ if (!props.availableMetrics) {+ return defaultCards.value;+ }++ return props.availableMetrics.map((key) => ({+ key,+ label: `analytics.channel.metrics.${key}.label`,+ metric: props.report.summary[key],+ percent: key === 'engagement_rate',+ }));+});+const cards = computed(() =>- props.availableMetrics- ? props.availableMetrics.map((key) => ({- key,- label: `analytics.channel.metrics.${key}.label`,- metric: props.report.summary[key],- percent: key === 'engagement_rate',- }))- : defaultCards.value,+ listedCards.value.map((card) => ({+ ...card,+ change: cardChange(card.key, card.metric.change),+ })),+);++/** Whether any card has a number; with none there is nothing to share. */+const hasAnyValue = computed((): boolean =>+ cards.value.some((card) => card.metric.value !== null),);const desktopColumns = computed((): string => {@@ -78,6 +123,19 @@ const desktopColumns = computed((): string => {return 'lg:grid-cols-5';});+/** On a phone two cards share a row; an odd count leaves the last one alone, so it takes the whole row. */+const spansPhoneRow = (index: number): boolean =>+ cards.value.length % 2 === 1 && index === cards.value.length - 1;++/** A half-width card on a phone stacks its change under the number; a card with the whole row keeps them side by side. */+const valueRowClass = (index: number): string => {+ if (spansPhoneRow(index)) {+ return 'flex flex-wrap items-center gap-x-3 gap-y-1';+ }++ return 'flex flex-col items-start gap-1 md:flex-row md:flex-wrap md:items-center md:gap-x-3';+};+const aboutKey = (key: string): string =>key === 'reactions' && props.network? 'analytics.channel.metrics.reactions.about_network'@@ -86,38 +144,58 @@ const aboutKey = (key: string): string =>const testId = (key: string): string =>props.availableMetrics ? `insights-card-${key}` : `analytics-summary-${key}`;-const display = (value: number | null, percent: boolean): string =>- value === null- ? '—'- : percent- ? formatPercent(value)- : formatNumberCompact(value);--const changeLabel = (key: string, change: number | null): string | null => {- if (change === null) return null;- return key === 'followers'- ? `${change > 0 ? '+' : ''}${formatNumberCompact(change)}`- : formatPercentChange(change);+const display = (value: number | null, percent: boolean): string => {+ if (percent) {+ return formatPercent(value);+ }++ return formatNumberCompact(value);};++const rangeLabel = computed(() =>+ date.formatDayMonthYearRange(props.report.range),+);+const buildShareOption = (): ShareMetricOption =>+ summaryShareOption(+ cards.value.map((card) => ({+ label: trans(card.label),+ figure: display(card.metric.value, card.percent),+ missing: card.metric.value === null,+ change: card.change,+ })),+ props.channel ?? null,+ rangeLabel.value,+ );</script><template><AnalyticsSection:title="$t('analytics.dashboard.summary')"- :subtitle="subtitle"+ :range="report.range"+ :previous-range="report.previous_range":subtitle-testid="subtitleTestid"flush>+ <template #actions>+ <ShareChartButton+ v-if="hasAnyValue"+ :subject="channel"+ :range="rangeLabel"+ :build="buildShareOption"+ test-id="share-summary"+ />+ </template><divclass="grid grid-cols-2 border-t border-border md:grid-cols-3":class="desktopColumns"data-testid="analytics-summary"><div- v-for="card in cards"+ v-for="(card, index) in cards":key="card.key":data-testid="testId(card.key)"class="flex min-w-0 flex-col gap-2 px-4 py-4 shadow-[1px_0_0_var(--border),0_1px_0_var(--border)] sm:px-5"+ :class="{ 'max-md:col-span-2': spansPhoneRow(index) }"><div class="flex min-h-6 items-center gap-0.5"><p class="truncate text-sm text-muted-foreground">@@ -128,24 +206,20 @@ const changeLabel = (key: string, change: number | null): string | null => {:test-id="`${testId(card.key)}-about`"/></div>- <div class="flex flex-wrap items-center gap-x-3 gap-y-1">+ <div :class="valueRowClass(index)"><spanclass="font-heading text-2xl leading-8 font-medium text-foreground tabular-nums"+ :data-testid="`${testId(card.key)}-value`">{{ display(card.metric.value, card.percent) }}</span><MetricChange- v-if="changeLabel(card.key, card.metric.change)"+ v-if="card.change":data-testid="`${testId(card.key)}-change`"- :change="card.metric.change!"- :label="changeLabel(card.key, card.metric.change)!"+ :change="card.change.value"+ :label="card.change.label"/></div></div></div>- <p- class="border-t border-border px-4 py-3 text-xs text-muted-foreground sm:px-5"- >- {{ $t('analytics.dashboard.latest_snapshot_hint') }}- </p></AnalyticsSection></template>diff --git a/resources/js/components/analytics/workspace/TopPosts.vue b/resources/js/components/analytics/workspace/TopPosts.vueindex 12b4c28ca..f66b49a37 100644--- a/resources/js/components/analytics/workspace/TopPosts.vue+++ b/resources/js/components/analytics/workspace/TopPosts.vue@@ -1,6 +1,10 @@<script setup lang="ts">import { computed, ref } from 'vue';+import RankBadge from '@/components/analytics/RankBadge.vue';+import AccountIdentity from '@/components/analytics/workspace/AccountIdentity.vue';+import AnalyticsModeToggle from '@/components/analytics/workspace/AnalyticsModeToggle.vue';+import AnalyticsSection from '@/components/analytics/workspace/AnalyticsSection.vue';import AppLogo from '@/components/AppLogo.vue';import PlatformBrandIcon from '@/components/PlatformBrandIcon.vue';import PostDetailsDialog from '@/components/publish/PostDetailsDialog.vue';@@ -14,9 +18,6 @@ import { videoFrameUrl } from '@/lib/videoFrame';import type { TopPost, WorkspaceAnalyticsReport } from '@/types/analytics';import { Platform } from '@/types/platform';-import AccountIdentity from './AccountIdentity.vue';-import AnalyticsModeToggle from './AnalyticsModeToggle.vue';-import AnalyticsSection from './AnalyticsSection.vue';const props = defineProps<{topPosts: WorkspaceAnalyticsReport['top_posts'];@@ -104,7 +105,7 @@ const thumbnailFor = (post: TopPost): string | null => {class="grid border-t border-border sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5"><article- v-for="(post, index) in posts"+ v-for="post in posts":key="post.id"class="group relative flex min-w-0 flex-col gap-3 p-4 shadow-[1px_0_0_var(--border),0_1px_0_var(--border)] transition-colors duration-150 has-[button:hover]:bg-muted/60 has-[button:focus-visible]:bg-muted/60 sm:px-5"data-testid="analytics-top-post"@@ -120,11 +121,10 @@ const thumbnailFor = (post: TopPost): string | null => {}}</span></div><div class="flex shrink-0 flex-col items-end justify-between gap-1">- <span- class="inline-flex h-6 min-w-7 items-center justify-center rounded-md bg-primary-selected px-1.5 text-xs font-semibold text-primary-text tabular-nums"+ <RankBadge+ :rank="post.rank":data-testid="`analytics-top-post-rank-${post.id}`"- >#{{ index + 1 }}</span- >+ /><spanclass="text-xs leading-4 whitespace-nowrap text-muted-foreground":data-testid="`analytics-top-post-date-${post.id}`"diff --git a/resources/js/components/analytics/workspace/charts/AxisChannelRow.vue b/resources/js/components/analytics/workspace/charts/AxisChannelRow.vuenew file mode 100644index 000000000..e19fbd7de--- /dev/null+++ b/resources/js/components/analytics/workspace/charts/AxisChannelRow.vue@@ -0,0 +1,39 @@+<script setup lang="ts">+import ChannelAvatar from '@/components/ChannelAvatar.vue';+import { accountLabel } from '@/lib/analyticsAccounts';+import type { AccountIdentityData } from '@/types/analytics';++defineProps<{+ account: AccountIdentityData;+ /** The channel's number as the chart prints it. */+ value: string;+}>();+</script>++<template>+ <div class="flex h-full items-center gap-2">+ <span+ class="min-w-0 flex-1 truncate text-xs text-muted-foreground max-sm:hidden"+ data-testid="analytics-account-name"+ >+ {{ accountLabel(account) }}+ </span>+ <span+ class="ms-auto shrink-0 text-sm font-medium text-foreground tabular-nums"+ data-testid="analytics-account-value"+ >+ {{ value }}+ </span>+ <ChannelAvatar+ class="ms-1"+ :platform="account.platform"+ :src="account.avatar_url"+ :name="accountLabel(account)"+ :size="24"+ ring="card"+ :status="account.status ?? null"+ :account-id="account.social_account_key"+ :verified="account.verified_badge ?? null"+ />+ </div>+</template>diff --git a/resources/js/components/analytics/workspace/charts/FollowerHistoryLineChart.vue b/resources/js/components/analytics/workspace/charts/FollowerHistoryLineChart.vueindex c3dde5ce8..e70ea4558 100644--- a/resources/js/components/analytics/workspace/charts/FollowerHistoryLineChart.vue+++ b/resources/js/components/analytics/workspace/charts/FollowerHistoryLineChart.vue@@ -1,25 +1,40 @@<script setup lang="ts">-import { VisAxis, VisLine, VisScatter, VisXYContainer } from '@unovis/vue';-import { computed } from 'vue';+import {+ VisAxis,+ VisAxisSelectors,+ VisLine,+ VisLineSelectors,+ VisScatter,+ VisScatterSelectors,+ VisXYContainer,+} from '@unovis/vue';+import { computed, ref, useTemplateRef } from 'vue';+import LineEndLabel from '@/components/analytics/workspace/charts/LineEndLabel.vue';+import {+ formatCountTick,+ socialAccountChartConfig,+} from '@/components/analytics/workspace/charts/socialAccountChart';import {ChartContainer,ChartCrosshair,ChartTooltip,ChartTooltipContent,componentToString,+ numericTick,} from '@/components/ui/chart';+import { useChartAppContext } from '@/composables/analytics/useChartAppContext';+import { useBelowBreakpoint } from '@/composables/useBreakpoint';+import { useCanHover } from '@/composables/useCanHover';import date from '@/date';import { accountColor } from '@/lib/analyticsColors';+import { spreadLabels } from '@/lib/labelLayout';+import { formatNumberCompact } from '@/lib/utils';import type {FollowerAccount,WorkspaceAnalyticsReport,} from '@/types/analytics';-import {- formatCountTick,- socialAccountChartConfig,-} from './socialAccountChart';type ChartPoint = {date: string;@@ -61,38 +76,222 @@ const valueAccessor =const value = point[`account_${index}`];return typeof value === 'number' ? value : undefined;};-const formatDate = (tick: number | Date): string => {- const index = typeof tick === 'number' ? Math.round(tick) : 0;- const day = chartData.value[index]?.date;+/** One accessor per channel, kept while the channels stay, so unovis never sees a new line to redraw. */+const valueAccessors = computed(() =>+ props.accounts.map((_, index) => valueAccessor(index)),+);+const formatDate = numericTick((tick): string => {+ const day = chartData.value[Math.round(tick)]?.date;- return day ? date.formatMonthDay(day) : '';-};+ if (!day) {+ return '';+ }++ return date.formatMonthDay(day);+});+const appContext = useChartAppContext();const tooltipTemplate = computed(() =>- componentToString(chartConfig.value, ChartTooltipContent, {- labelFormatter: formatDate,- }),+ componentToString(+ chartConfig.value,+ ChartTooltipContent,+ { labelFormatter: formatDate },+ appContext,+ ),);const lineColor = (index: number): string =>props.colors[props.accounts[index]?.social_account_key ?? ''] ??accountColor(index);++/** Room on the right for each line's avatar and latest number; narrower on a phone. */+const belowSm = useBelowBreakpoint('sm');+const RAIL_WIDTH = { phone: 92, wide: 112 };+const railWidth = computed((): number => {+ if (belowSm.value) {+ return RAIL_WIDTH.phone;+ }++ return RAIL_WIDTH.wide;+});+/** Room over the plot for the top line-end label, and under it for the dates. */+const PLOT_PADDING = { top: 16, bottom: 8 };+const chartPadding = computed(() => ({+ top: PLOT_PADDING.top,+ right: railWidth.value,+ bottom: PLOT_PADDING.bottom,+ left: 0,+}));+/** From the end of a line to its label, where a leader runs when the label had to move. */+const LEADER_LENGTH = 32;+/** Where a leader starts after the line's end, how far it stops short of the avatar, and the offset from which a label gets one. */+const LEADER = { inset: 4, tip: 2, from: 1 };+/** The tallest a label is; labels closer than this are spread apart. */+const LABEL_HEIGHT = 24;++type LineEnd = {+ account: FollowerAccount;+ index: number;+ value: string;+ /** Where the line ends and where its label sits, in the frame's pixels. */+ lineY: number;+ labelY: number;+};++const frame = useTemplateRef<HTMLDivElement>('frame');+const lineEnds = ref<LineEnd[]>([]);+const lineEndX = ref(0);+/** The line whose label the pointer is on; the others fade. */+const focusedLine = ref<number | null>(null);++const canHover = useCanHover();++/** Fades the other lines while a label is pointed at; a tap on a touch screen never leaves, so it fades nothing. */+const focusLine = (index: number): void => {+ if (!canHover.value) {+ return;+ }++ focusedLine.value = index;+};++const clearFocus = (): void => {+ focusedLine.value = null;+};++/** Whether a line fades while another channel's label is pointed at. */+const isDimmed = (index: number): boolean =>+ focusedLine.value !== null && focusedLine.value !== index;++/** The attributes unovis sets on a component's elements, by selector. */+type ChartAttributes = Record<string, Record<string, string>>;++const lineAttributes = (index: number): ChartAttributes => ({+ [VisLineSelectors.line]: { 'data-dimmed': String(isDimmed(index)) },+});++const pointAttributes = (index: number): ChartAttributes => ({+ [VisScatterSelectors.point]: { 'data-dimmed': String(isDimmed(index)) },+});++const valueTickAttributes = {+ [VisAxisSelectors.tick]: {+ 'data-value-tick': (tick: number): string => String(tick),+ },+};++/** Each channel's latest known count, the value its line ends on. */+const latestValue = (index: number): number | undefined => {+ const latest = chartData.value[chartData.value.length - 1];++ if (!latest) {+ return undefined;+ }++ return valueAccessor(index)(latest);+};++/** Maps a count to its height in the frame, read off two of the value axis' ticks. */+const valueToY = (+ svg: SVGSVGElement,+ top: number,+): ((value: number) => number) | null => {+ const ticks = [...svg.querySelectorAll<SVGGElement>('g[data-value-tick]')]+ .map((tick) => ({+ value: Number(tick.getAttribute('data-value-tick')),+ y: tick.getCTM()?.f,+ }))+ .filter((tick): tick is { value: number; y: number } => tick.y !== undefined);+ const [low, high] = [ticks[0], ticks[ticks.length - 1]];++ if (!low || !high || low.value === high.value) {+ return null;+ }++ return (value) => top + low.y + ((value - low.value) * (high.y - low.y)) / (high.value - low.value);+};++const placeLineEnds = (svg: SVGSVGElement): void => {+ const box = frame.value?.getBoundingClientRect();++ if (!box) {+ return;+ }++ const svgBox = svg.getBoundingClientRect();+ const top = svgBox.top - box.top;+ const toY = valueToY(svg, top);++ if (!toY) {+ lineEnds.value = [];+ return;+ }++ lineEndX.value = svgBox.left - box.left + svgBox.width - railWidth.value;+ const ends = props.accounts.flatMap((account, index) => {+ const value = latestValue(index);++ if (value === undefined) {+ return [];+ }++ return [{ account, index, value: formatNumberCompact(value), lineY: toY(value), labelY: 0 }];+ });+ const labels = spreadLabels(+ ends.map((end) => end.lineY),+ { gap: LABEL_HEIGHT, top, bottom: Math.min(toY(0), top + svgBox.height) },+ );++ const placed = ends.map((end, position) => ({ ...end, labelY: labels[position] }));++ if (!sameLineEnds(placed, lineEnds.value)) {+ lineEnds.value = placed;+ }+};++/** Whether two placements put the same labels in the same places, so an unchanged render does not redraw every line. */+const sameLineEnds = (next: LineEnd[], current: LineEnd[]): boolean =>+ next.length === current.length &&+ next.every(+ (end, position) =>+ end.index === current[position].index &&+ end.value === current[position].value &&+ end.lineY === current[position].lineY &&+ end.labelY === current[position].labelY,+ );++/** A leader's three points: out from the line's end, along it, then up or down to its label. */+const leaderPoints = (end: LineEnd): string => {+ const start = lineEndX.value + LEADER.inset;+ const bend = lineEndX.value + LEADER_LENGTH / 2;+ const tip = lineEndX.value + LEADER_LENGTH - LEADER.tip;++ return `${start},${end.lineY} ${bend},${end.lineY} ${tip},${end.labelY}`;+};++/** A leader only where a label had to move away from its line. */+const movedEnds = computed(() =>+ lineEnds.value.filter((end) => Math.abs(end.labelY - end.lineY) > LEADER.from),+);const crosshairColor = (_point: ChartPoint, index: number): string =>lineColor(Math.floor(index / 2));</script><template><div+ ref="frame"+ class="relative"role="img":aria-label="$t('analytics.dashboard.followers_line_description')"><ChartContainer:config="chartConfig"cursor- class="h-72 w-full sm:h-80"+ class="h-72 w-full sm:h-80 [&_[data-dimmed=true]]:opacity-20 [&_[data-dimmed]]:transition-opacity"data-testid="followers-unovis-chart"><VisXYContainer:data="chartData"- :padding="{ top: 16, right: 12, bottom: 8, left: 0 }"+ :padding="chartPadding"+ :on-render-complete="placeLineEnds"><templatev-for="(account, index) in accounts"@@ -100,16 +299,18 @@ const crosshairColor = (_point: ChartPoint, index: number): string =>><VisLine:x="xAccessor"- :y="valueAccessor(index)"+ :y="valueAccessors[index]":color="lineColor(index)":line-width="2"curve-type="monotoneX"+ :attributes="lineAttributes(index)"/><VisScatter:x="xAccessor"- :y="valueAccessor(index)"+ :y="valueAccessors[index]":color="lineColor(index)":size="4"+ :attributes="pointAttributes(index)"/></template><VisAxis@@ -127,6 +328,8 @@ const crosshairColor = (_point: ChartPoint, index: number): string =>:grid-line="true":domain-line="false":tick-line="false"+ :duration="0"+ :attributes="valueTickAttributes"/><ChartCrosshair:template="tooltipTemplate"@@ -138,5 +341,33 @@ const crosshairColor = (_point: ChartPoint, index: number): string =><ChartTooltip /></VisXYContainer></ChartContainer>+ <svg+ class="pointer-events-none absolute inset-0 size-full overflow-visible"+ aria-hidden="true"+ >+ <polyline+ v-for="end in movedEnds"+ :key="end.account.social_account_key"+ :points="leaderPoints(end)"+ fill="none"+ :stroke="lineColor(end.index)"+ stroke-width="1.5"+ stroke-linejoin="round"+ class="transition-opacity data-[dimmed=true]:opacity-20"+ :data-dimmed="isDimmed(end.index)"+ />+ </svg>+ <div+ v-for="end in lineEnds"+ :key="end.account.social_account_key"+ class="absolute z-10 -translate-y-1/2"+ :style="{ left: `${lineEndX + LEADER_LENGTH}px`, top: `${end.labelY}px` }"+ data-testid="followers-line-end"+ :data-account="end.account.social_account_key"+ @mouseenter="focusLine(end.index)"+ @mouseleave="clearFocus"+ >+ <LineEndLabel :account="end.account" :value="end.value" />+ </div></div></template>diff --git a/resources/js/components/analytics/workspace/charts/LineEndLabel.vue b/resources/js/components/analytics/workspace/charts/LineEndLabel.vuenew file mode 100644index 000000000..bb3c15034--- /dev/null+++ b/resources/js/components/analytics/workspace/charts/LineEndLabel.vue@@ -0,0 +1,32 @@+<script setup lang="ts">+import ChannelAvatar from '@/components/ChannelAvatar.vue';+import { accountLabel } from '@/lib/analyticsAccounts';+import type { AccountIdentityData } from '@/types/analytics';++defineProps<{+ account: AccountIdentityData;+ /** The channel's latest number as the chart prints it. */+ value: string;+}>();+</script>++<template>+ <div class="flex items-center gap-1.5">+ <ChannelAvatar+ :platform="account.platform"+ :src="account.avatar_url"+ :name="accountLabel(account)"+ :size="20"+ ring="card"+ :status="account.status ?? null"+ :account-id="account.social_account_key"+ :verified="account.verified_badge ?? null"+ />+ <span+ class="text-xs font-medium text-foreground tabular-nums"+ data-testid="analytics-line-end-value"+ >+ {{ value }}+ </span>+ </div>+</template>diff --git a/resources/js/components/analytics/workspace/charts/PostsOverTimeStackedBarChart.vue b/resources/js/components/analytics/workspace/charts/PostsOverTimeStackedBarChart.vueindex 8711799ff..b028d36b7 100644--- a/resources/js/components/analytics/workspace/charts/PostsOverTimeStackedBarChart.vue+++ b/resources/js/components/analytics/workspace/charts/PostsOverTimeStackedBarChart.vue@@ -5,23 +5,31 @@ import {VisStackedBarSelectors,VisXYContainer,} from '@unovis/vue';+import { trans } from 'laravel-vue-i18n';import { computed } from 'vue';+import {+ formatCountTick,+ socialAccountChartConfig,+} from '@/components/analytics/workspace/charts/socialAccountChart';import {ChartContainer,ChartTooltip,ChartTooltipContent,+ type ChartTooltipDetail,componentToString,+ numericTick,} from '@/components/ui/chart';-import date from '@/date';-import dayjs from '@/dayjs';+import { useChartAppContext } from '@/composables/analytics/useChartAppContext';import { accountColor } from '@/lib/analyticsColors';-import type { PostAccount, PostBucket } from '@/types/analytics';+import { bucketRangeLabel } from '@/lib/channelMetrics';+import { formatFullNumber } from '@/lib/utils';+import type {+ BucketResolution,+ PostAccount,+ PostBucket,+} from '@/types/analytics';-import {- formatCountTick,- socialAccountChartConfig,-} from './socialAccountChart';type ChartPoint = {index: number;@@ -32,24 +40,13 @@ type ChartPoint = {const props = defineProps<{accounts: PostAccount[];buckets: PostBucket[];- resolution: string;+ resolution: BucketResolution;colors: Record<string, string>;- valueLabel?: string;}>();-const bucketLabel = (bucket: PostBucket): string => {- const start = dayjs(bucket.start);-- if (props.resolution === 'monthly')- return date.formatMonthYear(start.month() + 1, start.year());- if (bucket.start === bucket.end) return date.formatMonthDay(bucket.start);-- return `${date.formatMonthDay(bucket.start)} – ${date.formatMonthDay(bucket.end)}`;-};-const chartData = computed<ChartPoint[]>(() =>props.buckets.map((bucket, index) => {- const point: ChartPoint = { index, label: bucketLabel(bucket) };+ const point: ChartPoint = { index, label: bucketRangeLabel(bucket, props.resolution) };props.accounts.forEach((account, accountIndex) => {point[`account_${accountIndex}`] =@@ -76,15 +73,31 @@ const barColors = computed(() =>props.colors[account.social_account_key] ?? accountColor(index),),);-const formatBucket = (tick: number | Date): string => {- const index = typeof tick === 'number' ? Math.round(tick) : 0;- return chartData.value[index]?.label ?? '';-};+const formatBucket = numericTick(+ (tick): string => chartData.value[Math.round(tick)]?.label ?? '',+);+/** The posts of a column across every channel, as the report counts them. */+const bucketTotal = numericTick((tick): ChartTooltipDetail | null => {+ const bucket = props.buckets[Math.round(tick)];++ if (!bucket) {+ return null;+ }++ return {+ label: trans('analytics.dashboard.total_posts'),+ value: formatFullNumber(bucket.total),+ };+});const ticks = computed(() => props.buckets.map((_, index) => index));+const appContext = useChartAppContext();const tooltipTemplate = computed(() =>- componentToString(chartConfig.value, ChartTooltipContent, {- labelFormatter: formatBucket,- }),+ componentToString(+ chartConfig.value,+ ChartTooltipContent,+ { labelFormatter: formatBucket, totalFormatter: bucketTotal },+ appContext,+ ),);const tooltipTriggers = computed(() => ({[VisStackedBarSelectors.bar]: (bar: {@@ -131,9 +144,6 @@ const barAttributes = {type="y":tick-format="formatCountTick":num-ticks="5"- :label="valueLabel"- label-font-size="11px"- label-color="var(--muted-foreground)":grid-line="true":domain-line="false":tick-line="false"diff --git a/resources/js/components/analytics/workspace/charts/SocialAccountMetricBarChart.vue b/resources/js/components/analytics/workspace/charts/SocialAccountMetricBarChart.vueindex 128c5b56b..b47a678b4 100644--- a/resources/js/components/analytics/workspace/charts/SocialAccountMetricBarChart.vue+++ b/resources/js/components/analytics/workspace/charts/SocialAccountMetricBarChart.vue@@ -6,46 +6,41 @@ import {VisStackedBarSelectors,VisXYContainer,} from '@unovis/vue';-import { computed, getCurrentInstance, h, onBeforeUnmount, render } from 'vue';+import { computed, h, onBeforeUnmount, render, useTemplateRef } from 'vue';-import ChannelAvatar from '@/components/ChannelAvatar.vue';+import AxisChannelRow from '@/components/analytics/workspace/charts/AxisChannelRow.vue';+import {+ formatCountTick,+ socialAccountChartConfig,+} from '@/components/analytics/workspace/charts/socialAccountChart';import {ChartContainer,ChartTooltip,ChartTooltipContent,+ type ChartTooltipDetail,componentToString,} from '@/components/ui/chart';-import { getPlatformLabel } from '@/composables/usePlatformLogo';+import { useChartAppContext } from '@/composables/analytics/useChartAppContext';+import { useBelowBreakpoint } from '@/composables/useBreakpoint';import { accountColor } from '@/lib/analyticsColors';-import type { AccountIdentityData } from '@/types/analytics';--import {- formatCountTick,- socialAccountChartConfig,-} from './socialAccountChart';--const props = defineProps<{- rows: {- account: AccountIdentityData;- value: number | null;- gained?: number | null;- }[];- colors: Record<string, string>;- valueLabel?: string;- detail?: (index: number) => string | null;-}>();--type BarPoint = { index: number; value: number; base: number; gained: number };-const split = computed(() =>- props.rows.some((row) => row.gained !== undefined),+import { formatNumberCompact } from '@/lib/utils';+import type { AccountMetricRow } from '@/types/analytics';+++const props = withDefaults(+ defineProps<{+ rows: AccountMetricRow[];+ colors: Record<string, string>;+ detail?: (index: number) => ChartTooltipDetail[];+ /** How each channel's number reads in the column before its bar. */+ formatValue?: (value: number | null) => string;+ }>(),+ { detail: undefined, formatValue: formatNumberCompact },);-const chartData = computed<BarPoint[]>(() =>- props.rows.map((row, index) => {- const value = row.value ?? 0;- const gained = Math.min(Math.max(row.gained ?? 0, 0), value);- return { index, value, base: value - gained, gained };- }),+type BarPoint = { index: number; value: number };+const chartData = computed<BarPoint[]>(() =>+ props.rows.map((row, index) => ({ index, value: row.value ?? 0 })),);const chartConfig = computed(() =>socialAccountChartConfig(@@ -58,35 +53,24 @@ const chartHeight = computed();const indexAccessor = (point: BarPoint): number => point.index;const valueAccessor = (point: BarPoint): number => point.value;-const splitAccessors = [- (point: BarPoint): number => point.base,- (point: BarPoint): number => point.gained,-];const rowColor = (point: BarPoint): string => {const key = props.rows[point.index]?.account.social_account_key;return (key && props.colors[key]) || accountColor(point.index);};-const colorAccessor = (point: BarPoint, stack: number): string =>- split.value && stack === 0 && point.gained > 0- ? `color-mix(in srgb, ${rowColor(point)} 40%, var(--card))`- : rowColor(point);-const formatAccount = (tick: number | Date): string => {- const index = typeof tick === 'number' ? Math.round(tick) : 0;- const account = props.rows[index]?.account;- if (!account) return '';-- const label = account.username- ? `@${account.username}`- : account.name || getPlatformLabel(account.platform);- return label.length > 12 ? `${label.slice(0, 11)}…` : label;-};+const rowAt = (index: number): AccountMetricRow | undefined =>+ props.rows[Math.round(index)];+/** The axis draws no text: each row's channel and number are laid over it as HTML. */+const blankTick = (): string => '';const categoryTicks = computed(() => props.rows.map((_, index) => index));-const detailFormatter = (key: string): string | null =>- props.detail?.(Number(key.replace('account_', ''))) ?? null;+const detailFormatter = (key: string): ChartTooltipDetail[] =>+ props.detail?.(Number(key.replace('account_', ''))) ?? [];const tooltipTemplate = computed(() =>- componentToString(chartConfig.value, ChartTooltipContent, {- detailFormatter,- }),+ componentToString(+ chartConfig.value,+ ChartTooltipContent,+ { detailFormatter },+ appContext,+ ),);const tooltipTriggers = computed(() => ({[VisStackedBarSelectors.bar]: (bar: {@@ -103,72 +87,101 @@ const tickAttributes = {'data-account-tick': (tick: number): string => String(Math.round(tick)),},};-const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';const AVATAR_SIZE = 24;-const AVATAR_OVERHANG = 4;-const AVATAR_GAP = 8;-const appContext = getCurrentInstance()?.appContext ?? null;+/** Between a row's number and the start of its bar. */+const COLUMN_GAP = 12;+/** Name, number and avatar before the bars; a phone drops the name so the bars keep the room. */+const belowSm = useBelowBreakpoint('sm');+const COLUMN_WIDTH = { phone: 80, wide: 240 };+const columnWidth = computed((): number => {+ if (belowSm.value) {+ return COLUMN_WIDTH.phone;+ }++ return COLUMN_WIDTH.wide;+});+/** Room over the first bar and after the longest one. */+const PLOT_PADDING = { top: 12, right: 16 };+/** The bars start after the rows' column; the axis itself draws no text to make room for. */+const chartPadding = computed(() => ({+ top: PLOT_PADDING.top,+ right: PLOT_PADDING.right,+ bottom: 0,+ left: columnWidth.value + COLUMN_GAP,+}));+const appContext = useChartAppContext();const avatarHosts: HTMLElement[] = [];--const accountLabel = (account: AccountIdentityData): string =>- account.username- ? `@${account.username}`- : account.name || getPlatformLabel(account.platform);+const avatarLayer = useTemplateRef<HTMLDivElement>('avatarLayer');const unmountAvatars = (): void => {- avatarHosts.splice(0).forEach((host) => render(null, host));+ avatarHosts.splice(0).forEach((host) => {+ render(null, host);+ host.remove();+ });};-const buildAxisChannel = (account: AccountIdentityData): SVGElement => {- const box = AVATAR_SIZE + AVATAR_OVERHANG * 2;- const frame = document.createElementNS(SVG_NAMESPACE, 'foreignObject');- frame.setAttribute('x', String(-AVATAR_SIZE - AVATAR_GAP - AVATAR_OVERHANG));- frame.setAttribute('y', String(-AVATAR_SIZE / 2 - AVATAR_OVERHANG));- frame.setAttribute('width', String(box));- frame.setAttribute('height', String(box));- frame.setAttribute('data-account-logo', '');- frame.setAttribute('data-testid', 'analytics-axis-channel');- frame.setAttribute('data-platform', account.platform);- frame.style.overflow = 'visible';+/**+ * The row's channel and number, as HTML laid over the chart at the tick's+ * position. Not a `<foreignObject>` inside the SVG: WebKit (every browser on+ * iOS) ignores the tick's transform there and draws every row at the chart's+ * corner.+ */+const placeAxisChannel = (+ layer: HTMLDivElement,+ svgOffset: { x: number; y: number },+ tick: SVGGElement,+ row: AccountMetricRow,+): void => {+ const origin = tick.getCTM();++ if (!origin) {+ return;+ }const host = document.createElement('div');- host.style.padding = `${AVATAR_OVERHANG}px`;- host.style.lineHeight = '0';-- const avatar = h(ChannelAvatar, {- platform: account.platform,- src: account.avatar_url,- name: accountLabel(account),- size: AVATAR_SIZE,- ring: 'card',- status: account.status ?? null,- accountId: account.social_account_key,- verified: account.verified_badge ?? null,- reserveSpace: false,+ const width = columnWidth.value;++ host.className = 'absolute';+ host.dataset.testid = 'analytics-axis-channel';+ host.dataset.platform = row.account.platform;+ host.style.left = `${svgOffset.x}px`;+ host.style.top = `${svgOffset.y + origin.f - AVATAR_SIZE / 2}px`;+ host.style.width = `${width}px`;+ host.style.height = `${AVATAR_SIZE}px`;++ const content = h(AxisChannelRow, {+ account: row.account,+ value: props.formatValue(row.value),});- avatar.appContext = appContext;- render(avatar, host);+ content.appContext = appContext;+ render(content, host);avatarHosts.push(host);- frame.appendChild(host);-- return frame;+ layer.appendChild(host);};const decorateTicks = (svg: SVGSVGElement): void => {unmountAvatars();- svg.querySelectorAll('[data-account-logo]').forEach((logo) =>- logo.remove(),- );++ const layer = avatarLayer.value;++ if (!layer) {+ return;+ }++ const svgBox = svg.getBoundingClientRect();+ const layerBox = layer.getBoundingClientRect();+ const svgOffset = {+ x: svgBox.left - layerBox.left,+ y: svgBox.top - layerBox.top,+ };+svg.querySelectorAll<SVGGElement>('g[data-account-tick]').forEach((tick) => {- const index = Number(tick.getAttribute('data-account-tick'));- const account = props.rows[index]?.account;+ const row = rowAt(Number(tick.getAttribute('data-account-tick')));- if (!account) {- return;+ if (row) {+ placeAxisChannel(layer, svgOffset, tick, row);}-- tick.appendChild(buildAxisChannel(account));},);};@@ -182,20 +195,24 @@ const barAttributes = {<template><ChartContainer:config="chartConfig"- class="w-full"+ class="relative w-full":style="{ height: chartHeight }"data-testid="accounts-unovis-bar-chart">+ <div+ ref="avatarLayer"+ class="pointer-events-none absolute inset-0 z-10"+ /><VisXYContainer:data="chartData"y-direction="south"- :padding="{ top: 12, right: 16, bottom: 0, left: 0 }"+ :padding="chartPadding":on-render-complete="decorateTicks"><VisStackedBar:x="indexAccessor"- :y="split ? splitAccessors : valueAccessor"- :color="colorAccessor"+ :y="valueAccessor"+ :color="rowColor"orientation="horizontal":rounded-corners="4":bar-padding="0.4"@@ -206,18 +223,15 @@ const barAttributes = {type="x":tick-format="formatCountTick":num-ticks="5"- :label="valueLabel"- label-font-size="11px"- label-color="var(--muted-foreground)":grid-line="true":domain-line="false":tick-line="false"/><VisAxistype="y"- :tick-format="formatAccount"+ :tick-format="blankTick":tick-values="categoryTicks"- :tick-padding="AVATAR_SIZE + AVATAR_GAP + 6"+ :duration="0":attributes="tickAttributes":grid-line="false":domain-line="false"diff --git a/resources/js/components/analytics/workspace/charts/socialAccountChart.ts b/resources/js/components/analytics/workspace/charts/socialAccountChart.tsindex f77369ae0..c02cfdbe9 100644--- a/resources/js/components/analytics/workspace/charts/socialAccountChart.ts+++ b/resources/js/components/analytics/workspace/charts/socialAccountChart.ts@@ -1,7 +1,7 @@-import type { ChartConfig } from '@/components/ui/chart';-import { getPlatformLabel } from '@/composables/usePlatformLogo';+import { type ChartConfig, numericTick } from '@/components/ui/chart';+import { accountLabel } from '@/lib/analyticsAccounts';import { accountColor } from '@/lib/analyticsColors';-import { formatNumberCompact } from '@/lib/utils';+import { distinctCountLabels } from '@/lib/utils';import type { AccountIdentityData } from '@/types/analytics';export const socialAccountChartConfig = (@@ -10,9 +10,7 @@ export const socialAccountChartConfig = (): ChartConfig =>Object.fromEntries(accounts.map((account, index) => {- const label = account.username- ? `@${account.username}`- : account.name || getPlatformLabel(account.platform);+ const label = accountLabel(account);return [`account_${index}`,@@ -25,11 +23,14 @@ export const socialAccountChartConfig = (platform: account.platform,name: label,src: account.avatar_url,+ verified: account.verified_badge ?? null,},},];}),);-export const formatCountTick = (tick: number | Date): string =>- typeof tick === 'number' ? formatNumberCompact(tick) : '';+/** A count axis' tick, compact but never like its neighbours: close values (9,990 to 10,010) keep the decimals that tell them apart. */+export const formatCountTick = numericTick(+ (_tick, index, ticks): string => distinctCountLabels(ticks)[index] ?? '',+);diff --git a/resources/js/components/auth/SocialLogin.vue b/resources/js/components/auth/SocialLogin.vueindex 76914dfa7..329f2b111 100644--- a/resources/js/components/auth/SocialLogin.vue+++ b/resources/js/components/auth/SocialLogin.vue@@ -1,5 +1,7 @@<script setup lang="ts">import { usePage } from '@inertiajs/vue3';+import Github from '@thesvg/vue/github';+import Google from '@thesvg/vue/google';import { computed } from 'vue';import { Button } from '@/components/ui/button';@@ -51,11 +53,7 @@ const githubUrl = computed(() => githubRedirect.url({ query: query.value }));as="a":href="googleUrl">- <img- src="/images/social/google.svg"- alt="Google"- class="size-4"- />+ <Google aria-hidden="true" class="size-4" />{{mode === 'login'? $t('auth.google_login')@@ -71,10 +69,9 @@ const githubUrl = computed(() => githubRedirect.url({ query: query.value }));as="a":href="githubUrl">- <img- src="/images/social/github.svg"- alt="GitHub"- class="size-4 dark:invert"+ <Github+ aria-hidden="true"+ class="size-4 text-foreground [&_path]:fill-current"/>{{mode === 'login'diff --git a/resources/js/components/create/ideas/IdeasToolbar.vue b/resources/js/components/create/ideas/IdeasToolbar.vueindex 1e529373a..aa9ed1324 100644--- a/resources/js/components/create/ideas/IdeasToolbar.vue+++ b/resources/js/components/create/ideas/IdeasToolbar.vue@@ -96,6 +96,7 @@ const views: { key: IdeasView; label: string; icon: typeof IconColumns3 }[] = [v-model:untagged="untagged":labels="labels"test-id="ideas-filter-labels"+ sheet-below-sm/><divdiff --git a/resources/js/components/mcp/McpConnectDialog.vue b/resources/js/components/mcp/McpConnectDialog.vueindex c0d0749c1..f7f9f81fb 100644--- a/resources/js/components/mcp/McpConnectDialog.vue+++ b/resources/js/components/mcp/McpConnectDialog.vue@@ -59,10 +59,9 @@ const focusDialogFrame = (event: Event): void => {class="inline-flex size-11 shrink-0 items-center justify-center rounded-xl border border-border bg-card"aria-hidden="true">- <img- :src="client.logo"- alt=""- :class="['size-6', client.logoClass]"+ <component+ :is="client.logo"+ class="size-6 text-foreground"/></span><div class="flex min-w-0 flex-col gap-1">@@ -112,10 +111,10 @@ const focusDialogFrame = (event: Event): void => {<spanclass="absolute inset-x-0 flex items-center justify-center gap-1.5 text-xs font-medium text-muted-foreground">- <img- :src="client.logo"- alt=""- :class="['size-3.5', client.logoClass]"+ <component+ :is="client.logo"+ aria-hidden="true"+ class="size-3.5 text-foreground"/>{{ client.labelKey ? $t(client.label) : client.label }}</span>diff --git a/resources/js/components/posts/PostChannelFilter.vue b/resources/js/components/posts/PostChannelFilter.vueindex 26921e3d1..0506c5314 100644--- a/resources/js/components/posts/PostChannelFilter.vue+++ b/resources/js/components/posts/PostChannelFilter.vue@@ -21,8 +21,13 @@ interface Channel {}const props = withDefaults(- defineProps<{ channels: Channel[]; testId?: string }>(),- { testId: 'posts-channel' },+ defineProps<{+ channels: Channel[];+ testId?: string;+ /** Opens as a bottom sheet on phones instead of a popover. */+ sheetBelowSm?: boolean;+ }>(),+ { testId: 'posts-channel', sheetBelowSm: false },);const selectedIds = defineModel<string[]>({ required: true });@@ -57,6 +62,7 @@ const { open: openConnectDialog } = useConnectChannelDialog();:test-id="testId"content-class="w-96"icon-only-on-mobile+ :sheet-below-sm="sheetBelowSm"><template #icon><IconLayoutGrid class="size-4" />diff --git a/resources/js/components/posts/composer/MediaSourceMenu.vue b/resources/js/components/posts/composer/MediaSourceMenu.vueindex b3387adf0..1fbd44de9 100644--- a/resources/js/components/posts/composer/MediaSourceMenu.vue+++ b/resources/js/components/posts/composer/MediaSourceMenu.vue@@ -29,7 +29,6 @@ import {type MediaImportPayload,useMediaImport,} from '@/composables/useMediaImport';-import { inTextColor } from '@/lib/brandLogos';import { defaultCanvaPreset, openCanva } from '@/lib/mediaSources/canva';import {type GoogleDrivePick,@@ -63,7 +62,12 @@ const ICONS: Record<SourceKey, Component> = {canva: Canva,google_drive: GoogleDrive,google_photos: GooglePhotos,- unsplash: inTextColor(Unsplash),+ unsplash: Unsplash,+};++/** Unsplash's one-color mark is drawn in the text color, so it follows the theme. */+const ICON_CLASSES: Partial<Record<SourceKey, string>> = {+ unsplash: 'fill-current',};const page = usePage();@@ -260,7 +264,7 @@ const pickCanvaPreset = (><component:is="ICONS[option.source]"- class="text-foreground"+ :class="['text-foreground', ICON_CLASSES[option.source]]"/>{{ option.label }}</DropdownMenuSubTrigger>@@ -307,7 +311,7 @@ const pickCanvaPreset = (><component:is="ICONS[option.source]"- class="text-foreground"+ :class="['text-foreground', ICON_CLASSES[option.source]]"/>{{ option.label }}</DropdownMenuItem>diff --git a/resources/js/components/posts/previews/BlueskyPreview.vue b/resources/js/components/posts/previews/BlueskyPreview.vueindex 1790c6fab..9d261c93c 100644--- a/resources/js/components/posts/previews/BlueskyPreview.vue+++ b/resources/js/components/posts/previews/BlueskyPreview.vue@@ -9,9 +9,9 @@ import {} from '@tabler/icons-vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import date from '@/date';-import type { PreviewProps } from './types';defineProps<PreviewProps>();</script>diff --git a/resources/js/components/posts/previews/DiscordPreview.vue b/resources/js/components/posts/previews/DiscordPreview.vueindex 77262b2c7..ca719aa16 100644--- a/resources/js/components/posts/previews/DiscordPreview.vue+++ b/resources/js/components/posts/previews/DiscordPreview.vue@@ -2,9 +2,9 @@import { computed } from 'vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import date from '@/date';-import type { PreviewProps } from './types';interface EmbedDraft {title?: string;diff --git a/resources/js/components/posts/previews/FacebookPreview.vue b/resources/js/components/posts/previews/FacebookPreview.vueindex 75dc5fa55..11b1c7a8a 100644--- a/resources/js/components/posts/previews/FacebookPreview.vue+++ b/resources/js/components/posts/previews/FacebookPreview.vue@@ -11,11 +11,11 @@ import PreviewStoryHeader from '@/components/posts/previews/PreviewStoryHeader.vimport PreviewText from '@/components/posts/previews/PreviewText.vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';import PreviewVerticalCard from '@/components/posts/previews/PreviewVerticalCard.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import date from '@/date';import { facebookLinkPreviewUrl } from '@/lib/facebookLinkPreview';import { ContentType } from '@/types/content-type';-import type { PreviewProps } from './types';defineProps<PreviewProps>();</script>diff --git a/resources/js/components/posts/previews/GoogleBusinessPreview.vue b/resources/js/components/posts/previews/GoogleBusinessPreview.vueindex 696ff2372..736e5a226 100644--- a/resources/js/components/posts/previews/GoogleBusinessPreview.vue+++ b/resources/js/components/posts/previews/GoogleBusinessPreview.vue@@ -3,6 +3,7 @@ import { IconDotsVertical, IconShare } from '@tabler/icons-vue';import { computed } from 'vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import date from '@/date';import {GOOGLE_BUSINESS_EVENT_TOPIC_TYPES,@@ -13,7 +14,6 @@ import {import { isGif, isImage } from '@/lib/mediaType';import type { MediaItem } from '@/types/media';-import type { PreviewProps } from './types';const props = defineProps<PreviewProps>();diff --git a/resources/js/components/posts/previews/InstagramPreview.vue b/resources/js/components/posts/previews/InstagramPreview.vueindex c115648ab..6970b1975 100644--- a/resources/js/components/posts/previews/InstagramPreview.vue+++ b/resources/js/components/posts/previews/InstagramPreview.vue@@ -18,6 +18,7 @@ import PreviewAvatar from '@/components/posts/previews/PreviewAvatar.vue';import PreviewStoryHeader from '@/components/posts/previews/PreviewStoryHeader.vue';import PreviewText from '@/components/posts/previews/PreviewText.vue';import PreviewVerticalCard from '@/components/posts/previews/PreviewVerticalCard.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import {providePreviewSoundtrack,soundtrackLabel,@@ -25,7 +26,6 @@ import {import { ContentType } from '@/types/content-type';import type { InstagramAudio } from '@/types/instagram';-import type { PreviewProps } from './types';const props = defineProps<PreviewProps>();diff --git a/resources/js/components/posts/previews/LinkedInPreview.vue b/resources/js/components/posts/previews/LinkedInPreview.vueindex 4ae3daefd..bf891228a 100644--- a/resources/js/components/posts/previews/LinkedInPreview.vue+++ b/resources/js/components/posts/previews/LinkedInPreview.vue@@ -7,9 +7,9 @@ import {} from '@tabler/icons-vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import date from '@/date';-import type { PreviewProps } from './types';defineProps<PreviewProps>();</script>diff --git a/resources/js/components/posts/previews/MastodonPreview.vue b/resources/js/components/posts/previews/MastodonPreview.vueindex ea60d286a..18d97158f 100644--- a/resources/js/components/posts/previews/MastodonPreview.vue+++ b/resources/js/components/posts/previews/MastodonPreview.vue@@ -10,9 +10,9 @@ import {import { computed } from 'vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import date from '@/date';-import type { PreviewProps } from './types';const props = defineProps<PreviewProps>();diff --git a/resources/js/components/posts/previews/PinterestPreview.vue b/resources/js/components/posts/previews/PinterestPreview.vueindex 4b588d1b5..6fd6f984b 100644--- a/resources/js/components/posts/previews/PinterestPreview.vue+++ b/resources/js/components/posts/previews/PinterestPreview.vue@@ -4,8 +4,7 @@ import { computed } from 'vue';import PostMediaPreview from '@/components/posts/previews/PostMediaPreview.vue';import PreviewAvatar from '@/components/posts/previews/PreviewAvatar.vue';--import type { PreviewProps } from './types';+import type { PreviewProps } from '@/components/posts/previews/types';const props = defineProps<PreviewProps>();diff --git a/resources/js/components/posts/previews/PlatformPreview.vue b/resources/js/components/posts/previews/PlatformPreview.vueindex 7956162c1..c2f7bb228 100644--- a/resources/js/components/posts/previews/PlatformPreview.vue+++ b/resources/js/components/posts/previews/PlatformPreview.vue@@ -1,27 +1,27 @@<script setup lang="ts">import { computed, nextTick, ref, watch } from 'vue';++import BlueskyPreview from '@/components/posts/previews/BlueskyPreview.vue';+import DiscordPreview from '@/components/posts/previews/DiscordPreview.vue';+import FacebookPreview from '@/components/posts/previews/FacebookPreview.vue';+import GoogleBusinessPreview from '@/components/posts/previews/GoogleBusinessPreview.vue';+import InstagramPreview from '@/components/posts/previews/InstagramPreview.vue';+import LinkedInPreview from '@/components/posts/previews/LinkedInPreview.vue';+import MastodonPreview from '@/components/posts/previews/MastodonPreview.vue';+import PinterestPreview from '@/components/posts/previews/PinterestPreview.vue';+import TelegramPreview from '@/components/posts/previews/TelegramPreview.vue';+import ThreadsPreview from '@/components/posts/previews/ThreadsPreview.vue';+import TikTokPreview from '@/components/posts/previews/TikTokPreview.vue';+import type { PreviewAccount } from '@/components/posts/previews/types';+import XPreview from '@/components/posts/previews/XPreview.vue';+import YouTubePreview from '@/components/posts/previews/YouTubePreview.vue';import { getPlatformLabel } from '@/composables/usePlatformLogo';import { useXLinkDefuser } from '@/composables/useXLinkDefuser';import { type ThreadReply, threadRepliesOf } from '@/lib/threadReplies';import type { MediaItem } from '@/types/media';import { THREAD_PLATFORMS } from '@/types/network-options';-import BlueskyPreview from './BlueskyPreview.vue';-import DiscordPreview from './DiscordPreview.vue';-import FacebookPreview from './FacebookPreview.vue';-import GoogleBusinessPreview from './GoogleBusinessPreview.vue';-import InstagramPreview from './InstagramPreview.vue';-import LinkedInPreview from './LinkedInPreview.vue';-import MastodonPreview from './MastodonPreview.vue';-import PinterestPreview from './PinterestPreview.vue';-import TelegramPreview from './TelegramPreview.vue';-import ThreadsPreview from './ThreadsPreview.vue';-import TikTokPreview from './TikTokPreview.vue';-import type { PreviewAccount } from './types';-import XPreview from './XPreview.vue';-import YouTubePreview from './YouTubePreview.vue';-interface Props {platform: string;socialAccount: PreviewAccount | null | undefined;diff --git a/resources/js/components/posts/previews/PreviewAvatar.vue b/resources/js/components/posts/previews/PreviewAvatar.vueindex 36d170405..e46112f80 100644--- a/resources/js/components/posts/previews/PreviewAvatar.vue+++ b/resources/js/components/posts/previews/PreviewAvatar.vue@@ -1,7 +1,7 @@<script setup lang="ts">+import type { PreviewAccount } from '@/components/posts/previews/types';import { getInitials } from '@/composables/useInitials';-import type { PreviewAccount } from './types';withDefaults(defineProps<{diff --git a/resources/js/components/posts/previews/PreviewMedia.vue b/resources/js/components/posts/previews/PreviewMedia.vueindex 965e1c0c8..09f179459 100644--- a/resources/js/components/posts/previews/PreviewMedia.vue+++ b/resources/js/components/posts/previews/PreviewMedia.vue@@ -3,11 +3,11 @@ import { IconVolumeOff } from '@tabler/icons-vue';import { computed } from 'vue';import PostMediaPreview from '@/components/posts/previews/PostMediaPreview.vue';+import type { PreviewMediaLayout } from '@/components/posts/previews/types';import VideoPreview from '@/components/posts/previews/VideoPreview.vue';import { isDocument, isVideo } from '@/lib/mediaType';import type { MediaItem } from '@/types/media';-import type { PreviewMediaLayout } from './types';const props = withDefaults(defineProps<{diff --git a/resources/js/components/posts/previews/PreviewStoryHeader.vue b/resources/js/components/posts/previews/PreviewStoryHeader.vueindex 216c4b095..af01b84ae 100644--- a/resources/js/components/posts/previews/PreviewStoryHeader.vue+++ b/resources/js/components/posts/previews/PreviewStoryHeader.vue@@ -1,7 +1,6 @@<script setup lang="ts">import PreviewAvatar from '@/components/posts/previews/PreviewAvatar.vue';--import type { PreviewAccount } from './types';+import type { PreviewAccount } from '@/components/posts/previews/types';defineProps<{account: PreviewAccount;diff --git a/resources/js/components/posts/previews/PreviewTextPost.vue b/resources/js/components/posts/previews/PreviewTextPost.vueindex 1c15ad862..263bbf830 100644--- a/resources/js/components/posts/previews/PreviewTextPost.vue+++ b/resources/js/components/posts/previews/PreviewTextPost.vue@@ -6,15 +6,15 @@ import LinkCard from '@/components/posts/previews/LinkCard.vue';import PreviewAvatar from '@/components/posts/previews/PreviewAvatar.vue';import PreviewMedia from '@/components/posts/previews/PreviewMedia.vue';import PreviewText from '@/components/posts/previews/PreviewText.vue';-import VerifiedBadge from '@/components/VerifiedBadge.vue';-import { useLinkCard } from '@/composables/useLinkCard';-import type { MediaItem } from '@/types/media';-import type {PreviewAccount,PreviewAction,PreviewMediaLayout,-} from './types';+} from '@/components/posts/previews/types';+import VerifiedBadge from '@/components/VerifiedBadge.vue';+import { useLinkCard } from '@/composables/useLinkCard';+import type { MediaItem } from '@/types/media';+const props = withDefaults(defineProps<{diff --git a/resources/js/components/posts/previews/PreviewVerticalCard.vue b/resources/js/components/posts/previews/PreviewVerticalCard.vueindex 655f2aede..b74d088cc 100644--- a/resources/js/components/posts/previews/PreviewVerticalCard.vue+++ b/resources/js/components/posts/previews/PreviewVerticalCard.vue@@ -1,10 +1,10 @@<script setup lang="ts">import { IconPlayerPlayFilled } from '@tabler/icons-vue';+import type { PreviewAction } from '@/components/posts/previews/types';import VerticalMediaCanvas from '@/components/posts/previews/VerticalMediaCanvas.vue';import type { MediaItem } from '@/types/media';-import type { PreviewAction } from './types';withDefaults(defineProps<{diff --git a/resources/js/components/posts/previews/TelegramPreview.vue b/resources/js/components/posts/previews/TelegramPreview.vueindex 1846ff598..7562d543a 100644--- a/resources/js/components/posts/previews/TelegramPreview.vue+++ b/resources/js/components/posts/previews/TelegramPreview.vue@@ -1,7 +1,6 @@<script setup lang="ts">import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';--import type { PreviewProps } from './types';+import type { PreviewProps } from '@/components/posts/previews/types';defineProps<PreviewProps>();</script>diff --git a/resources/js/components/posts/previews/ThreadsPreview.vue b/resources/js/components/posts/previews/ThreadsPreview.vueindex 7af115deb..7ee24dad6 100644--- a/resources/js/components/posts/previews/ThreadsPreview.vue+++ b/resources/js/components/posts/previews/ThreadsPreview.vue@@ -12,9 +12,9 @@ import {import { computed } from 'vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import { ContentType } from '@/types/content-type';-import type { PreviewProps } from './types';const props = defineProps<PreviewProps>();diff --git a/resources/js/components/posts/previews/TikTokPreview.vue b/resources/js/components/posts/previews/TikTokPreview.vueindex e30e0a75f..3b7595a7a 100644--- a/resources/js/components/posts/previews/TikTokPreview.vue+++ b/resources/js/components/posts/previews/TikTokPreview.vue@@ -16,9 +16,9 @@ import { computed } from 'vue';import PreviewAvatar from '@/components/posts/previews/PreviewAvatar.vue';import PreviewText from '@/components/posts/previews/PreviewText.vue';import PreviewVerticalCard from '@/components/posts/previews/PreviewVerticalCard.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import { isImage } from '@/lib/mediaType';-import type { PreviewProps } from './types';const props = defineProps<PreviewProps>();diff --git a/resources/js/components/posts/previews/XPreview.vue b/resources/js/components/posts/previews/XPreview.vueindex 93bea3c49..9e50e2ad8 100644--- a/resources/js/components/posts/previews/XPreview.vue+++ b/resources/js/components/posts/previews/XPreview.vue@@ -9,8 +9,7 @@ import {} from '@tabler/icons-vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';--import type { PreviewProps } from './types';+import type { PreviewProps } from '@/components/posts/previews/types';defineProps<PreviewProps>();</script>diff --git a/resources/js/components/posts/previews/YouTubePreview.vue b/resources/js/components/posts/previews/YouTubePreview.vueindex 823e00398..73c699a8c 100644--- a/resources/js/components/posts/previews/YouTubePreview.vue+++ b/resources/js/components/posts/previews/YouTubePreview.vue@@ -11,10 +11,10 @@ import { computed } from 'vue';import PreviewAvatar from '@/components/posts/previews/PreviewAvatar.vue';import PreviewText from '@/components/posts/previews/PreviewText.vue';import PreviewVerticalCard from '@/components/posts/previews/PreviewVerticalCard.vue';+import type { PreviewProps } from '@/components/posts/previews/types';import { isVideo } from '@/lib/mediaType';import { toNullableText } from '@/lib/utils';-import type { PreviewProps } from './types';const props = defineProps<PreviewProps>();diff --git a/resources/js/components/publish/CalendarTimeGrid.vue b/resources/js/components/publish/CalendarTimeGrid.vueindex adc0a3890..efec392ea 100644--- a/resources/js/components/publish/CalendarTimeGrid.vue+++ b/resources/js/components/publish/CalendarTimeGrid.vue@@ -207,7 +207,6 @@ watch(v-for="(column, index) in columns":key="column.key"class="relative"- :class="{ 'border-l border-border-strong': index > 0 }"><divv-for="hour in HOURS"@@ -219,6 +218,7 @@ watch('bg-primary/15': isHourOver(index, hour),'border-t border-border-strong':hour > 0 && (index > 0 || hour % 2 === 1),+ 'border-l border-border-strong': index > 0,}":style="{ height: `${ROW_HEIGHT}px` }":data-drop-over="isHourOver(index, hour) || undefined"@@ -230,7 +230,7 @@ watch(aria-hidden="true"><span- class="px-2 text-xs leading-[15px] font-medium text-muted-foreground"+ class="px-2 text-xs leading-[15px] font-medium whitespace-nowrap text-muted-foreground max-sm:px-1">{{ date.formatHourOption(hourLabel(hour)) }}</span><span class="h-px flex-1 bg-border-strong" />diff --git a/resources/js/components/publish/PublishFilterMenu.vue b/resources/js/components/publish/PublishFilterMenu.vueindex 4ceabc893..3cd083356 100644--- a/resources/js/components/publish/PublishFilterMenu.vue+++ b/resources/js/components/publish/PublishFilterMenu.vue@@ -74,64 +74,74 @@ const rowClass =</Button></template>- <template v-if="status !== null">+ <template #default="{ close }">+ <template v-if="status !== null">+ <div+ role="group"+ :aria-label="$t('calendar.status.label')"+ data-testid="calendar-status-filter"+ >+ <p class="px-2 pt-1 pb-1.5 text-xs text-muted-foreground">+ {{ $t('calendar.status.label') }}+ </p>+ <button+ v-for="option in CALENDAR_STATUSES"+ :key="option"+ type="button"+ :aria-pressed="status === option"+ :class="rowClass"+ :data-testid="`calendar-status-${option}`"+ @click="selectStatus(option)"+ >+ {{ $t(`calendar.status.${option}`) }}+ <IconCheck v-if="status === option" class="ms-auto size-4" />+ </button>+ </div>+ <div class="my-2 h-px bg-border" />+ </template>+<divrole="group"- :aria-label="$t('calendar.status.label')"- data-testid="calendar-status-filter"+ :aria-label="$t('posts.publish.timezone.label')"+ data-testid="publish-timezone-select"><p class="px-2 pt-1 pb-1.5 text-xs text-muted-foreground">- {{ $t('calendar.status.label') }}+ {{ $t('posts.publish.timezone.label') }}</p>+ <TimezoneSelect+ v-model="timezone"+ :options="timezones"+ testid="publish-timezone"+ />+ </div>++ <template v-if="hasSlotOptions()">+ <div class="my-2 h-px bg-border" /><button- v-for="option in CALENDAR_STATUSES"- :key="option"+ v-if="showSlots !== null"type="button"- :aria-pressed="status === option"+ :aria-pressed="showSlots":class="rowClass"- :data-testid="`calendar-status-${option}`"- @click="selectStatus(option)"+ :data-testid="`${testId}-toggle-slots`"+ @click="setShowSlots(!showSlots)">- {{ $t(`calendar.status.${option}`) }}- <IconCheck v-if="status === option" class="ms-auto size-4" />+ {{ $t('posts.publish.menu.show_posting_times') }}+ <IconCheck v-if="showSlots" class="ms-auto size-4" /></button>- </div>- <div class="my-2 h-px bg-border" />- </template>-- <div- role="group"- :aria-label="$t('posts.publish.timezone.label')"- data-testid="publish-timezone-select"- >- <TimezoneSelect- v-model="timezone"- :options="timezones"- testid="publish-timezone"- />- </div>+ <Link+ v-if="manageSlotsHref"+ :href="manageSlotsHref"+ :class="rowClass"+ :data-testid="`${testId}-manage-slots`"+ >+ {{ $t('posts.publish.menu.manage_posting_times') }}+ </Link>+ </template>- <template v-if="hasSlotOptions()">- <div class="my-2 h-px bg-border" />- <button- v-if="showSlots !== null"- type="button"- :aria-pressed="showSlots"- :class="rowClass"- :data-testid="`${testId}-toggle-slots`"- @click="setShowSlots(!showSlots)"- >- {{ $t('posts.publish.menu.show_posting_times') }}- <IconCheck v-if="showSlots" class="ms-auto size-4" />- </button>- <Link- v-if="manageSlotsHref"- :href="manageSlotsHref"- :class="rowClass"- :data-testid="`${testId}-manage-slots`"- >- {{ $t('posts.publish.menu.manage_posting_times') }}- </Link>+ <template v-if="$slots['compact-items']">+ <div class="my-2 h-px bg-border" />+ <slot name="compact-items" :row-class="rowClass" :close="close" />+ </template></template></ResponsivePopover>diff --git a/resources/js/components/publish/PublishTabs.vue b/resources/js/components/publish/PublishTabs.vueindex 39fd9d14b..7cb20dd87 100644--- a/resources/js/components/publish/PublishTabs.vue+++ b/resources/js/components/publish/PublishTabs.vue@@ -46,7 +46,10 @@ const closeSelect = (): void => {<IconChevronDown class="size-4 text-muted-foreground" /></button></template>- <nav class="flex flex-col gap-1" :aria-label="$t('posts.publish.title')">+ <nav class="flex flex-col gap-1" :aria-label="$t('posts.publish.tabs.label')">+ <p class="px-2 pt-1 pb-0.5 text-xs text-muted-foreground">+ {{ $t('posts.publish.tabs.label') }}+ </p><Linkv-for="key in tabs":key="key"diff --git a/resources/js/components/settings/profile/ProfileLoginSettings.vue b/resources/js/components/settings/profile/ProfileLoginSettings.vueindex 6de17fe65..d7dc4fe42 100644--- a/resources/js/components/settings/profile/ProfileLoginSettings.vue+++ b/resources/js/components/settings/profile/ProfileLoginSettings.vue@@ -1,5 +1,7 @@<script setup lang="ts">import { Form, usePage } from '@inertiajs/vue3';+import Github from '@thesvg/vue/github';+import Google from '@thesvg/vue/google';import { ref } from 'vue';import ConnectedAccountController from '@/actions/App/Http/Controllers/App/Settings/ConnectedAccountController';@@ -13,8 +15,8 @@ import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Separator } from '@/components/ui/separator';import { connect } from '@/routes/app/profile/connected-accounts';+import type { SocialProvider } from '@/types';-export type SocialProvider = 'google' | 'github';export type ConnectedAccount = {provider: SocialProvider;@@ -149,14 +151,17 @@ const providerEnabled = (provider: SocialProvider): boolean =>:data-test="`connected-account-${account.provider}`"><template #media>- <img- :src="`/images/social/${account.provider}.svg`"- :alt="account.label"- class="size-7 shrink-0 object-contain"- :class="{- 'dark:invert': account.provider === 'github',- }"- :data-testid="`connected-account-icon-${account.provider}`"+ v-if="account.provider === 'google'"+ aria-hidden="true"+ class="size-7 shrink-0"+ data-testid="connected-account-icon-google"+ />+ <Github+ v-else+ aria-hidden="true"+ class="size-7 shrink-0 text-foreground [&_path]:fill-current"+ data-testid="connected-account-icon-github"/></template><pdiff --git a/resources/js/components/ui/chart/ChartTooltipContent.vue b/resources/js/components/ui/chart/ChartTooltipContent.vueindex 8ed288369..b6c5bdc89 100644--- a/resources/js/components/ui/chart/ChartTooltipContent.vue+++ b/resources/js/components/ui/chart/ChartTooltipContent.vue@@ -5,14 +5,17 @@ import ChannelAvatar from '@/components/ChannelAvatar.vue';import { activeLocale } from '@/language';-import type { ChartConfig } from '.';+import type { ChartConfig, ChartTooltipDetail } from '.';const props = withDefaults(defineProps<{payload?: Record<string, unknown>;config?: ChartConfig;labelFormatter?: (value: number | Date) => string;- detailFormatter?: (key: string, value: number) => string | null;+ /** The labelled numbers listed under an entry, such as where it started and what it gained. */+ detailFormatter?: (key: string, value: number) => ChartTooltipDetail[];+ /** A labelled total for the whole point, shown under its heading, such as a day's posts. */+ totalFormatter?: (x: number | Date) => ChartTooltipDetail | null;x?: number | Date;}>(),{ payload: () => ({}), config: () => ({}) },@@ -27,12 +30,25 @@ const entries = computed(() =>key,item,value,- detail: props.detailFormatter?.(key, value) ?? null,+ details: props.detailFormatter?.(key, value) ?? [],},]: [];}),);++const total = computed((): ChartTooltipDetail | null => {+ if (props.x === undefined || !props.totalFormatter) {+ return null;+ }++ return props.totalFormatter(props.x);+});++const DETAIL_TONES: Record<NonNullable<ChartTooltipDetail['tone']>, string> = {+ up: 'text-success-text',+ down: 'text-destructive-text',+};</script><template>@@ -46,22 +62,26 @@ const entries = computed(() =>>{{ labelFormatter ? labelFormatter(x) : x }}</p>+ <div+ v-if="total"+ class="flex items-center justify-between gap-6 border-b border-border px-3 py-2 font-medium text-foreground"+ data-testid="analytics-tooltip-total"+ >+ <span>{{ total.label }}</span>+ <span class="tabular-nums">{{ total.value }}</span>+ </div><div class="grid gap-2 px-3 py-2.5"><div v-for="entry in entries" :key="entry.key" class="grid gap-0.5"><div class="flex items-center justify-between gap-6"><spanclass="inline-flex min-w-0 items-center gap-2 text-muted-foreground">- <span- data-testid="analytics-tooltip-swatch"- class="size-2.5 shrink-0 rounded-[3px]"- :style="{ backgroundColor: entry.item.color }"- /><ChannelAvatarv-if="entry.item.avatar":platform="entry.item.avatar.platform":name="entry.item.avatar.name":src="entry.item.avatar.src"+ :verified="entry.item.avatar.verified ?? null":size="20"ring="popover"data-testid="analytics-tooltip-avatar"@@ -74,13 +94,31 @@ const entries = computed(() =>>{{ entry.value.toLocaleString(activeLocale) }}</span></div>- <p- v-if="entry.detail"- class="ps-[18px] text-muted-foreground"+ <dl+ v-if="entry.details.length > 0"+ class="mt-1 grid gap-1 border-t border-border pt-2"data-testid="analytics-tooltip-detail">- {{ entry.detail }}- </p>+ <div+ v-for="detail in entry.details"+ :key="detail.label"+ class="flex items-center justify-between gap-6"+ >+ <dt+ class="text-muted-foreground"+ data-testid="analytics-tooltip-detail-label"+ >+ {{ detail.label }}+ </dt>+ <dd+ class="font-medium text-foreground tabular-nums"+ data-testid="analytics-tooltip-detail-value"+ :class="detail.tone && DETAIL_TONES[detail.tone]"+ >+ {{ detail.value }}+ </dd>+ </div>+ </dl></div></div></div>diff --git a/resources/js/components/ui/chart/index.ts b/resources/js/components/ui/chart/index.tsindex b9a650b38..6fa61541f 100644--- a/resources/js/components/ui/chart/index.ts+++ b/resources/js/components/ui/chart/index.ts@@ -1,23 +1,37 @@import { createContext } from 'reka-ui';import type { Ref } from 'vue';+import type { VerifiedBadge } from '@/types/social-account';+export {VisCrosshair as ChartCrosshair,VisTooltip as ChartTooltip,} from '@unovis/vue';export { default as ChartContainer } from './ChartContainer.vue';export { default as ChartTooltipContent } from './ChartTooltipContent.vue';-export { componentToString } from './utils';+export { componentToString, numericTick } from './utils';export type ChartConfig = Record<string,{label: string;color: string;- avatar?: { platform: string; name: string; src: string | null };+ avatar?: {+ platform: string;+ name: string;+ src: string | null;+ verified?: VerifiedBadge | null;+ };}>;+/** One labelled number under an entry of the tooltip; a tone colors a gain or a loss. */+export type ChartTooltipDetail = {+ label: string;+ value: string;+ tone?: 'up' | 'down';+};+interface ChartContext {id: string;config: Ref<ChartConfig>;diff --git a/resources/js/components/ui/chart/utils.ts b/resources/js/components/ui/chart/utils.tsindex 0667adee8..d44fca0af 100644--- a/resources/js/components/ui/chart/utils.ts+++ b/resources/js/components/ui/chart/utils.ts@@ -1,4 +1,4 @@-import { h, render, type Component } from 'vue';+import { type AppContext, type Component, h, render } from 'vue';import { activeLocale } from '@/language';@@ -8,6 +8,7 @@ export const componentToString = (config: ChartConfig,component: Component,props: Record<string, unknown> = {},+ appContext: AppContext | null = null,): ((data: Record<string, unknown>, x?: number | Date) => string) | undefined => {if (typeof document === 'undefined') return undefined;@@ -23,10 +24,23 @@ export const componentToString = (if (cached) return cached;const element = document.createElement('div');- render(h(component, { ...props, payload: data, config, x }), element);+ const tooltip = h(component, { ...props, payload: data, config, x });+ tooltip.appContext = appContext;+ render(tooltip, element);const content = element.innerHTML;render(null, element);cache.set(key, content);return content;};};++/**+ * unovis types an axis tick as `number | Date`, since the same axis also+ * draws time. Our charts only run on numbers (a column's index or a value),+ * so each formatter takes the number, and this is the one place that reads+ * it out of unovis' type.+ */+export const numericTick =+ <Result>(format: (tick: number, index: number, ticks: number[]) => Result) =>+ (tick: number | Date, index = 0, ticks: number[] | Date[] = []): Result =>+ format(Number(tick), index, ticks.map(Number))diff --git a/resources/js/components/ui/date-range-picker/DateRangePicker.vue b/resources/js/components/ui/date-range-picker/DateRangePicker.vueindex b9ea25f69..a7c412f70 100644--- a/resources/js/components/ui/date-range-picker/DateRangePicker.vue+++ b/resources/js/components/ui/date-range-picker/DateRangePicker.vue@@ -31,12 +31,28 @@ const props = withDefaults(defineProps<{disabled?: booleanalign?: "start" | "center" | "end"sheetBelowSm?: boolean+ /** Opened only through `v-model:open`, as from a menu item, with no button of its own. */+ withoutTrigger?: boolean}>(), {align: "end",sheetBelowSm: false,+ withoutTrigger: false,})const [DefinePanel, ReusePanel] = createReusableTemplate()+const [DefineMonth, ReuseMonth] = createReusableTemplate<{ fill?: boolean }>()++/** The phone sheet's month: every day stretched over the card, like the calendar's period sheet. */+const FILLED_MONTH = [+ "w-full p-0",+ "[&_[data-slot=range-calendar-header]]:justify-start [&_[data-slot=range-calendar-header]]:gap-2",+ "[&_[data-slot=range-calendar-heading]]:order-first [&_[data-slot=range-calendar-heading]]:me-auto [&_[data-slot=range-calendar-heading]]:text-base",+ "[&_[data-slot=range-calendar-grid]]:w-full",+ "[&_[data-slot=range-calendar-head-cell]]:flex-1 [&_[data-slot=range-calendar-head-cell]]:text-xs",+ "[&_[data-slot=range-calendar-grid-row]]:mt-1",+ "[&_[data-slot=range-calendar-cell]]:flex [&_[data-slot=range-calendar-cell]]:flex-1 [&_[data-slot=range-calendar-cell]]:justify-center",+ "[&_[data-slot=range-calendar-trigger]]:size-10 [&_[data-slot=range-calendar-trigger]]:text-base",+].join(" ")const belowSm = useBelowBreakpoint("sm")const asSheet = computed(() => props.sheetBelowSm && belowSm.value)@@ -150,6 +166,18 @@ watch(</script><template>+ <DefineMonth v-slot="{ fill }">+ <RangeCalendar+ v-model="value"+ initial-focus+ :class="{ [FILLED_MONTH]: fill }"+ :locale="calendarLocale"+ :number-of-months="numberOfMonths"+ :min-value="minimum"+ :max-value="maximum"+ />+ </DefineMonth>+<DefinePanel><div class="flex flex-col sm:flex-row"><div class="hidden flex-col border-b border-border py-2 sm:flex sm:w-[170px] sm:shrink-0 sm:border-r sm:border-b-0">@@ -172,20 +200,13 @@ watch(</div><div class="flex shrink-0 justify-center">- <RangeCalendar- v-model="value"- initial-focus- :locale="calendarLocale"- :number-of-months="numberOfMonths"- :min-value="minimum"- :max-value="maximum"- />+ <ReuseMonth /></div></div></DefinePanel><Popover v-model:open="isOpen">- <PopoverTrigger as-child>+ <PopoverTrigger v-if="!withoutTrigger" as-child><slot name="trigger"><Buttonvariant="outline"@@ -221,9 +242,16 @@ watch(v-if="asSheet"v-model:open="isOpen":title="$t('common.date_range_picker.placeholder')"+ :show-header="false"+ handletest-id="date-range-picker-sheet"- content-class="pb-[max(1rem,env(safe-area-inset-bottom))]"+ content-class="bg-muted px-4 pb-[max(1.5rem,env(safe-area-inset-bottom))]">- <ReusePanel />+ <p class="mb-4 text-center text-base font-emphasis text-foreground">+ {{ $t('common.date_range_picker.placeholder') }}+ </p>+ <div class="rounded-xl bg-card p-4" data-testid="date-range-picker-month">+ <ReuseMonth :fill="true" />+ </div></BottomSheet></template>diff --git a/resources/js/components/webhook/CreateWebhookDialog.vue b/resources/js/components/webhook/CreateWebhookDialog.vueindex 9ecb231b0..7bc82c24b 100644--- a/resources/js/components/webhook/CreateWebhookDialog.vue+++ b/resources/js/components/webhook/CreateWebhookDialog.vue@@ -10,9 +10,9 @@ import {DialogFooter,DialogTitle,} from '@/components/ui/dialog';+import WebhookFormFields from '@/components/webhook/WebhookFormFields.vue';import { store } from '@/routes/app/webhooks';-import WebhookFormFields from './WebhookFormFields.vue';const open = defineModel<boolean>('open', { default: false });diff --git a/resources/js/components/webhook/EditWebhookDialog.vue b/resources/js/components/webhook/EditWebhookDialog.vueindex 27ddf692b..21cb34a00 100644--- a/resources/js/components/webhook/EditWebhookDialog.vue+++ b/resources/js/components/webhook/EditWebhookDialog.vue@@ -10,9 +10,9 @@ import {DialogFooter,DialogTitle,} from '@/components/ui/dialog';+import WebhookFormFields from '@/components/webhook/WebhookFormFields.vue';import { update } from '@/routes/app/webhooks';-import WebhookFormFields from './WebhookFormFields.vue';interface WebhookItem {id: string;diff --git a/resources/js/components/webhook/WebhookDeliveryBadge.vue b/resources/js/components/webhook/WebhookDeliveryBadge.vueindex c02ccdbe5..472d7193a 100644--- a/resources/js/components/webhook/WebhookDeliveryBadge.vue+++ b/resources/js/components/webhook/WebhookDeliveryBadge.vue@@ -1,8 +1,8 @@<script setup lang="ts">import { Badge } from '@/components/ui/badge';+import { deliveryBadgeVariant, deliveryState } from '@/components/webhook/webhook-delivery';import type { WebhookLog } from '@/types/webhook';-import { deliveryBadgeVariant, deliveryState } from './webhook-delivery';defineProps<{log: WebhookLog;diff --git a/resources/js/components/webhook/WebhookEventsPicker.vue b/resources/js/components/webhook/WebhookEventsPicker.vueindex e0cb229de..330e80890 100644--- a/resources/js/components/webhook/WebhookEventsPicker.vue+++ b/resources/js/components/webhook/WebhookEventsPicker.vue@@ -5,13 +5,12 @@ import InputError from '@/components/InputError.vue';import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';import { Label } from '@/components/ui/label';-import {allWebhookEvents,webhookEventDescriptionKey,webhookEventGroups,webhookEventLabelKey,-} from './webhook-events';+} from '@/components/webhook/webhook-events';const events = defineModel<string[]>({ required: true });diff --git a/resources/js/components/webhook/WebhookFormFields.vue b/resources/js/components/webhook/WebhookFormFields.vueindex 9a36700ac..1661dca50 100644--- a/resources/js/components/webhook/WebhookFormFields.vue+++ b/resources/js/components/webhook/WebhookFormFields.vue@@ -4,8 +4,7 @@ import { IconWorld } from '@tabler/icons-vue';import InputError from '@/components/InputError.vue';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';--import WebhookEventsPicker from './WebhookEventsPicker.vue';+import WebhookEventsPicker from '@/components/webhook/WebhookEventsPicker.vue';const endpoint = defineModel<string>('endpoint', { required: true });const events = defineModel<string[]>('events', { required: true });diff --git a/resources/js/components/webhook/WebhookLogDetail.vue b/resources/js/components/webhook/WebhookLogDetail.vueindex dfd1f3ce3..4acf0a6a1 100644--- a/resources/js/components/webhook/WebhookLogDetail.vue+++ b/resources/js/components/webhook/WebhookLogDetail.vue@@ -6,12 +6,12 @@ import { computed, ref } from 'vue';import JsonViewer from '@/components/JsonViewer.vue';import { Button } from '@/components/ui/button';+import { webhookEventLabel } from '@/components/webhook/webhook-events';+import WebhookDeliveryBadge from '@/components/webhook/WebhookDeliveryBadge.vue';import date from '@/date';import { replay } from '@/routes/app/webhooks';import type { WebhookLog } from '@/types/webhook';-import { webhookEventLabel } from './webhook-events';-import WebhookDeliveryBadge from './WebhookDeliveryBadge.vue';const props = defineProps<{webhookId: string;diff --git a/resources/js/components/webhook/WebhookLogList.vue b/resources/js/components/webhook/WebhookLogList.vueindex 7982e720c..163b6d912 100644--- a/resources/js/components/webhook/WebhookLogList.vue+++ b/resources/js/components/webhook/WebhookLogList.vue@@ -2,11 +2,11 @@import { InfiniteScroll } from '@inertiajs/vue3';import { Spinner } from '@/components/ui/spinner';+import { webhookEventLabel } from '@/components/webhook/webhook-events';+import WebhookDeliveryBadge from '@/components/webhook/WebhookDeliveryBadge.vue';import date from '@/date';import type { WebhookLog } from '@/types/webhook';-import { webhookEventLabel } from './webhook-events';-import WebhookDeliveryBadge from './WebhookDeliveryBadge.vue';defineProps<{logs: WebhookLog[];diff --git a/resources/js/composables/analytics/useChartAppContext.ts b/resources/js/composables/analytics/useChartAppContext.tsnew file mode 100644index 000000000..09f561629--- /dev/null+++ b/resources/js/composables/analytics/useChartAppContext.ts@@ -0,0 +1,9 @@+import { type AppContext, getCurrentInstance } from 'vue';++/**+ * The app's context for a chart's tooltip, which unovis renders outside the+ * component tree: without it, `$t` and the app's components are missing in+ * there. Read in `setup`, the only place the current instance exists.+ */+export const useChartAppContext = (): AppContext | null =>+ getCurrentInstance()?.appContext ?? null;diff --git a/resources/js/composables/useMediaEditSwap.ts b/resources/js/composables/useMediaEditSwap.tsindex 68e128008..1e1623d78 100644--- a/resources/js/composables/useMediaEditSwap.ts+++ b/resources/js/composables/useMediaEditSwap.ts@@ -37,22 +37,8 @@ const editedItem = async (change: MediaEditChange): Promise<MediaItem> => {file: change.file,url: mediaStoreChunked.url(),});- if (!uploaded.id || !uploaded.path || !uploaded.url) {- throw new Error('Incomplete asset upload');- }- return {- id: uploaded.id,- path: uploaded.path,- url: uploaded.url,- type: uploaded.type,- mime_type: uploaded.mime_type ?? change.file.type,- original_filename: uploaded.original_filename,- size: uploaded.size,- meta,- upload_token: uploaded.upload_token ?? null,- created_at: uploaded.created_at,- } as MediaItem;+ return { ...uploaded, meta };};/**diff --git a/resources/js/composables/useMediaUpload.ts b/resources/js/composables/useMediaUpload.tsindex 9a6f0aa75..87153a762 100644--- a/resources/js/composables/useMediaUpload.ts+++ b/resources/js/composables/useMediaUpload.ts@@ -231,29 +231,15 @@ export const useMediaUpload = (options: {active.add(entry.key);try {- const uploaded = await uploadChunked({- file: entry.file,- url: storeChunked.url(),- signal: entry.controller.signal,- onProgress: (progress) => setProgress(entry.key, progress),- });- if (!uploaded.id || !uploaded.url) {- throw new Error('Incomplete upload');- }-- finished.set(entry.key, {- id: uploaded.id,- path: uploaded.path,- url: uploaded.url,- type: uploaded.type,- mime_type: uploaded.mime_type ?? entry.file.type,- original_filename:- uploaded.original_filename ?? entry.file.name,- size: uploaded.size ?? entry.file.size,- meta: uploaded.meta,- upload_token: uploaded.upload_token ?? null,- created_at: uploaded.created_at,- });+ finished.set(+ entry.key,+ await uploadChunked({+ file: entry.file,+ url: storeChunked.url(),+ signal: entry.controller.signal,+ onProgress: (progress) => setProgress(entry.key, progress),+ }),+ );} catch (error) {if (!entry.controller.signal.aborted && find(entry.key)) {replace(entry.key, failure(entry, error));diff --git a/resources/js/composables/useSettingsNavigation.ts b/resources/js/composables/useSettingsNavigation.tsindex 2f0b3922b..9a610037b 100644--- a/resources/js/composables/useSettingsNavigation.ts+++ b/resources/js/composables/useSettingsNavigation.ts@@ -5,7 +5,7 @@ import {IconCoin,IconCode,IconSignature,- IconPlug,+ IconMcp,IconBuilding,IconAdjustmentsHorizontal,IconTag,@@ -154,7 +154,7 @@ export const useSettingsNavigation = () => {IconCode,workspace && canManageWorkspace.value,),- ...item('mcp', mcp.url(), IconPlug, workspace),+ ...item('mcp', mcp.url(), IconMcp, workspace),...item('webhooks',webhooks.url(),diff --git a/resources/js/datalayer.ts b/resources/js/datalayer.tsindex 37160fccc..023e68d71 100644--- a/resources/js/datalayer.ts+++ b/resources/js/datalayer.ts@@ -1,4 +1,4 @@-import type { Auth } from './types';+import type { Auth } from '@/types';interface FlashData {conversion_event?: string;diff --git a/resources/js/date.ts b/resources/js/date.tsindex fc070b82f..a44941d8b 100644--- a/resources/js/date.ts+++ b/resources/js/date.ts@@ -1,6 +1,7 @@import dayjs from '@/dayjs';import { activeLocale } from '@/language';import { timeFormat, userTimezone } from '@/preferences';+import type { DateRange } from '@/types/analytics';/*** A dayjs instance bound to the current language. `dayjs.locale()` is global and@@ -27,6 +28,43 @@ const getUserTimezone = (): string => userTimezone.value;const userNow = () =>localized(dayjs().tz(getUserTimezone()).format('YYYY-MM-DDTHH:mm:ss'));+/** A period's first day with only what its last day does not already say. */+const rangeStart = (range: DateRange): string => {+ const start = localized(range.start);+ const end = localized(range.end);++ if (start.year() !== end.year()) {+ return start.format('D MMM YYYY');+ }++ if (start.month() !== end.month()) {+ return start.format('D MMM');+ }++ return start.format('D');+};++/** A period with its last day in full: "25 – 31 Oct 2026", or the day alone when it is one day. */+const dayMonthYearRange = (range: DateRange): string => spanOf(range, 'D MMM YYYY');++/** A period ending on its last day in `endFormat`, the day alone when the period is one day. */+const spanOf = (range: DateRange, endFormat: string): string => {+ const end = localized(range.end).format(endFormat);++ if (range.start === range.end) {+ return end;+ }++ return `${rangeStart(range)} – ${end}`;+};++/** Whether a period starts and ends in the year `other` ends in. */+const withinYearOf = (range: DateRange, other: DateRange): boolean => {+ const year = localized(other.end).year();++ return localized(range.start).year() === year && localized(range.end).year() === year;+};+/*** `{ year: 'numeric' }` when the instant falls in another year than now, in* that zone, so an `Intl` date shows the year only when it is not obvious.@@ -193,6 +231,30 @@ export default {return localized(date).format('D MMM YYYY');},+ /**+ * A period as Insights prints it, naming its month and year once when both+ * ends share them: "25 – 31 Oct 2026", "28 Sep – 4 Oct 2026",+ * "28 Dec 2025 – 3 Jan 2026".+ */+ formatDayMonthYearRange(range: DateRange): string {+ return dayMonthYearRange(range);+ },++ /**+ * The period compared with `current`, without the year when it falls in+ * the same one: "18 – 24 Oct" next to "25 – 31 Oct 2026".+ */+ formatComparedRange(+ range: DateRange,+ current: DateRange,+ ): string {+ if (!withinYearOf(range, current)) {+ return dayMonthYearRange(range);+ }++ return spanOf(range, 'D MMM');+ },+/*** Short month + day + year for chart tooltips (locale-aware via L).*/diff --git a/resources/js/language.ts b/resources/js/language.tsindex dba86e6a6..8a1feda4f 100644--- a/resources/js/language.ts+++ b/resources/js/language.ts@@ -1,8 +1,8 @@import { getActiveLanguage, loadLanguageAsync } from 'laravel-vue-i18n';import { ref } from 'vue';-import dayjs from './dayjs';-import type { Auth, Language } from './types';+import dayjs from '@/dayjs';+import type { Auth, Language } from '@/types';interface LocaleProps {locale?: string;diff --git a/resources/js/lib/analyticsAccounts.ts b/resources/js/lib/analyticsAccounts.tsnew file mode 100644index 000000000..5e6a425bd--- /dev/null+++ b/resources/js/lib/analyticsAccounts.ts@@ -0,0 +1,19 @@+import { getPlatformLabel } from '@/composables/usePlatformLogo';+import type { AccountIdentityData } from '@/types/analytics';+import { channelName } from '@/types/channel';++/**+ * A channel's name in Insights by the app's one rule, `channelName`, as the+ * sidebar shows it; its network for a row that kept neither name nor handle.+ */+export const accountLabel = (+ account: Pick<AccountIdentityData, 'username' | 'name' | 'platform'>,+): string => {+ const name = channelName({ display_name: account.name, username: account.username });++ if (name) {+ return name;+ }++ return getPlatformLabel(account.platform);+};diff --git a/resources/js/lib/brandLogos.ts b/resources/js/lib/brandLogos.tsdeleted file mode 100644index 2fcbd27c4..000000000--- a/resources/js/lib/brandLogos.ts+++ /dev/null@@ -1,11 +0,0 @@-import { h, type Component, type FunctionalComponent } from 'vue';--/**- * A one-color brand logo from @thesvg/vue drawn in the surrounding text- * color, so it follows the theme. For logos whose paths carry no fill of- * their own (Unsplash): a fill on a path still wins.- */-export const inTextColor =- (logo: Component): FunctionalComponent =>- (_, { attrs }) =>- h(logo, { ...attrs, fill: 'currentColor' });diff --git a/resources/js/lib/canvasFile.ts b/resources/js/lib/canvasFile.tsnew file mode 100644index 000000000..8a3afa30d--- /dev/null+++ b/resources/js/lib/canvasFile.ts@@ -0,0 +1,26 @@+/**+ * A canvas encoded as an image file; rejects when the browser cannot encode it.+ * It imports nothing, so code run outside the bundler (the media editor's+ * preset parity test runs `mediaEditor.ts` in Node) can use it.+ */+export const canvasToFile = (+ canvas: HTMLCanvasElement,+ name: string,+ type: string,+ quality?: number,+): Promise<File> =>+ new Promise((resolve, reject) => {+ canvas.toBlob(+ (blob) => {+ if (!blob) {+ reject(new Error('The image could not be encoded.'));++ return;+ }++ resolve(new File([blob], name, { type }));+ },+ type,+ quality,+ );+ });diff --git a/resources/js/lib/channelMetrics.ts b/resources/js/lib/channelMetrics.tsindex 86bac42f1..0e80ee9d0 100644--- a/resources/js/lib/channelMetrics.ts+++ b/resources/js/lib/channelMetrics.ts@@ -1,10 +1,19 @@import date from '@/date';import { accountColor } from '@/lib/analyticsColors';-import { formatNumberCompact, formatPercent } from '@/lib/utils';+import {+ distinctCountLabels,+ formatCountChange,+ formatNumberCompact,+ formatPercent,+ formatPercentChange,+} from '@/lib/utils';import type {+ BucketResolution,ChannelMetricSeries,+ DateRange,FollowerGrowthRate,MetricSeriesPoint,+ PublicationPeriod,SeriesMetric,} from '@/types/analytics';@@ -125,12 +134,69 @@ export const PRESETS: Preset[] = [},];-export const isLevelMetric = (metric: SeriesMetric): boolean =>+const isLevelMetric = (metric: SeriesMetric): boolean =>LEVEL_METRICS.includes(metric);export const isPercentMetric = (metric: SeriesMetric): boolean =>PERCENT_METRICS.includes(metric);+/** Metrics the page counts rather than measures: their change is a difference, never a percentage. */+const COUNTED_METRICS: readonly SeriesMetric[] = ['net_followers'];++/** How a number moved: the signed value, which picks its tone, and how the page labels it. */+export type MetricDelta = { value: number; label: string };++/** A count's change as the page labels it: "+7", "-3". */+export const countDelta = (change: number): MetricDelta => ({ value: change, label: formatCountChange(change) });++/** A change as a percentage of the previous value, as the page labels it: "+8.5%". */+export const percentDelta = (change: number): MetricDelta => ({ value: change, label: formatPercentChange(change) });++/**+ * The followers gained or lost over the period: the net new followers the+ * report already counts (the last reading against where the period started),+ * the same number as the Summary's; null without a reading to start from.+ */+const followersDelta = (series: ChannelMetricSeries): MetricDelta | null => {+ const net = series.totals.current.net_followers;++ if (net == null) {+ return null;+ }++ return countDelta(net);+};++/**+ * How a channel metric moved: followers by what the period gained or lost,+ * net new followers by the difference with the previous period ("+7"), the+ * rest by a percentage of the previous period ("+8.5%"), kept positive so a+ * loss shrinking reads as a rise. Null for a rate, which has no previous+ * period, or when there is nothing to compare.+ */+export const seriesDelta = (series: ChannelMetricSeries, metric: SeriesMetric): MetricDelta | null => {+ if (metric === 'followers') {+ return followersDelta(series);+ }++ const current = series.totals.current[metric];+ const previous = series.totals.previous[metric];++ if (isPercentMetric(metric) || current == null || previous == null) {+ return null;+ }++ if (COUNTED_METRICS.includes(metric)) {+ return countDelta(current - previous);+ }++ if (previous === 0) {+ return null;+ }++ return percentDelta(((current - previous) / Math.abs(previous)) * 100);+};+/*** The metrics the menu offers, in menu order: followers, the network's audience metric (reach where it is* collected, otherwise impressions or views), profile visits, posts and net new followers.@@ -224,7 +290,7 @@ export const AXIS_STEPS = 4;/*** A domain split into four round steps, so every axis shares the same gridlines.*/-export const niceDomain = (+const niceDomain = (values: number[],fromZero: boolean,fractional = false,@@ -258,36 +324,93 @@ export const definedValues = (.map((point) => point.values[metric]).filter((value): value is number => typeof value === 'number');+/** The period a chart mode reads its one figure from: the previous one in Comparison, else the current. */+export const shownPeriod = (mode: ChartMode): PublicationPeriod => {+ if (mode === 'previous') {+ return 'previous';+ }++ return 'current';+};++/** The periods a chart mode draws: both in Both, else the one it shows. */+export const chartPeriods = (mode: ChartMode): PublicationPeriod[] => {+ if (mode === 'both') {+ return ['current', 'previous'];+ }++ return [shownPeriod(mode)];+};++/**+ * An axis' domain for the metrics drawn on it: from zero unless it only holds+ * followers, in hundredths for a rate; none when no metric uses the axis.+ */+export const axisDomain = (+ metrics: SeriesMetric[],+ values: number[],+): { min: number; max: number } | null => {+ if (metrics.length === 0) {+ return null;+ }++ return niceDomain(+ values,+ metrics.some((metric) => metric !== 'followers'),+ metrics.some(isPercentMetric),+ );+};++/** An axis' tick labels, bottom up: in percent for a rate, else compact but never two alike. */+export const axisTickLabels = (+ domain: { min: number; max: number },+ metrics: SeriesMetric[],+): string[] => {+ const values = Array.from(+ { length: AXIS_STEPS + 1 },+ (_, step) => domain.min + (step / AXIS_STEPS) * (domain.max - domain.min),+ );+ const rate = metrics.find(isPercentMetric);++ if (rate) {+ return values.map((value) => formatSeriesValue(value, rate));+ }++ return distinctCountLabels(values);+};++/** How many readings a metric needs to draw anything: two for a level, which only shows as a line between them, one otherwise. */+const readingsToDraw = (metric: SeriesMetric): number => {+ if (isLevelMetric(metric)) {+ return 2;+ }++ return 1;+};++/** Whether the chart has something to draw for the metrics shown, over the periods the mode shows. */export const hasEnoughHistory = (series: ChannelMetricSeries,specs: SeriesSpec[],mode: ChartMode,-): boolean => {- const periods =- mode === 'both'- ? [series.current, series.previous]- : [mode === 'previous' ? series.previous : series.current];-- return specs.some((spec) =>- periods.some(- (points) =>- definedValues(points, spec.metric).length >=- (isLevelMetric(spec.metric) ? 2 : 1),+): boolean =>+ specs.some((spec) =>+ chartPeriods(mode).some(+ (period) =>+ definedValues(series[period], spec.metric).length >=+ readingsToDraw(spec.metric),),);-};export const formatSeriesValue = (value: number | null | undefined,metric?: SeriesMetric,): string => {- if (value === null || value === undefined) {- return '—';+ if (metric && isPercentMetric(metric)) {+ return formatPercent(value);}- return metric && isPercentMetric(metric)- ? formatPercent(value)- : formatNumberCompact(value);+ return formatNumberCompact(value);};export const bucketLabel = (@@ -302,17 +425,47 @@ export const bucketLabel = (return monthLabel(point.start);}- return resolution === 'weekly' && point.start !== point.end- ? `${date.formatMonthDay(point.start)} – ${date.formatMonthDay(point.end)}`- : date.formatDayMonthYear(point.start);+ if (resolution === 'weekly' && point.start !== point.end) {+ return weekLabel(point);+ }++ return date.formatDayMonthYear(point.start);};+/** The days a week covers: "5 Oct – 11 Oct". */+const weekLabel = (week: DateRange): string =>+ `${date.formatMonthDay(week.start)} – ${date.formatMonthDay(week.end)}`;+export const monthLabel = (day: string): string => {const [year, month] = day.split('-').map(Number);return date.formatMonthYear(month, year);};+/** A bucket on the chart's time axis: the month for monthly buckets, else the day it starts. */+export const axisBucketLabel = (+ bucket: { start: string },+ resolution: BucketResolution,+): string => {+ if (resolution === 'monthly') {+ return monthLabel(bucket.start);+ }++ return date.formatMonthDay(bucket.start);+};++/** A bucket as its column's label: the month, the day, or the days a week covers. */+export const bucketRangeLabel = (+ bucket: DateRange,+ resolution: BucketResolution,+): string => {+ if (resolution === 'monthly' || bucket.start === bucket.end) {+ return axisBucketLabel(bucket, resolution);+ }++ return weekLabel(bucket);+};+const direction = (current: number,previous: number,diff --git a/resources/js/lib/insightsShare.ts b/resources/js/lib/insightsShare.tsnew file mode 100644index 000000000..53286f7fc--- /dev/null+++ b/resources/js/lib/insightsShare.ts@@ -0,0 +1,391 @@+/**+ * Builders for the share dialog. They run when the dialog opens, never in a+ * script-level computed, so every `trans()` here reads the loaded locale.+ */++import { trans } from 'laravel-vue-i18n';++import date from '@/date';+import { activeLocale } from '@/language';+import { accountLabel } from '@/lib/analyticsAccounts';+import {+ axisBucketLabel,+ bucketRangeLabel,+ type ChartMode,+ formatSeriesValue,+ type SeriesSpec,+ countDelta,+ type MetricDelta,+ seriesDelta,+ shownPeriod,+} from '@/lib/channelMetrics';+import {+ periodFigure,+ type ShareChannel,+ type ShareLine,+ type ShareMetricOption,+ type ShareSeries,+ type SharePoint,+ type ShareShape,+ type ShareTile,+} from '@/lib/shareCard';+import { formatCountChange, formatNumberCompact } from '@/lib/utils';+import type {+ AccountIdentityData,+ ChannelMetricSeries,+ FollowerAccount,+ FollowersChartMode,+ PostsChartMode,+ PublicationPeriod,+ SeriesMetric,+ WorkspaceAnalyticsReport,+} from '@/types/analytics';++type Followers = WorkspaceAnalyticsReport['followers'];++type Posts = WorkspaceAnalyticsReport['posts'];++/** The share card draws each mode of the Followers card the way the page does. */+const FOLLOWERS_SHAPES: Record<FollowersChartMode, ShareShape> = {+ bar: 'rows',+ line: 'lines',+ growth: 'rows',+};++/** A per-channel view's rows: which number each channel shows, and how it reads. */+type ChannelRowsSpec<Account> = {+ value: (account: Account) => number | null;+ format: (value: number | null) => string;+};++/** What a channel's row shows in the per-channel modes: its followers, or its signed change. */+export const FOLLOWERS_ROWS: Record<+ Exclude<FollowersChartMode, 'line'>,+ ChannelRowsSpec<FollowerAccount>+> = {+ bar: { value: (account) => account.value, format: formatNumberCompact },+ growth: { value: (account) => account.growth, format: formatCountChange },+};++const POSTS_SHAPES: Record<PostsChartMode, ShareShape> = {+ bar: 'rows',+ stacked: 'stacked',+};++/** The Posts card's Bar view: each channel's posts sent. */+export const POSTS_ROWS: ChannelRowsSpec<Posts['accounts'][number]> = {+ value: (account) => account.count,+ format: formatNumberCompact,+};++const sum = (values: number[]): number =>+ values.reduce((total, value) => total + value, 0);++/**+ * The period a share card names, with how many of the workspace's channels+ * it counts when the page is filtered to some ("2 – 31 Oct 2026 · 2 of 5+ * channels"), so the image and its post never pass a few channels off as all.+ */+export const shareRangeLabel = (range: string, shown: number | null, total: number | undefined): string => {+ if (shown === null || !total) {+ return range;+ }++ return `${range} · ${trans('analytics.share.channels_shown', { shown: String(shown), total: String(total) })}`;+};++/** The post text for one metric across the workspace's channels. */+const metricCaption = (replacements: { metric: string; value: string; range: string }): string =>+ trans('analytics.share.caption_workspace', replacements);++/** Labels joined the way the reader's language lists them: "Posts and Followers". */+const listOf = (labels: string[]): string =>+ new Intl.ListFormat(activeLocale.value, { type: 'conjunction' }).format(labels);++/** The Summary's numbers as one phrase in the reader's language: "Followers 1.2K, Posts 30 and Reach 5K". */+const summaryList = (tiles: CaptionNumber[]): string =>+ listOf(+ tiles+ .filter((tile) => !tile.missing)+ .map((tile) => `${tile.label} ${tile.figure}`),+ );++/** A number the post text lists, by its label; one without a value is left out. */+type CaptionNumber = Pick<ShareTile, 'label' | 'figure' | 'missing'>;++/** The post text for the Summary: every number with a value, in one line. */+const summaryCaption = (+ channel: string | null,+ tiles: CaptionNumber[],+ range: string,+): string => {+ const replacements = { metrics: summaryList(tiles), range };++ if (channel === null) {+ return trans('analytics.share.caption_summary_workspace', replacements);+ }++ return trans('analytics.share.caption_summary_channel', { ...replacements, channel });+};++/** An option with nothing drawn but what it is given, in the shape it names. */+const shareOption = (+ option: Pick<ShareMetricOption, 'key' | 'label' | 'caption' | 'shape'> &+ Partial<ShareMetricOption>,+): ShareMetricOption => ({+ figure: '',+ change: null,+ points: [],+ tiles: [],+ lines: [],+ series: [],+ chartMode: 'current',+ ...option,+});++/**+ * The avatar's address for the card, which loads it with CORS. A CDN in front+ * of the storage host (Cloudflare) ignores `Vary: Origin`, so the copy the+ * page's `<img>` cached without CORS headers would refuse the card; a query of+ * its own gives the card a cache entry of its own, fetched with CORS.+ */+const corsAvatar = (url: string | null | undefined): string | null => {+ if (!url) {+ return null;+ }++ const address = new URL(url, window.location.origin);++ address.searchParams.set('cors', '1');++ return address.toString();+};++/** The channel as the card draws it: its avatar, network and verified mark. */+const shareChannel = (account: AccountIdentityData): ShareChannel => ({+ platform: account.platform,+ avatar: corsAvatar(account.avatar_url),+ verified: account.verified_badge ?? null,+});++/** One row per channel in its color, the way the page's per-channel charts draw it. */+const channelRows = <Account extends AccountIdentityData>(+ accounts: Account[],+ spec: ChannelRowsSpec<Account>,+ colors: Record<string, string>,+): SharePoint[] =>+ accounts.map((account) => ({+ label: accountLabel(account),+ value: spec.value(account),+ figure: spec.format(spec.value(account)),+ color: colors[account.social_account_key],+ channel: shareChannel(account),+ }));++/** Each channel's count day by day, carrying its last known count over the days without a reading. */+const carriedForward = (followers: Followers, key: string): (number | null)[] => {+ let lastKnown: number | null = null;++ return followers.series.map((point) => {+ const value = point.accounts[key];++ if (typeof value === 'number') {+ lastKnown = value;+ }++ return lastKnown;+ });+};++/** One line per channel in its color, ending in its avatar and latest count, like the page's Line view. */+const followersLines = (followers: Followers, colors: Record<string, string>): ShareLine[] =>+ followers.accounts.map((account) => {+ const values = carriedForward(followers, account.social_account_key);++ return {+ color: colors[account.social_account_key],+ channel: shareChannel(account),+ figure: formatNumberCompact(values[values.length - 1]),+ values,+ };+ });++/** The Line view's dates, the points the lines run over. */+const followersDates = (followers: Followers): SharePoint[] =>+ followers.series.map((point) => ({ label: date.formatMonthDay(point.date), value: null }));++const followersPoints = (+ followers: Followers,+ mode: FollowersChartMode,+ colors: Record<string, string>,+): SharePoint[] => {+ if (mode === 'line') {+ return followersDates(followers);+ }++ return channelRows(followers.accounts, FOLLOWERS_ROWS[mode], colors);+};++/** The lines of the Line view; the other views draw rows. */+const followersLinesFor = (+ followers: Followers,+ mode: FollowersChartMode,+ colors: Record<string, string>,+): ShareLine[] => {+ if (mode !== 'line') {+ return [];+ }++ return followersLines(followers, colors);+};++/** The followers gained or lost over the period, across the channels that report it; null when none does. */+export const followersNet = (followers: Followers): number | null => {+ const nets = followers.accounts+ .map((account) => account.net)+ .filter((net): net is number => net != null);++ if (nets.length === 0) {+ return null;+ }++ return sum(nets);+};++const followersChange = (followers: Followers): MetricDelta | null => {+ const net = followersNet(followers);++ if (net === null) {+ return null;+ }++ return countDelta(net);+};++/** The workspace's followers the way the page's Followers card draws them in `mode`. */+export const followersShareOption = (+ followers: Followers,+ range: string,+ mode: FollowersChartMode,+ colors: Record<string, string>,+): ShareMetricOption => {+ const label = trans('analytics.dashboard.followers');+ const figure = formatSeriesValue(followers.total, 'followers');++ return shareOption({+ key: 'followers',+ label,+ figure,+ change: followersChange(followers),+ points: followersPoints(followers, mode, colors),+ lines: followersLinesFor(followers, mode, colors),+ shape: FOLLOWERS_SHAPES[mode],+ caption: metricCaption({ metric: label, value: figure, range }),+ });+};++/** One metric of the channel chart as the card draws it. */+const chartSeries = (series: ChannelMetricSeries, spec: SeriesSpec, label: string): ShareSeries => {+ const current = series.totals.current[spec.metric];+ const previous = series.totals.previous[spec.metric];++ return {+ metric: spec.metric,+ label,+ color: spec.color,+ kind: spec.type,+ axis: spec.axis,+ current: series.current.map((point) => point.values[spec.metric] ?? null),+ previous: series.previous.map((point) => point.values[spec.metric] ?? null),+ figure: formatSeriesValue(current, spec.metric),+ previousFigure: formatSeriesValue(previous, spec.metric),+ change: seriesDelta(series, spec.metric),+ };+};++/** A metric's number for the post text over one period; `missing` when it has no value there, so the text leaves it out. */+const captionNumber = (series: ChannelMetricSeries, metric: ShareSeries, period: PublicationPeriod): CaptionNumber => ({+ label: metric.label,+ figure: periodFigure(metric, period),+ missing: series.totals[period][metric.metric] == null,+});++/**+ * The channel's metrics chart exactly as the page shows it: the metrics it+ * draws, each as bars or a line on its axis, for the periods its toggle shows.+ */+export const channelChartShareOption = (+ series: ChannelMetricSeries,+ specs: SeriesSpec[],+ mode: ChartMode,+ labels: Record<SeriesMetric, string>,+ channel: string,+ range: string,+): ShareMetricOption => {+ const drawn = specs.map((spec) => chartSeries(series, spec, labels[spec.metric]));+ const period = shownPeriod(mode);+ const numbers = drawn.map((metric) => captionNumber(series, metric, period));++ return shareOption({+ key: 'channel',+ label: listOf(drawn.map((metric) => metric.label)),+ points: series[period].map((point) => ({ label: axisBucketLabel(point, series.resolution), value: null })),+ shape: 'combo',+ series: drawn,+ chartMode: mode,+ caption: summaryCaption(channel, numbers, range),+ });+};++/** Every number of the Summary in one card, as the cards print them. */+export const summaryShareOption = (+ tiles: ShareTile[],+ channel: string | null,+ range: string,+): ShareMetricOption =>+ shareOption({+ key: 'summary',+ label: trans('analytics.dashboard.summary'),+ shape: 'tiles',+ tiles,+ caption: summaryCaption(channel, tiles, range),+ });++/** The Posts card's columns over time, each split by channel in its color. */+const postsOverTime = (posts: Posts, colors: Record<string, string>): SharePoint[] =>+ posts.buckets.map((bucket) => ({+ label: bucketRangeLabel(bucket, posts.resolution),+ value: bucket.total,+ segments: posts.accounts.map((account) => ({+ value: bucket.accounts[account.social_account_key] ?? 0,+ color: colors[account.social_account_key],+ })),+ }));++const postsPoints = (posts: Posts, mode: PostsChartMode, colors: Record<string, string>): SharePoint[] => {+ if (mode === 'stacked') {+ return postsOverTime(posts, colors);+ }++ return channelRows(posts.accounts, POSTS_ROWS, colors);+};++/** The posts sent over the period the way the page's Posts card draws them in `mode`. */+export const postsShareOption = (+ posts: Posts,+ range: string,+ mode: PostsChartMode,+ colors: Record<string, string>,+): ShareMetricOption => {+ const label = trans('analytics.dashboard.posts');+ const figure = formatSeriesValue(posts.total, 'posts');++ return shareOption({+ key: 'posts',+ label,+ figure,+ points: postsPoints(posts, mode, colors),+ shape: POSTS_SHAPES[mode],+ caption: metricCaption({ metric: label, value: figure, range }),+ });+};diff --git a/resources/js/lib/labelLayout.ts b/resources/js/lib/labelLayout.tsnew file mode 100644index 000000000..a334fdf84--- /dev/null+++ b/resources/js/lib/labelLayout.ts@@ -0,0 +1,40 @@+/** How close a label may sit to its placed neighbour, `step` away from it; `edge` when it has none. */+const fromNeighbour = (placed: number[], neighbour: number | undefined, step: number, edge: number): number => {+ if (neighbour === undefined) {+ return edge;+ }++ return placed[neighbour] + step;+};++/**+ * Where a column of labels goes when each wants to sit at its own height+ * (`targets`, top to bottom in any order) but none may come closer than `gap`+ * to the next: labels that collide are pushed down, then the whole run is+ * lifted back above `bottom`. Returns the heights in the order of `targets`,+ * shrinking the gap when there are too many labels for the room.+ */+export const spreadLabels = (+ targets: number[],+ { gap, top, bottom }: { gap: number; top: number; bottom: number },+): number[] => {+ const order = targets.map((_, index) => index).sort((a, b) => targets[a] - targets[b]);+ const step = Math.min(gap, (bottom - top) / Math.max(targets.length, 1));+ const placed = [...targets];++ order.forEach((index, position) => {+ const above = order[position - 1];+ const lowest = fromNeighbour(placed, above, step, top + step / 2);++ placed[index] = Math.max(targets[index], lowest);+ });++ for (let position = order.length - 1; position >= 0; position -= 1) {+ const below = order[position + 1];+ const highest = fromNeighbour(placed, below, -step, bottom - step / 2);++ placed[order[position]] = Math.min(placed[order[position]], highest);+ }++ return placed;+};diff --git a/resources/js/lib/mcpClients.ts b/resources/js/lib/mcpClients.tsindex bad2f7f12..4f568246b 100644--- a/resources/js/lib/mcpClients.ts+++ b/resources/js/lib/mcpClients.ts@@ -1,3 +1,22 @@+import AntigravityGoogle from '@thesvg/vue/antigravity-google';+import CherryStudio from '@thesvg/vue/cherry-studio';+import Claude from '@thesvg/vue/claude';+import ClaudeCode from '@thesvg/vue/claude-code';+import CodexOpenai from '@thesvg/vue/codex-openai';+import Composio from '@thesvg/vue/composio';+import Cursor from '@thesvg/vue/cursor';+import GeminiCli from '@thesvg/vue/gemini-cli';+import Glama from '@thesvg/vue/glama';+import GrokXai from '@thesvg/vue/grok-xai';+import McpModelContextProtocol from '@thesvg/vue/mcp-model-context-protocol';+import N8n from '@thesvg/vue/n8n';+import NousresearchHermes from '@thesvg/vue/nousresearch-hermes';+import OpenWebui from '@thesvg/vue/open-webui';+import OpenaiChatgpt from '@thesvg/vue/openai-chatgpt';+import Opencode from '@thesvg/vue/opencode';+import type { Component } from 'vue';++export type McpClientId = 'claude' | 'chatgpt' | 'other';export interface McpClient {@@ -5,11 +24,8 @@ export interface McpClient {/** A brand name, or a lang key to resolve with `$t` when `labelKey` is set. */label: string;labelKey?: boolean;- /** The mark on neutral surfaces, with `logoClass` for the theme. */- logo: string;- logoClass?: string;- /** A black mark for primary buttons, inverted to white in light mode. */- monoLogo: string;+ /** The mark on neutral surfaces, in its brand color or the text color. */+ logo: Component;/** Where the user adds a connector in that client; none for a generic app. */settingsUrl?: string;/** Listed in the client's app store: the user connects from its page, nothing to paste. */@@ -32,16 +48,13 @@ export const mcpClients: McpClient[] = [{id: 'claude',label: 'Claude',- logo: '/images/ai/claude-color.svg',- monoLogo: '/images/ai/claude-mono.svg',+ logo: Claude,settingsUrl: CLAUDE_ADD_CONNECTOR_URL,},{id: 'chatgpt',label: 'ChatGPT',- logo: '/images/ai/openai.svg',- logoClass: 'dark:invert',- monoLogo: '/images/ai/openai.svg',+ logo: OpenaiChatgpt,settingsUrl: CHATGPT_APP_URL,listed: true,},@@ -52,7 +65,34 @@ export const otherMcpClient: McpClient = {id: 'other',label: 'mcp.other_clients_title',labelKey: true,- logo: '/images/ai/mcp.svg',- logoClass: 'dark:invert',- monoLogo: '/images/ai/mcp.svg',+ logo: McpModelContextProtocol,};++/** A connected app's logo, found by a word of the name the app registered with. */+export interface McpAppLogo {+ id: string;+ name: string;+ logo: Component;+ logoClass?: string;+}++/**+ * The logos of the MCP apps people connect, most specific name first+ * ("Claude Code" before Claude's own mark). An app without one shows the MCP mark.+ */+export const mcpAppLogos: McpAppLogo[] = [+ { id: 'claude-code', name: 'claude code', logo: ClaudeCode },+ { id: 'cursor', name: 'cursor', logo: Cursor, logoClass: '[&_path]:fill-current!' },+ { id: 'codex', name: 'codex', logo: CodexOpenai },+ { id: 'gemini', name: 'gemini', logo: GeminiCli },+ { id: 'antigravity', name: 'antigravity', logo: AntigravityGoogle },+ { id: 'grok', name: 'grok', logo: GrokXai },+ { id: 'n8n', name: 'n8n', logo: N8n, logoClass: '[&_path]:fill-current' },+ { id: 'open-webui', name: 'open webui', logo: OpenWebui },+ { id: 'opencode', name: 'opencode', logo: Opencode },+ { id: 'cherry-studio', name: 'cherry studio', logo: CherryStudio },+ { id: 'composio', name: 'composio', logo: Composio, logoClass: '[&_path]:fill-current [&_path]:stroke-current' },+ { id: 'glama', name: 'glama', logo: Glama },+ { id: 'hermes', name: 'hermes', logo: NousresearchHermes },+ ...mcpClients.map((client) => ({ id: client.id, name: client.label.toLowerCase(), logo: client.logo })),+];diff --git a/resources/js/lib/mediaEditor.ts b/resources/js/lib/mediaEditor.tsindex 489591772..9f117c859 100644--- a/resources/js/lib/mediaEditor.ts+++ b/resources/js/lib/mediaEditor.ts@@ -1,3 +1,4 @@+import { canvasToFile } from '@/lib/canvasFile';import {mediaRuleFor,toMediaRules,@@ -348,29 +349,12 @@ export const renderImageEdit = (const mime = resolveOutputMime(output.mimeType);- return new Promise((resolve, reject) => {- canvas.toBlob(- (blob) => {- if (!blob) {- reject(new Error('Image could not be encoded'));-- return;- }-- resolve({- file: new File(- [blob],- resolveOutputFileName(output.fileName, mime),- { type: mime },- ),- width,- height,- });- },- mime,- 0.92,- );- });+ return canvasToFile(+ canvas,+ resolveOutputFileName(output.fileName, mime),+ mime,+ 0.92,+ ).then((file) => ({ file, width, height }));};export const renderMediaEdit = (diff --git a/resources/js/lib/mediaSources/canva.ts b/resources/js/lib/mediaSources/canva.tsindex 03fa93138..974824b85 100644--- a/resources/js/lib/mediaSources/canva.ts+++ b/resources/js/lib/mediaSources/canva.ts@@ -1,15 +1,15 @@import { useHttp } from '@inertiajs/vue3';+import {+ createPopupNonce,+ openSourcePopup,+ waitForPopupResult,+} from '@/lib/mediaSources/popup';import { create, edit } from '@/routes/app/integrations/canva/designs';import { show } from '@/routes/app/integrations/canva/returns';import type { CanvaPresetOption } from '@/types';import type { MediaItem } from '@/types/media';-import {- createPopupNonce,- openSourcePopup,- waitForPopupResult,-} from './popup';export interface CanvaResult {importId: string;diff --git a/resources/js/lib/mediaSources/googleDrive.ts b/resources/js/lib/mediaSources/googleDrive.tsindex 04f184519..c6d55daed 100644--- a/resources/js/lib/mediaSources/googleDrive.ts+++ b/resources/js/lib/mediaSources/googleDrive.ts@@ -1,9 +1,9 @@import { ref } from 'vue';-import { ALLOWED_MIME_TYPES, HEIC_MIME_TYPES } from '@/lib/mediaType';-import { signInWithGoogle } from './googleSignIn';-import { loadScript } from './loadScript';+import { signInWithGoogle } from '@/lib/mediaSources/googleSignIn';+import { loadScript } from '@/lib/mediaSources/loadScript';+import { ALLOWED_MIME_TYPES, HEIC_MIME_TYPES } from '@/lib/mediaType';/** True while the Picker is on screen, so modal dialogs let it be used. */export const isGooglePickerOpen = ref(false);diff --git a/resources/js/lib/mediaSources/googlePhotos.ts b/resources/js/lib/mediaSources/googlePhotos.tsindex 618f25613..081dcc744 100644--- a/resources/js/lib/mediaSources/googlePhotos.ts+++ b/resources/js/lib/mediaSources/googlePhotos.ts@@ -1,9 +1,9 @@import { useHttp } from '@inertiajs/vue3';import dayjs from '@/dayjs';+import { signInWithGoogle } from '@/lib/mediaSources/googleSignIn';import { destroy, show } from '@/routes/app/media/google-photos/sessions';-import { signInWithGoogle } from './googleSignIn';export interface GooglePhotosPick {sessionId: string;diff --git a/resources/js/lib/mediaSources/googleSignIn.ts b/resources/js/lib/mediaSources/googleSignIn.tsindex 42cb6e671..79bae57b6 100644--- a/resources/js/lib/mediaSources/googleSignIn.ts+++ b/resources/js/lib/mediaSources/googleSignIn.ts@@ -1,13 +1,13 @@import { useHttp } from '@inertiajs/vue3';-import { start } from '@/routes/app/integrations/google';-import { claim } from '@/routes/app/integrations/google/returns';-import {createPopupNonce,openSourcePopup,waitForPopupResult,-} from './popup';+} from '@/lib/mediaSources/popup';+import { start } from '@/routes/app/integrations/google';+import { claim } from '@/routes/app/integrations/google/returns';+export type GoogleMediaSource = 'google_drive' | 'google_photos';diff --git a/resources/js/lib/publicationMetrics.ts b/resources/js/lib/publicationMetrics.tsindex 535e90d7c..917a14b38 100644--- a/resources/js/lib/publicationMetrics.ts+++ b/resources/js/lib/publicationMetrics.ts@@ -25,9 +25,8 @@ export const formatPublicationMetric = (key: string,fact: PublicationMetricFact,): string => {- if (fact.value === null) return '—';if (fact.unit === 'percent') return formatPercent(fact.value);- if (fact.unit === 'milliseconds') {+ if (fact.unit === 'milliseconds' && fact.value !== null) {const average = key.includes('average');return `${formatNumberCompact(fact.value / (average ? 1000 : 60000))} ${average ? 's' : 'min'}`;}diff --git a/resources/js/lib/shareCard/channel.ts b/resources/js/lib/shareCard/channel.tsnew file mode 100644index 000000000..517dd350d--- /dev/null+++ b/resources/js/lib/shareCard/channel.ts@@ -0,0 +1,128 @@+import { IconRosetteDiscountCheckFilled } from '@tabler/icons-vue';++import { getPlatformLogo } from '@/composables/usePlatformLogo';+import { surface } from '@/lib/shareCard/colors';+import { iconPaths } from '@/lib/shareCard/icons';+import { type ShareTint } from '@/lib/shareCard/theme';+import type { Point, ShareChannel, ShareImages, SharePoint } from '@/lib/shareCard/types';+import type { VerifiedBadge } from '@/types/social-account';++/** A channel's avatar beside its name, at most the page's 24px at 2x, with the network badge at its corner. */+export const AVATAR = { size: 48, fill: 0.8, radius: 0.25, gap: 14, badge: 0.5, verified: 0.42 };++/** The network badge's white ring (a share of the badge, never thinner than `ringMin`) and how far it sits in from the avatar's corner. */+const BADGE = { ring: 0.12, ringMin: 1.5, insetX: 0.66, insetY: 0.8 };++/** The verified rosette: how far it overhangs the avatar's top right, its white backing, and the 24px grid its path is drawn on. */+const VERIFIED = { overhang: 0.7, rise: 0.3, backing: 0.42, grid: 24 };++/** `VerifiedBadge`'s colors. */+const VERIFIED_COLORS: Record<VerifiedBadge, string> = { blue: '#1d9bf0', business: '#e2b719', government: '#829aab' };++/** A channel's own color, the one the page draws it in, else the tint's strong color. */+export const rowColor = (point: SharePoint, tint: ShareTint): string => {+ if (!point.color) {+ return tint.strong;+ }++ return point.color;+};++const avatarImage = (channel: ShareChannel, images: ShareImages): HTMLImageElement | undefined => {+ if (!channel.avatar) {+ return undefined;+ }++ return images.get(channel.avatar);+};++/** An image scaled to cover a square, cropped to its middle, inside the current clip. */+const drawCover = (context: CanvasRenderingContext2D, image: HTMLImageElement, at: Point, size: number): void => {+ const scale = size / Math.min(image.naturalWidth, image.naturalHeight);+ const width = image.naturalWidth * scale;+ const height = image.naturalHeight * scale;++ context.drawImage(image, at.x + (size - width) / 2, at.y + (size - height) / 2, width, height);+};++/** An image in a rounded square, on a white ground so a transparent logo reads on any tint. */+const paintTile = (context: CanvasRenderingContext2D, image: HTMLImageElement, at: Point, size: number): void => {+ context.save();+ context.beginPath();+ context.roundRect(at.x, at.y, size, size, size * AVATAR.radius);+ context.fillStyle = surface();+ context.fill();+ context.clip();+ drawCover(context, image, at, size);+ context.restore();+};++/** The network's logo on the avatar's bottom-end corner, ringed in white like `ChannelAvatar`'s badge. */+const paintNetworkBadge = (context: CanvasRenderingContext2D, logo: HTMLImageElement, avatar: Point, size: number): void => {+ const badge = size * AVATAR.badge;+ const ring = Math.max(BADGE.ringMin, badge * BADGE.ring);+ const at = { x: avatar.x + size - badge * BADGE.insetX, y: avatar.y + size - badge * BADGE.insetY };++ context.beginPath();+ context.roundRect(at.x - ring, at.y - ring, badge + ring * 2, badge + ring * 2, (badge + ring * 2) * AVATAR.radius);+ context.fillStyle = surface();+ context.fill();+ paintTile(context, logo, at, badge);+};++/** The verified rosette on the avatar's top-end corner, on a white disc like `VerifiedBadge`. */+const paintVerified = (context: CanvasRenderingContext2D, badge: VerifiedBadge, avatar: Point, size: number): void => {+ const mark = size * AVATAR.verified;+ const at = { x: avatar.x + size - mark * VERIFIED.overhang, y: avatar.y - mark * VERIFIED.rise };++ context.beginPath();+ context.arc(at.x + mark / 2, at.y + mark / 2, mark * VERIFIED.backing, 0, Math.PI * 2);+ context.fillStyle = surface();+ context.fill();++ context.save();+ context.translate(at.x, at.y);+ context.scale(mark / VERIFIED.grid, mark / VERIFIED.grid);+ context.fillStyle = VERIFIED_COLORS[badge];+ iconPaths(IconRosetteDiscountCheckFilled).forEach((path) => context.fill(new Path2D(path)));+ context.restore();+};++/**+ * The channel as the page's chart shows it: its avatar with the network's logo+ * at the corner and the verified mark when it has one; a channel without an+ * avatar shows the network's logo in its place.+ */+export const paintChannel = (+ context: CanvasRenderingContext2D,+ channel: ShareChannel,+ images: ShareImages,+ at: Point,+ size: number,+): void => {+ const logo = images.get(getPlatformLogo(channel.platform));+ const avatar = avatarImage(channel, images);++ if (avatar) {+ paintTile(context, avatar, at, size);++ if (logo) {+ paintNetworkBadge(context, logo, at, size);+ }+ } else if (logo) {+ paintTile(context, logo, at, size);+ }++ if (channel.verified) {+ paintVerified(context, channel.verified, at, size);+ }+};++/** The room a row's avatar takes before its bar: none when the row has no channel. */+export const avatarSpace = (point: SharePoint, avatarSize: number): number => {+ if (!point.channel) {+ return 0;+ }++ return avatarSize + AVATAR.gap;+};diff --git a/resources/js/lib/shareCard/colors.ts b/resources/js/lib/shareCard/colors.tsnew file mode 100644index 000000000..9cbbc7c23--- /dev/null+++ b/resources/js/lib/shareCard/colors.ts@@ -0,0 +1,47 @@+import { CHANGE_TOKENS } from '@/lib/shareCard/theme';++/** Every color resolved so far: the light palette never changes while the page is open. */+const resolved = new Map<string, string>();++/**+ * The value any CSS color stands for in the light theme (`var(--series-3)`,+ * `oklch(…)`, a name), as the browser computes it, even on a dark page: a+ * canvas cannot read CSS variables, and the card is always light.+ */+const resolveLightCssColor = (color: string): string => {+ const probe = document.createElement('span');++ probe.dataset.lightTheme = '';+ probe.style.color = color;+ document.body.append(probe);++ const value = getComputedStyle(probe).color;++ probe.remove();++ return value;+};++/** A color as the canvas can draw it, resolved once per page. */+export const lightColor = (color: string): string => {+ const known = resolved.get(color) ?? resolveLightCssColor(color);++ resolved.set(color, known);++ return known;+};++/** The app's text, as `--foreground`. */+export const ink = (): string => lightColor('var(--foreground)');++/** The app's secondary text, as `--muted-foreground`. */+export const muted = (): string => lightColor('var(--muted-foreground)');++/** The app's card surface, as `--card`: the panel, the logo's disc, the avatars' rings. */+export const surface = (): string => lightColor('var(--card)');++/** The charts' dashed grid, as `--border`. */+export const gridColor = (): string => lightColor('var(--border)');++/** A change's tone, as `MetricChange` draws it. */+export const changeColor = (direction: keyof typeof CHANGE_TOKENS): string => lightColor(CHANGE_TOKENS[direction]);diff --git a/resources/js/lib/shareCard/combo.ts b/resources/js/lib/shareCard/combo.tsnew file mode 100644index 000000000..3e5d12f86--- /dev/null+++ b/resources/js/lib/shareCard/combo.ts@@ -0,0 +1,389 @@+import {+ AXIS_STEPS,+ axisDomain,+ axisTickLabels,+ type ChartMode,+ chartPeriods,+ type MetricDelta,+} from '@/lib/channelMetrics';+import { ink, muted } from '@/lib/shareCard/colors';+import {+ changeWidth,+ definedRuns,+ fillBar,+ paintChange,+ paintDates,+ strokeCurve,+ strokeGrid,+ tickRoom,+ writeTick,+} from '@/lib/shareCard/draw';+import { paintIdentity } from '@/lib/shareCard/frame';+import { comboDates, shareOf } from '@/lib/shareCard/scale';+import { widest, writeText } from '@/lib/shareCard/text';+import { CHART, heading, IDENTITY, PANEL, PLOT, sans } from '@/lib/shareCard/theme';+import type { Box, Point, ShareCardOptions, ShareSeries } from '@/lib/shareCard/types';+import type { PublicationPeriod } from '@/types/analytics';++/**+ * The previous period's hatch: a tile of the color's light wash with one+ * stripe across it, turned 45°, drawn at the canvas' own pixel density so the+ * exported file's stripes stay sharp.+ */+const HATCH = { size: 10, wash: 0.12, stripe: 0.4, angle: 45 };++/**+ * How wide each bar of a `slot` is: one bar like the page's, or, with both+ * periods, two bars side by side that fill the day with a small gap between+ * them instead of halving a single bar.+ */+export const barWidth = (slot: number, bars: number, maxWidth: number = CHART.barMaxWidth): number =>+ Math.max(Math.min(barsRoom(slot, bars) / bars, maxWidth), CHART.barMinWidth);++/** The room a slot's bars share: a single bar keeps the page's padding, a pair fills the day but for the gap between them. */+const barsRoom = (slot: number, bars: number): number => {+ if (bars === 1) {+ return slot * (1 - CHART.barPadding);+ }++ return slot * (1 - COMBO.groupPadding) - COMBO.pairGap * (bars - 1);+};++/** The channel chart at 2x: its legend's label, figure and swatch, and its 16px bars. */+const COMBO = { legendGap: 56, identityShare: 0.5, labelSize: 22, figureSize: 52, figureLine: 52, swatchRise: 0.55, swatch: 18, swatchGap: 12, changeSize: 22, changeGap: 14, changeBelow: 14, groupPadding: 0.1, pairGap: 4, dash: [10, 8] };++/** The page's hatch for a previous period's bars: stripes of the color over a light wash of it. */+const hatchPattern = (context: CanvasRenderingContext2D, color: string): CanvasPattern | string => {+ const tile = document.createElement('canvas');+ const pixels = context.getTransform().a;+ const size = HATCH.size * pixels;++ tile.width = size;+ tile.height = size;++ const stripes = tile.getContext('2d');++ if (!stripes) {+ return color;+ }++ stripes.fillStyle = color;+ stripes.globalAlpha = HATCH.wash;+ stripes.fillRect(0, 0, size, size);+ stripes.globalAlpha = 1;+ stripes.fillRect(0, 0, size * HATCH.stripe, size);++ const pattern = context.createPattern(tile, 'repeat');++ if (!pattern) {+ return color;+ }++ pattern.setTransform(new DOMMatrix().rotate(HATCH.angle).scale(1 / pixels));++ return pattern;+};++/** The page's fill for a period's bars: the previous period always hatched. */+const periodFill = (context: CanvasRenderingContext2D, color: string, period: PublicationPeriod): CanvasPattern | string => {+ if (period === 'previous') {+ return hatchPattern(context, color);+ }++ return color;+};++/** The page's stroke for a period's line: the previous period always dashed. */+const periodDash = (period: PublicationPeriod): number[] => {+ if (period === 'previous') {+ return COMBO.dash;+ }++ return [];+};++/** The legend swatch's corner, and the dashed outline that stands for a previous period's line. */+const SWATCH = { radius: 4, dash: [4, 3], outline: 3 };++/** A legend swatch like the page's: solid for this period, hatched (bars) or a dashed outline (lines) for the previous one. */+const paintLegendSwatch = (context: CanvasRenderingContext2D, series: ShareSeries, color: string, period: PublicationPeriod, at: Point, size: number): void => {+ context.save();+ context.beginPath();+ context.roundRect(at.x, at.y, size, size, SWATCH.radius);++ if (period === 'previous' && series.kind === 'line') {+ context.setLineDash(SWATCH.dash);+ context.lineWidth = SWATCH.outline;+ context.strokeStyle = color;+ context.stroke();+ context.restore();++ return;+ }++ context.fillStyle = periodFill(context, color, period);+ context.fill();+ context.restore();+};++/** What a legend item prints in a chart mode: the previous period alone in Comparison, both periods in Both. */+const legendEntries = (series: ShareSeries, mode: ChartMode): { figure: string; period: PublicationPeriod }[] =>+ chartPeriods(mode).map((period) => ({ figure: periodFigure(series, period), period }));++/** A metric's figure over one period. */+export const periodFigure = (series: ShareSeries, period: PublicationPeriod): string => {+ if (period === 'previous') {+ return series.previousFigure;+ }++ return series.figure;+};++/** A legend figure's ink: the previous period's is muted next to the current one in Both, like the page's. */+const legendFigureColor = (period: PublicationPeriod, mode: ChartMode): string => {+ if (period === 'previous' && mode === 'both') {+ return muted();+ }++ return ink();+};++/** How wide a legend item's change is drawn; none without one. */+const legendChangeWidth = (context: CanvasRenderingContext2D, change: MetricDelta | null, size: number): number => {+ if (!change) {+ return 0;+ }++ return changeWidth(context, change, size);+};++/** The change a legend item shows: none in Comparison, which shows the previous period itself. */+const legendChange = (series: ShareSeries, mode: ChartMode): MetricDelta | null => {+ if (mode === 'previous') {+ return null;+ }++ return series.change;+};++/** One metric of the legend laid out at a size: its period figures, their widths, its change and how wide it all is. */+type LegendItem = {+ series: ShareSeries;+ entries: { figure: string; period: PublicationPeriod }[];+ entryWidths: number[];+ change: MetricDelta | null;+ width: number;+};++/** The legend's fonts and gaps at `fit` of their full size. */+const legendSizes = (fit: number): { size: (value: number) => number; labelFont: string; figureFont: string } => ({+ size: (value: number): number => value * fit,+ labelFont: sans(500, COMBO.labelSize * fit),+ figureFont: heading(500, COMBO.figureSize * fit),+});++/** The legend's items at `fit` of their full size, measured but not drawn. */+const legendLayout = (context: CanvasRenderingContext2D, options: ShareCardOptions, fit: number): LegendItem[] => {+ const { size, labelFont, figureFont } = legendSizes(fit);++ return options.series.map((series) => {+ const entries = legendEntries(series, options.chartMode);+ const change = legendChange(series, options.chartMode);++ context.font = figureFont;+ const entryWidths = entries.map((entry) => size(COMBO.swatch + COMBO.swatchGap) + context.measureText(entry.figure).width);+ const figuresWidth = entryWidths.reduce((total, width) => total + width, 0) + size(COMBO.changeGap) * (entries.length - 1);+ const changeRoom = legendChangeWidth(context, change, size(COMBO.changeSize));+ context.font = labelFont;++ return { series, entries, entryWidths, change, width: Math.max(context.measureText(series.label).width, figuresWidth, changeRoom) };+ });+};++/** How wide the legend's items run side by side, with the gaps between them. */+const legendWidth = (items: LegendItem[], fit: number): number =>+ items.reduce((total, item) => total + item.width, 0) + COMBO.legendGap * fit * Math.max(items.length - 1, 0);++/**+ * The page's legend on the headline's right: each metric's name over its+ * swatches and figures, its change under them, at `fit` of its full size.+ * Returns how wide it is.+ */+const paintComboLegend = (context: CanvasRenderingContext2D, options: ShareCardOptions, right: number, top: number, fit: number): number => {+ const { size, labelFont, figureFont } = legendSizes(fit);+ const items = legendLayout(context, options, fit);+ let edge = right;++ [...items].reverse().forEach((item) => {+ const left = edge - item.width;+ const baseline = top + size(COMBO.labelSize + COMBO.figureLine);+ let cursor = left;++ writeText(context, item.series.label, { x: left, y: top + size(COMBO.labelSize) }, { font: labelFont, color: muted() });++ item.entries.forEach((entry, position) => {+ paintLegendSwatch(context, item.series, item.series.color, entry.period, { x: cursor, y: baseline - size(COMBO.figureSize * COMBO.swatchRise) }, size(COMBO.swatch));+ writeText(context, entry.figure, { x: cursor + size(COMBO.swatch + COMBO.swatchGap), y: baseline }, { font: figureFont, color: legendFigureColor(entry.period, options.chartMode) });+ cursor += item.entryWidths[position] + size(COMBO.changeGap);+ });++ if (item.change) {+ paintChange(context, item.change, { x: left, y: baseline + size(COMBO.changeBelow) }, size(COMBO.changeSize), 'left');+ }++ edge = left - size(COMBO.legendGap);+ });++ return legendWidth(items, fit);+};++/**+ * The legend's size and the room it leaves the channel's name and period: the+ * legend keeps its full size while they fit beside it, else it shrinks so they+ * do. The name keeps at most `COMBO.identityShare` of the headline, so the+ * legend never vanishes, and that room is given to it whole, so a name that+ * fits is never cut by a rounding at the edge.+ */+const legendFit = (context: CanvasRenderingContext2D, options: ShareCardOptions, headline: number): { fit: number; identity: number } => {+ const identity = Math.min(+ Math.max(+ widest(context, [options.subject], heading(600, IDENTITY.nameSize)),+ widest(context, [options.range], sans(500, IDENTITY.detailSize)),+ ),+ headline * COMBO.identityShare,+ );+ const full = legendWidth(legendLayout(context, options, 1), 1);+ const room = headline - identity - COMBO.legendGap;++ return { fit: Math.min(1, room / full), identity };+};++/** The metrics drawn on an axis of the channel chart. */+const axisSeries = (options: ShareCardOptions, axis: ShareSeries['axis']): ShareSeries[] =>+ options.series.filter((series) => series.axis === axis);++/** An axis' domain over the periods shown, by the page's rule. */+const comboDomain = (series: ShareSeries[], periods: PublicationPeriod[]): { min: number; max: number } | null =>+ axisDomain(+ series.map((metric) => metric.metric),+ series.flatMap((metric) => periods.flatMap((period) => metric[period].filter((value): value is number => value !== null))),+ );++/** A period's values over the chart's days only, like the page, which lays the previous period over the current one's days. */+const shownValues = (series: ShareSeries, period: PublicationPeriod, days: number): (number | null)[] =>+ series[period].slice(0, days);++/** An axis' domain, or 0 to 1 for an axis no metric uses, so a value there still has a place. */+const domainOrUnit = (domain: { min: number; max: number } | null): { min: number; max: number } => {+ if (!domain) {+ return { min: 0, max: 1 };+ }++ return domain;+};++/** An axis' tick labels, bottom up; none when no metric uses it. */+const axisLabels = (options: ShareCardOptions, domain: { min: number; max: number } | null, axis: ShareSeries['axis']): string[] => {+ if (!domain) {+ return [];+ }++ return axisTickLabels(domain, axisSeries(options, axis).map((series) => series.metric));+};++/** The room the right axis' labels take, measured like the left one's; none when no metric uses it. */+const rightAxisRoom = (context: CanvasRenderingContext2D, labels: string[]): number => {+ if (labels.length === 0) {+ return 0;+ }++ return tickRoom(context, labels);+};++/** Where an axis' tick labels sit: right-aligned before the plot on the left, left-aligned after it on the right. */+const AXIS_SIDES: Record<ShareSeries['axis'], { align: 'left' | 'right'; edge: (plot: Box) => number; direction: number }> = {+ left: { align: 'right', edge: (plot) => plot.x, direction: -1 },+ right: { align: 'left', edge: (plot) => plot.x + plot.width, direction: 1 },+};++/**+ * The channel chart as the page shows it: its metrics' bars and lines on a+ * left and a right axis, for the periods its toggle shows, the previous+ * period's bars hatched and its lines dashed, under the page's legend. The+ * legend names the metrics, so the line under the name keeps only the period.+ */+export const paintCombo = (context: CanvasRenderingContext2D, options: ShareCardOptions, panel: Box): void => {+ const left = panel.x + PANEL.padding;+ const right = panel.x + panel.width - PANEL.padding;+ const legend = legendFit(context, options, right - left);+ const drawnLegend = paintComboLegend(context, options, right, panel.y + IDENTITY.top, legend.fit);++ paintIdentity(context, options.subject, options.range, { x: left, y: panel.y + IDENTITY.top }, Math.max(right - left - drawnLegend - COMBO.legendGap, legend.identity));++ const periods = chartPeriods(options.chartMode);+ const domains = {+ left: comboDomain(axisSeries(options, 'left'), periods),+ right: comboDomain(axisSeries(options, 'right'), periods),+ };+ const labels = { left: axisLabels(options, domains.left, 'left'), right: axisLabels(options, domains.right, 'right') };+ const leftRoom = tickRoom(context, labels.left);+ const plot = {+ x: left + leftRoom,+ y: panel.y + PLOT.top,+ width: right - left - leftRoom - rightAxisRoom(context, labels.right),+ height: panel.height - PLOT.top - PLOT.bottom,+ };+ const count = Math.max(options.points.length, 1);+ const slot = plot.width / count;+ const x = (index: number): number => plot.x + slot * (index + 0.5);+ const y = (axis: 'left' | 'right', value: number): number => {+ const domain = domainOrUnit(domains[axis]);++ return plot.y + plot.height - shareOf(value, domain.min, domain.max) * plot.height;+ };+ const gridY = (step: number): number => plot.y + plot.height - (step / AXIS_STEPS) * plot.height;++ const steps = Array.from({ length: AXIS_STEPS + 1 }, (_, step) => step);++ strokeGrid(context, steps.map((step) => [{ x: plot.x, y: gridY(step) }, { x: plot.x + plot.width, y: gridY(step) }]));++ (['left', 'right'] as const).forEach((axis) => {+ const side = AXIS_SIDES[axis];++ labels[axis].forEach((label, step) => {+ writeTick(context, label, { x: side.edge(plot) + side.direction * PLOT.tickGap, y: gridY(step) }, { align: side.align, baseline: 'middle' });+ });+ });++ const width = barWidth(slot, periods.length);+ const barStep = width + COMBO.pairGap * (periods.length - 1);++ options.series.filter((series) => series.kind === 'bar').forEach((series) => {+ const color = series.color;+ const zero = y(series.axis, Math.max(0, domainOrUnit(domains[series.axis]).min));++ periods.forEach((period, position) => {+ context.fillStyle = periodFill(context, color, period);++ shownValues(series, period, count).forEach((value, index) => {+ if (value === null || value === 0) {+ return;+ }++ const middle = x(index) + (position - (periods.length - 1) / 2) * barStep;++ fillBar(context, zero, y(series.axis, value), middle, width, false);+ });+ });+ });++ options.series.filter((series) => series.kind === 'line').forEach((series) => {+ periods.forEach((period) => {+ definedRuns(shownValues(series, period, count), x, (value) => y(series.axis, value)).forEach((run) => {+ strokeCurve(context, run, series.color, periodDash(period));+ });+ });+ });++ paintDates(context, options.points, comboDates(count), x, plot);+};diff --git a/resources/js/lib/shareCard/curve.ts b/resources/js/lib/shareCard/curve.tsnew file mode 100644index 000000000..58e9ecaf9--- /dev/null+++ b/resources/js/lib/shareCard/curve.ts@@ -0,0 +1,86 @@+import type { Point } from '@/lib/shareCard/types';++/** d3's `curveMonotoneX`: each segment's handles sit a third along it, and a middle tangent takes at most half the blended slope. */+const MONOTONE = { handle: 3, blend: 0.5 };++/** The sign d3 gives a slope: zero counts as positive. */+const slopeSign = (slope: number): number => {+ if (slope < 0) {+ return -1;+ }++ return 1;+};++/** d3's `slope3`: a middle point's tangent, flat at a peak or a dip, never steeper than its neighbours allow. */+const innerTangent = (before: Point, point: Point, after: Point): number => {+ const left = point.x - before.x;+ const right = after.x - point.x;+ const leftSlope = (point.y - before.y) / left;+ const rightSlope = (after.y - point.y) / right;+ const weighted = (leftSlope * right + rightSlope * left) / (left + right);++ return (slopeSign(leftSlope) + slopeSign(rightSlope)) * Math.min(Math.abs(leftSlope), Math.abs(rightSlope), MONOTONE.blend * Math.abs(weighted)) || 0;+};++/** d3's `slope2`: an end point's tangent, from its segment's slope and the tangent at the segment's other end. */+const endTangent = (from: Point, to: Point, neighbour: number): number => {+ const width = to.x - from.x;++ if (!width) {+ return neighbour;+ }++ return (MONOTONE.handle * (to.y - from.y) / width - neighbour) / 2;+};++/** The line through the points as a monotone cubic, d3's `curveMonotoneX` the page's charts use. */+export const traceMonotone = (context: CanvasRenderingContext2D, points: Point[]): void => {+ context.beginPath();++ if (points.length === 0) {+ return;+ }++ context.moveTo(points[0].x, points[0].y);++ if (points.length < 3) {+ points.slice(1).forEach((point) => context.lineTo(point.x, point.y));++ return;+ }++ const last = points.length - 1;+ const inner = points.map((point, index) => {+ if (index === 0 || index === last) {+ return 0;+ }++ return innerTangent(points[index - 1], point, points[index + 1]);+ });+ const tangents = inner.map((tangent, index) => {+ if (index === 0) {+ return endTangent(points[0], points[1], inner[1]);+ }++ if (index === last) {+ return endTangent(points[last - 1], points[last], inner[last - 1]);+ }++ return tangent;+ });++ points.slice(1).forEach((point, index) => {+ const previous = points[index];+ const third = (point.x - previous.x) / MONOTONE.handle;++ context.bezierCurveTo(+ previous.x + third,+ previous.y + third * tangents[index],+ point.x - third,+ point.y - third * tangents[index + 1],+ point.x,+ point.y,+ );+ });+};diff --git a/resources/js/lib/shareCard/draw.ts b/resources/js/lib/shareCard/draw.tsnew file mode 100644index 000000000..82fa14471--- /dev/null+++ b/resources/js/lib/shareCard/draw.ts@@ -0,0 +1,199 @@+import { type Icon, IconMinus, IconTrendingDown, IconTrendingUp } from '@tabler/icons-vue';++import type { MetricDelta } from '@/lib/channelMetrics';+import { changeColor, gridColor, muted } from '@/lib/shareCard/colors';+import { traceMonotone } from '@/lib/shareCard/curve';+import { iconPaths } from '@/lib/shareCard/icons';+import { type TextStyle, widest, writeText } from '@/lib/shareCard/text';+import { CHANGE_TOKENS, CHART, PLOT, sans } from '@/lib/shareCard/theme';+import type { Box, Point, SharePoint } from '@/lib/shareCard/types';+import { distinctCountLabels } from '@/lib/utils';++export const strokeLine = (context: CanvasRenderingContext2D, from: Point, to: Point): void => {+ context.beginPath();+ context.moveTo(from.x, from.y);+ context.lineTo(to.x, to.y);+ context.stroke();+};++/** `MetricChange`'s trend icon: its size and the gap after it as shares of the label's, and its stroke on the 24px icon grid. */+export const CHANGE_ICON = { scale: 1.15, gap: 0.3, stroke: 2.5, grid: 24 };++/** The trending icons `MetricChange` draws for each tone. */+const CHANGE_ICONS: Record<keyof typeof CHANGE_TOKENS, Icon> = {+ up: IconTrendingUp,+ down: IconTrendingDown,+ flat: IconMinus,+};++/** How far an anchor sits from a change's left edge, as a share of its width. */+const ALIGN_SHIFT = { left: 0, right: 1 } as const;++/** Which way a change points: up for a gain, down for a loss, flat when nothing moved. */+const changeDirection = (change: MetricDelta): keyof typeof CHANGE_TOKENS => {+ if (change.value > 0) {+ return 'up';+ }++ if (change.value < 0) {+ return 'down';+ }++ return 'flat';+};++/** How wide a change is drawn at `size`: its trend icon, a gap, then its label. */+export const changeWidth = (context: CanvasRenderingContext2D, change: MetricDelta, size: number): number => {+ context.font = sans(600, size);++ return size * (CHANGE_ICON.scale + CHANGE_ICON.gap) + context.measureText(change.label).width;+};++/** The change as the page's `MetricChange`: the trending icon and the label, in the tone's color. */+export const paintChange = (+ context: CanvasRenderingContext2D,+ change: MetricDelta,+ anchor: Point,+ size: number,+ align: 'left' | 'right',+): void => {+ const direction = changeDirection(change);+ const color = changeColor(direction);+ const font = sans(600, size);+ const icon = size * CHANGE_ICON.scale;+ const gap = size * CHANGE_ICON.gap;+ const left = anchor.x - changeWidth(context, change, size) * ALIGN_SHIFT[align];++ context.save();+ context.translate(left, anchor.y);+ context.scale(icon / CHANGE_ICON.grid, icon / CHANGE_ICON.grid);+ context.strokeStyle = color;+ context.lineWidth = CHANGE_ICON.stroke;+ context.lineCap = 'round';+ context.lineJoin = 'round';+ iconPaths(CHANGE_ICONS[direction]).forEach((path) => context.stroke(new Path2D(path)));+ context.restore();++ writeText(context, change.label, { x: left + icon + gap, y: anchor.y + icon / 2 + 1 }, { font, color, baseline: 'middle' });+};++/** How much room tick labels take beside the plot: their widest and the gap to the plot, at least the gutter's width. */+export const tickRoom = (context: CanvasRenderingContext2D, labels: string[]): number =>+ Math.max(PLOT.gutter, widest(context, labels, CHART.tickFont) + PLOT.tickGap);++/** The plot moved past its value ticks' labels, so a long one ("1,234,560") never runs over the panel's edge. */+export const besideTicks = (context: CanvasRenderingContext2D, plot: Box, labels: string[]): Box => {+ const extra = tickRoom(context, labels) - PLOT.gutter;++ return { ...plot, x: plot.x + extra, width: plot.width - extra };+};++/** The page's dashed grid lines. */+export const strokeGrid = (context: CanvasRenderingContext2D, lines: [Point, Point][]): void => {+ context.save();+ context.setLineDash(CHART.gridDash);+ context.lineWidth = CHART.gridWidth;+ context.strokeStyle = gridColor();+ lines.forEach((line) => strokeLine(context, ...line));+ context.restore();+};++/** A muted tick label of an axis. */+export const writeTick = (context: CanvasRenderingContext2D, label: string, at: Point, style: Pick<TextStyle, 'align' | 'baseline'>): void => {+ writeText(context, label, at, { font: CHART.tickFont, color: muted(), ...style });+};++/** The dashed value grid: one line per tick, with the tick's value at `label`. */+export const paintGrid = (+ context: CanvasRenderingContext2D,+ ticks: number[],+ line: (value: number) => [Point, Point],+ label: (value: number) => Point,+ style: Pick<TextStyle, 'align' | 'baseline'>,+): void => {+ const labels = distinctCountLabels(ticks);++ strokeGrid(context, ticks.map(line));+ ticks.forEach((value, index) => writeTick(context, labels[index], label(value), style));+};++/** The radius at a bar's low-coordinate edge and at its high one: only the data end is round. */+const dataEndRadii = (start: number, end: number, radius: number): [number, number] => {+ if (end > start) {+ return [0, radius];+ }++ return [radius, 0];+};++/**+ * A bar from the baseline (`start`) to its value (`end`) along its axis,+ * centred on `middle` across it and rounded only at the data end, like+ * unovis' `roundedCorners`.+ */+export const fillBar = (+ context: CanvasRenderingContext2D,+ start: number,+ end: number,+ middle: number,+ thickness: number,+ horizontal: boolean,+): void => {+ const length = Math.abs(end - start);+ const radius = Math.min(thickness * CHART.barRoundness, length);+ const [low, high] = dataEndRadii(start, end, radius);++ context.beginPath();++ if (horizontal) {+ context.roundRect(Math.min(start, end), middle - thickness / 2, length, thickness, [low, high, high, low]);+ } else {+ context.roundRect(middle - thickness / 2, Math.min(start, end), thickness, length, [low, low, high, high]);+ }++ context.fill();+};++/** The page's 2px monotone line through `points`, dashed when `dash` says so. */+export const strokeCurve = (context: CanvasRenderingContext2D, points: Point[], color: string, dash: number[] = []): void => {+ context.save();+ context.strokeStyle = color;+ context.lineWidth = CHART.lineWidth;+ context.lineJoin = 'round';+ context.lineCap = 'round';+ context.setLineDash(dash);+ traceMonotone(context, points);+ context.stroke();+ context.restore();+};++/**+ * A line's runs of points with a value, where the plot draws them: a missing+ * value breaks the line there, as unovis' line does on the page.+ */+export const definedRuns = (values: (number | null)[], x: (index: number) => number, y: (value: number) => number): Point[][] =>+ values+ .reduce<Point[][]>(+ (runs, value, index) => {+ if (value === null) {+ return [...runs, []];+ }++ runs[runs.length - 1].push({ x: x(index), y: y(value) });++ return runs;+ },+ [[]],+ )+ .filter((run) => run.length > 0);++/** The dates of the points at `indexes`, under the plot. */+export const paintDates = (+ context: CanvasRenderingContext2D,+ points: SharePoint[],+ indexes: number[],+ x: (index: number) => number,+ plot: Box,+): void => {+ indexes.forEach((index) => writeTick(context, points[index]?.label ?? '', { x: x(index), y: plot.y + plot.height + PLOT.dates }, { align: 'center' }));+};diff --git a/resources/js/lib/shareCard/frame.ts b/resources/js/lib/shareCard/frame.tsnew file mode 100644index 000000000..dca450777--- /dev/null+++ b/resources/js/lib/shareCard/frame.ts@@ -0,0 +1,189 @@+import { ink, muted, surface } from '@/lib/shareCard/colors';+import { paintChange } from '@/lib/shareCard/draw';+import { ellipsise, writeText } from '@/lib/shareCard/text';+import {+ BORDER,+ heading,+ HEADLINE,+ IDENTITY,+ PANEL,+ PLOT,+ sans,+ SHARE_CARD_SIZE,+ type ShareTint,+} from '@/lib/shareCard/theme';+import type { Box, Point, ShareCardOptions, SharePoint } from '@/lib/shareCard/types';++/** The home hero's dot grid in the ground's corners, fading toward the middle. */+const DOTS = { gap: 24, radius: 1.4, opacity: 0.22, reach: 0.38 };++/** The covers' background: the flat tint with the dot grid in the top-right and bottom-left corners. */+const drawGround = (context: CanvasRenderingContext2D, tint: ShareTint): void => {+ const { width, height } = SHARE_CARD_SIZE;+ const reach = Math.hypot(width, height) * DOTS.reach;++ context.fillStyle = tint.ground;+ context.fillRect(0, 0, width, height);++ for (let y = DOTS.gap / 2; y < height; y += DOTS.gap) {+ for (let x = DOTS.gap / 2; x < width; x += DOTS.gap) {+ const corner = Math.min(Math.hypot(width - x, y), Math.hypot(x, height - y));+ const strength = 1 - corner / reach;++ if (strength <= 0) {+ continue;+ }++ context.fillStyle = `rgba(10, 10, 10, ${DOTS.opacity * strength})`;+ context.beginPath();+ context.arc(x, y, DOTS.radius, 0, Math.PI * 2);+ context.fill();+ }+ }+};++/** Each tint's ground, drawn once and kept until a canvas of another pixel density asks for it. */+const grounds = new Map<string, { pixels: number; canvas: HTMLCanvasElement }>();++/** The ground for `tint` at the canvas' pixel density, drawn the first time it is asked for at that density. */+const groundFor = (tint: ShareTint, pixels: number): HTMLCanvasElement | null => {+ const known = grounds.get(tint.key);++ if (known && known.pixels === pixels) {+ return known.canvas;+ }++ const canvas = document.createElement('canvas');+ const context = canvas.getContext('2d');++ if (!context) {+ return null;+ }++ canvas.width = SHARE_CARD_SIZE.width * pixels;+ canvas.height = SHARE_CARD_SIZE.height * pixels;+ context.setTransform(pixels, 0, 0, pixels, 0, 0);+ drawGround(context, tint);+ grounds.set(tint.key, { pixels, canvas });++ return canvas;+};++/** Paints the tint and its dots under the panel, from the drawn ground when the browser can keep one. */+export const paintGround = (context: CanvasRenderingContext2D, tint: ShareTint): void => {+ const ground = groundFor(tint, context.getTransform().a);++ if (!ground) {+ drawGround(context, tint);++ return;+ }++ context.drawImage(ground, 0, 0, SHARE_CARD_SIZE.width, SHARE_CARD_SIZE.height);+};++/** A white surface with the ink border and no shadow. */+export const paintPanel = (context: CanvasRenderingContext2D): Box => {+ const { width, height } = SHARE_CARD_SIZE;+ const panel = {+ x: PANEL.x,+ y: PANEL.y,+ width: width - PANEL.x * 2,+ height: height - PANEL.y - PANEL.band,+ };++ context.beginPath();+ context.roundRect(panel.x, panel.y, panel.width, panel.height, PANEL.radius);+ context.fillStyle = surface();+ context.fill();+ context.strokeStyle = ink();+ context.lineWidth = BORDER;+ context.stroke();++ return panel;+};++/** The grid the logo's paths are drawn on. */+const LOGO_GRID = 410;++/** The TryPost mark, the four quarters of `AppLogo.vue`. */+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'],+ ['M0 0V300.264L205 81.3178L281.138 0H0Z', '#FFCC33'],+ ['M0 109.736V410H128.862L205 328.682L0 109.736Z', '#F39200'],+ ];++ context.save();+ context.beginPath();+ context.arc(at.x + size / 2, at.y + size / 2, size / 2, 0, Math.PI * 2);+ context.clip();+ context.fillStyle = surface();+ context.fillRect(at.x, at.y, size, size);+ context.translate(at.x, at.y);+ context.scale(size / LOGO_GRID, size / LOGO_GRID);++ for (const [path, color] of quarters) {+ context.fillStyle = color;+ context.fill(new Path2D(path));+ }++ context.restore();+};++/** The signature's logo, the gap after it and its text size. */+const MARK = { logo: 32, gap: 12, size: 24 };++/** The signature, centred in the band under the panel: whoever sees the post sees where it came from. */+export const paintMark = (context: CanvasRenderingContext2D, mark: string): void => {+ const font = sans(600, MARK.size);+ const centre = SHARE_CARD_SIZE.height - PANEL.band / 2;++ context.font = font;++ const start = (SHARE_CARD_SIZE.width - (MARK.logo + MARK.gap + context.measureText(mark).width)) / 2;++ paintLogo(context, { x: start, y: centre - MARK.logo / 2 }, MARK.logo);+ writeText(context, mark, { x: start + MARK.logo + MARK.gap, y: centre + 1 }, { font, color: ink(), baseline: 'middle' });+};++/** The workspace or channel name, with what and when under it. */+export const paintIdentity = (+ context: CanvasRenderingContext2D,+ subject: string,+ detail: string,+ at: Point,+ limit: number,+): void => {+ const nameFont = heading(600, IDENTITY.nameSize);+ const detailFont = sans(500, IDENTITY.detailSize);++ writeText(context, ellipsise(context, subject, nameFont, limit), { x: at.x, y: at.y + IDENTITY.name }, { font: nameFont, color: ink() });+ writeText(context, ellipsise(context, detail, detailFont, limit), { x: at.x, y: at.y + IDENTITY.detail }, { font: detailFont, color: muted() });+};++/** The subject and what and when on the left, the figure with its change on the right. */+export const paintHeadline = (context: CanvasRenderingContext2D, options: ShareCardOptions, panel: Box): void => {+ const left = panel.x + PANEL.padding;+ const right = panel.x + panel.width - PANEL.padding;+ const limit = panel.width - PANEL.padding * 2 - HEADLINE.reserve;++ paintIdentity(context, options.subject, `${options.label} · ${options.range}`, { x: left, y: panel.y + IDENTITY.top }, limit);+ writeText(context, options.figure, { x: right, y: panel.y + HEADLINE.figure }, { font: heading(500, HEADLINE.figureSize), color: ink(), align: 'right' });++ if (options.change) {+ paintChange(context, options.change, { x: right, y: panel.y + HEADLINE.change }, HEADLINE.changeSize, 'right');+ }+};++/** The plot under the headline, past the gutter for the value ticks. */+export const headlinePlot = (panel: Box): Box => ({+ x: panel.x + PANEL.padding + PLOT.gutter,+ y: panel.y + PLOT.top,+ width: panel.width - PANEL.padding * 2 - PLOT.gutter,+ height: panel.height - PLOT.top - PLOT.bottom,+});++/** The values of the points that have one. */+export const pointValues = (points: SharePoint[]): number[] => points.flatMap((point) => (point.value === null ? [] : [point.value]));diff --git a/resources/js/lib/shareCard/icons.ts b/resources/js/lib/shareCard/icons.tsnew file mode 100644index 000000000..f1ec18313--- /dev/null+++ b/resources/js/lib/shareCard/icons.ts@@ -0,0 +1,10 @@+import type { Icon } from '@tabler/icons-vue';+import type { VNode } from 'vue';++/** 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;+ const children = svg.children as VNode[];++ return children.filter((child) => child.type === 'path').map((child) => child.props?.d);+};diff --git a/resources/js/lib/shareCard/images.ts b/resources/js/lib/shareCard/images.tsnew file mode 100644index 000000000..fef00539b--- /dev/null+++ b/resources/js/lib/shareCard/images.ts@@ -0,0 +1,120 @@+import { getPlatformLogo } from '@/composables/usePlatformLogo';+import { heading, sans } from '@/lib/shareCard/theme';+import type { ShareCardOptions, ShareChannel, ShareImages, ShareMetricOption } from '@/lib/shareCard/types';++/**+ * How long a font or an image may take before the card draws without it, and+ * how long a failed image is kept as failed before the next card asks again:+ * a stalled request never holds the preview, and a missing one is not asked+ * for again on every repaint.+ */+const LOADING = { timeoutMs: 4000, retryAfterMs: 30000 };++/** The faces the card writes in. */+const FACES = [sans(500, 24), sans(600, 24), heading(500, 64), heading(600, 36)];++/** `promise`, or `fallback` once `ms` pass without it settling. */+const withTimeout = <Value>(promise: Promise<Value>, ms: number, fallback: Value): Promise<Value> =>+ Promise.race([promise, new Promise<Value>((resolve) => window.setTimeout(() => resolve(fallback), ms))]);++/** What an option writes, so the fonts load the glyphs it needs ("ł", "ş"), not only the Latin ones. */+const optionText = (option: Partial<ShareCardOptions> & Pick<ShareMetricOption, 'points' | 'lines'>): string =>+ [+ option.subject,+ option.range,+ option.mark,+ option.label,+ option.figure,+ ...option.points.flatMap((point) => [point.label, point.figure]),+ ...option.lines.map((line) => line.figure),+ ...(option.series ?? []).flatMap((series) => [series.label, series.figure, series.previousFigure]),+ ...(option.tiles ?? []).flatMap((tile) => [tile.label, tile.figure]),+ ]+ .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> => {+ if (!('fonts' in document)) {+ return;+ }++ await Promise.all(+ FACES.map((face) => withTimeout(document.fonts.load(face, text).catch(() => []), LOADING.timeoutMs, [])),+ );+};++/** Each image once per page: the preview repaints on every tint or metric change. */+const loadedImages = new Map<string, Promise<HTMLImageElement | null>>();++/** An image ready to draw, or null when it cannot load in time, so a missing or slow avatar never stops the card. */+const loadImage = (url: string): Promise<HTMLImageElement | null> => {+ const cached = loadedImages.get(url);++ if (cached) {+ return cached;+ }++ const image = new Image();++ image.crossOrigin = 'anonymous';+ image.src = url;++ const loading = withTimeout(+ image.decode().then(+ () => image,+ () => null,+ ),+ LOADING.timeoutMs,+ null,+ ).then((loaded) => {+ if (!loaded) {+ window.setTimeout(() => loadedImages.delete(url), LOADING.retryAfterMs);+ }++ return loaded;+ });++ loadedImages.set(url, loading);++ return loading;+};++/** A channel's network logo and, when it has one, its avatar. */+const channelImageUrls = (channel: ShareChannel): string[] => {+ const logo = getPlatformLogo(channel.platform);++ if (!channel.avatar) {+ return [logo];+ }++ return [channel.avatar, logo];+};++type LoadedImage = { url: string; image: HTMLImageElement };++/** The channels an option draws, as rows or as lines. */+const optionChannels = (option: Pick<ShareMetricOption, 'points' | 'lines'>): ShareChannel[] =>+ [...option.points.map((point) => point.channel), ...option.lines.map((line) => line.channel)].filter(+ (channel): channel is ShareChannel => channel !== undefined,+ );++/**+ * The fonts and images a card draws, loaded once per page: called while the+ * page is idle, it warms them so the first preview paints at once.+ */+export const prepareShareCard = async (+ option: Partial<ShareCardOptions> & Pick<ShareMetricOption, 'points' | 'lines'>,+): Promise<ShareImages> => {+ const urls = [...new Set(optionChannels(option).flatMap(channelImageUrls))];+ const [, images] = await Promise.all([+ loadFonts(optionText(option)),+ Promise.all(urls.map(async (url) => ({ url, image: await loadImage(url) }))),+ ]);++ return new Map(+ images+ .filter((loaded): loaded is LoadedImage => loaded.image !== null)+ .map(({ url, image }) => [url, image]),+ );+};diff --git a/resources/js/lib/shareCard/index.ts b/resources/js/lib/shareCard/index.tsnew file mode 100644index 000000000..1bf9eed4f--- /dev/null+++ b/resources/js/lib/shareCard/index.ts@@ -0,0 +1,114 @@+/**+ * The Insights share card: a chart or a headline number drawn on a canvas, to+ * download or post. Drawn rather than captured from the DOM, so it looks the+ * 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`)+ * on the shared frame, text, drawing and channel helpers; `scale` and `curve`+ * hold the pure arithmetic the painters share with the page's charts.+ */++import date from '@/date';+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 { prepareShareCard } from '@/lib/shareCard/images';+import { paintLinesCard } from '@/lib/shareCard/lines';+import { paintRowsCard } from '@/lib/shareCard/rows';+import { paintStackedCard } from '@/lib/shareCard/stacked';+import { paintSummary } from '@/lib/shareCard/summary';+import { SHARE_CARD_SIZE, SHARE_EXPORT_SCALE } from '@/lib/shareCard/theme';+import type { Box, ShareCardOptions, ShareImages, ShareShape } from '@/lib/shareCard/types';++export { periodFigure } from '@/lib/shareCard/combo';+export { prepareShareCard } from '@/lib/shareCard/images';+export { SHARE_CARD_SIZE, SHARE_TINTS, type ShareTint } from '@/lib/shareCard/theme';+export type {+ ShareCardOptions,+ ShareChannel,+ ShareLine,+ ShareMetricOption,+ SharePoint,+ ShareSeries,+ ShareShape,+ ShareTile,+} from '@/lib/shareCard/types';++/** What draws each shape inside the panel. */+const PAINTERS: Record<ShareShape, (context: CanvasRenderingContext2D, options: ShareCardOptions, images: ShareImages, panel: Box) => void> = {+ lines: paintLinesCard,+ rows: paintRowsCard,+ 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),+};++/**+ * The card with every color as the browser computes it: a canvas cannot read+ * CSS variables, so the theme's colors are resolved once before painting.+ */+const withResolvedColors = (options: ShareCardOptions): ShareCardOptions => {++ return {+ ...options,+ points: options.points.map((point) => ({+ ...point,+ color: point.color && lightColor(point.color),+ segments: point.segments?.map((segment) => ({ ...segment, color: lightColor(segment.color) })),+ })),+ lines: options.lines.map((line) => ({ ...line, color: lightColor(line.color) })),+ series: options.series.map((series) => ({ ...series, color: lightColor(series.color) })),+ };+};++/**+ * The direction the reader's language writes in. The card keeps its layout+ * left to right in every language (every text is placed by a side, never by+ * `start`), and each text runs in this direction, so an Arabic line with a+ * Latin name reads in the right order, in the preview and the file alike.+ */+const readingDirection = (): CanvasDirection => {+ if (document.documentElement.dir === 'rtl') {+ return 'rtl';+ }++ return 'ltr';+};++/** Paints the card; `images` comes from `prepareShareCard`, since a canvas only draws images already loaded. */+export const drawShareCard = (+ canvas: HTMLCanvasElement,+ options: ShareCardOptions,+ images: ShareImages,+ scale = SHARE_EXPORT_SCALE,+): void => {+ canvas.width = SHARE_CARD_SIZE.width * scale;+ canvas.height = SHARE_CARD_SIZE.height * scale;++ const context = canvas.getContext('2d');++ if (context === null) {+ return;+ }++ context.setTransform(scale, 0, 0, scale, 0, 0);+ context.direction = readingDirection();+ paintGround(context, options.tint);++ const panel = paintPanel(context);++ PAINTERS[options.shape](context, withResolvedColors(options), images, panel);+ paintMark(context, options.mark);+};++/** The card at download resolution, off screen, as a PNG named after its metric and today: `trypost-followers-2026-10-31.png`. */+export const shareCardFile = async (options: ShareCardOptions): Promise<File> => {+ const canvas = document.createElement('canvas');+ const name = `trypost-${options.key.replaceAll('_', '-')}-${date.userNow().format('YYYY-MM-DD')}.png`;++ drawShareCard(canvas, options, await prepareShareCard(options));++ return canvasToFile(canvas, name, 'image/png');+};diff --git a/resources/js/lib/shareCard/lines.ts b/resources/js/lib/shareCard/lines.tsnew file mode 100644index 000000000..011fd673a--- /dev/null+++ b/resources/js/lib/shareCard/lines.ts@@ -0,0 +1,107 @@+import { spreadLabels } from '@/lib/labelLayout';+import { paintChannel } from '@/lib/shareCard/channel';+import { ink } from '@/lib/shareCard/colors';+import { besideTicks, definedRuns, paintDates, paintGrid, strokeCurve } from '@/lib/shareCard/draw';+import { headlinePlot, paintHeadline } from '@/lib/shareCard/frame';+import { evenDates, linearTicks, shareOf, spread } from '@/lib/shareCard/scale';+import { writeText } from '@/lib/shareCard/text';+import { CHART, PLOT, sans } from '@/lib/shareCard/theme';+import type { Box, Point, ShareCardOptions, ShareImages, ShareLine } from '@/lib/shareCard/types';+import { distinctCountLabels } from '@/lib/utils';++/**+ * The page's Line view at 2x: its 112px rail (a 32px leader, the 20px avatar,+ * a 6px gap and the number in 12px medium), 24px between labels, 16px above+ * the plot the labels may use, 5 value ticks and up to 6 dates.+ */+const LINE_ENDS = { rail: 224, leader: 64, leaderFrom: 1, leaderWidth: 3, leaderInset: 8, leaderTip: 4, avatar: 40, avatarShare: 0.85, gap: 12, height: 48, fontSize: 24, fontShare: 0.6, headroom: 32 };++/** One channel's line in its color, with a dot on each known point. */+const strokeSeries = (context: CanvasRenderingContext2D, line: ShareLine, x: (index: number) => number, y: (value: number) => number): Point[] => {+ const runs = definedRuns(line.values, x, y);+ const known = runs.flat();+ const color = line.color;++ runs.forEach((run) => strokeCurve(context, run, color));++ context.fillStyle = color;+ known.forEach((point) => {+ context.beginPath();+ context.arc(point.x, point.y, CHART.dotRadius, 0, Math.PI * 2);+ context.fill();+ });++ return known;+};++/**+ * One line per channel, like the page's Line view: each ends in the channel's+ * avatar and latest number on the right, spread apart with a leader in the+ * line's color where lines end close together. The labels may use from just+ * above the plot down to the zero line; with many channels they shrink to fit.+ */+const paintLines = (context: CanvasRenderingContext2D, options: ShareCardOptions, images: ShareImages, area: Box): void => {+ const values = options.lines.flatMap((line) => line.values.filter((value): value is number => value !== null));++ if (values.length === 0) {+ return;+ }++ const low = Math.min(...values);+ const high = Math.max(...values);+ const ticks = linearTicks(low, high, CHART.valueTicks);+ const plot = besideTicks(context, { ...area, width: area.width - LINE_ENDS.rail }, distinctCountLabels(ticks));+ const x = (index: number): number => plot.x + spread(index, options.points.length) * plot.width;+ const y = (value: number): number => plot.y + plot.height - shareOf(value, low, high) * plot.height;+ const lineEnd = plot.x + plot.width;++ paintGrid(+ context,+ ticks,+ (value) => [{ x: plot.x, y: y(value) }, { x: lineEnd, y: y(value) }],+ (value) => ({ x: plot.x - PLOT.tickGap, y: y(value) }),+ { align: 'right', baseline: 'middle' },+ );++ paintDates(context, options.points, evenDates(options.points.length), x, plot);++ const ends = options.lines.flatMap((line) => {+ const known = strokeSeries(context, line, x, y);+ const last = known[known.length - 1];++ return last ? [{ line, lineY: last.y }] : [];+ });+ const room = { top: plot.y - LINE_ENDS.headroom, bottom: Math.min(y(0), plot.y + plot.height) };+ const step = Math.min(LINE_ENDS.height, (room.bottom - room.top) / Math.max(ends.length, 1));+ const avatarSize = Math.min(LINE_ENDS.avatar, step * LINE_ENDS.avatarShare);+ const font = sans(500, Math.min(LINE_ENDS.fontSize, step * LINE_ENDS.fontShare));+ const labels = spreadLabels(+ ends.map((end) => end.lineY),+ { gap: step, ...room },+ );++ ends.forEach(({ line, lineY }, position) => {+ const labelY = labels[position];+ const labelX = lineEnd + LINE_ENDS.leader;++ if (Math.abs(labelY - lineY) > LINE_ENDS.leaderFrom) {+ context.strokeStyle = line.color;+ context.lineWidth = LINE_ENDS.leaderWidth;+ context.lineJoin = 'round';+ context.beginPath();+ context.moveTo(lineEnd + LINE_ENDS.leaderInset, lineY);+ context.lineTo(lineEnd + LINE_ENDS.leader / 2, lineY);+ context.lineTo(labelX - LINE_ENDS.leaderTip, labelY);+ context.stroke();+ }++ paintChannel(context, line.channel, images, { x: labelX, y: labelY - avatarSize / 2 }, avatarSize);+ writeText(context, line.figure, { x: labelX + avatarSize + LINE_ENDS.gap, y: labelY }, { font, color: ink(), baseline: 'middle' });+ });+};++/** The headline over one line per channel. */+export const paintLinesCard = (context: CanvasRenderingContext2D, options: ShareCardOptions, images: ShareImages, panel: Box): void => {+ paintHeadline(context, options, panel);+ paintLines(context, options, images, headlinePlot(panel));+};diff --git a/resources/js/lib/shareCard/rows.ts b/resources/js/lib/shareCard/rows.tsnew file mode 100644index 000000000..975bd1ffe--- /dev/null+++ b/resources/js/lib/shareCard/rows.ts@@ -0,0 +1,101 @@+import { AVATAR, avatarSpace, paintChannel, rowColor } from '@/lib/shareCard/channel';+import { ink, muted } from '@/lib/shareCard/colors';+import { fillBar, paintGrid } from '@/lib/shareCard/draw';+import { headlinePlot, paintHeadline, pointValues } from '@/lib/shareCard/frame';+import { valueAxis } from '@/lib/shareCard/scale';+import { ellipsise, widest, writeText } from '@/lib/shareCard/text';+import { CHART, PLOT, sans } from '@/lib/shareCard/theme';+import type { Box, ShareCardOptions, ShareImages, SharePoint } from '@/lib/shareCard/types';++/** One bar per channel after a column of its name, number and avatar, as wide as they need; a name past `nameMax` is trimmed. Bars take 60% of a row, 40px at most: the page's 20px at 2x. */+const ROWS = {+ max: 12,+ nameMax: 320,+ figureGap: 32,+ labelGap: 24,+ axis: 44,+ valuesGap: 36,+ thickness: 40,+ thicknessShare: 0.6,+ label: { min: 14, max: 22, share: 0.55 },+ figure: { min: 16, max: 26, share: 0.6 },+};++type RankedPoint = SharePoint & { index: number; value: number };++/** The channels with the largest values when they do not all fit, kept in the page's order. */+const rankedRows = (points: SharePoint[]): RankedPoint[] =>+ points+ .map((point, index) => ({ ...point, index }))+ .filter((point): point is RankedPoint => point.value !== null)+ .sort((a, b) => Math.abs(b.value) - Math.abs(a.value))+ .slice(0, ROWS.max)+ .sort((a, b) => a.index - b.index);++/** A row's text size: its share of the row's height, kept between the size's bounds. */+const rowTextSize = (size: { min: number; max: number; share: number }, rowHeight: number): number =>+ Math.min(size.max, Math.max(size.min, rowHeight * size.share));++/**+ * One horizontal bar per channel from zero, losses to the left, in each+ * channel's color, after its name, its number and its avatar in a fixed+ * column, like the page's Bar and Growth views.+ */+const paintRows = (context: CanvasRenderingContext2D, options: ShareCardOptions, images: ShareImages, area: Box): void => {+ const rows = rankedRows(options.points);+ const axis = valueAxis(rows.map((point) => point.value), CHART.valueTicks);+ const plotHeight = area.height - ROWS.axis;+ const rowHeight = plotHeight / Math.max(rows.length, 1);+ const thickness = Math.min(rowHeight * ROWS.thicknessShare, ROWS.thickness);+ const labelFont = sans(500, rowTextSize(ROWS.label, rowHeight));+ const figureFont = sans(600, rowTextSize(ROWS.figure, rowHeight));+ const avatarSize = Math.min(AVATAR.size, rowHeight * AVATAR.fill);+ const nameWidth = Math.min(ROWS.nameMax, widest(context, rows.map((point) => point.label), labelFont));+ const figureWidth = widest(context, rows.map((point) => point.figure ?? ''), figureFont);+ const channelWidth = Math.max(0, ...rows.map((point) => avatarSpace(point, avatarSize)));+ const column = nameWidth + ROWS.figureGap + figureWidth + channelWidth + ROWS.labelGap;+ const plot = { x: area.x + column, y: area.y, width: area.width - column, height: plotHeight };+ const x = (value: number): number => plot.x + axis.at(value) * plot.width;++ paintGrid(+ context,+ axis.ticks,+ (value) => [{ x: x(value), y: plot.y }, { x: x(value), y: plot.y + plot.height }],+ (value) => ({ x: x(value), y: plot.y + plot.height + ROWS.valuesGap }),+ { align: 'center' },+ );++ rows.forEach((point, row) => {+ const centre = plot.y + rowHeight * (row + 0.5);++ writeText(context, ellipsise(context, point.label, labelFont, nameWidth), { x: area.x, y: centre }, { font: labelFont, color: muted(), baseline: 'middle' });++ if (point.figure) {+ writeText(context, point.figure, { x: area.x + nameWidth + ROWS.figureGap + figureWidth, y: centre }, { font: figureFont, color: ink(), align: 'right', baseline: 'middle' });+ }++ if (point.channel) {+ paintChannel(context, point.channel, images, { x: plot.x - ROWS.labelGap - avatarSize, y: centre - avatarSize / 2 }, avatarSize);+ }++ if (point.value === 0) {+ return;+ }++ context.fillStyle = rowColor(point, options.tint);+ fillBar(context, plot.x + axis.zero * plot.width, x(point.value), centre, thickness, true);+ });+};++/** The headline over one bar per channel, which takes the gutter for its names and numbers. */+export const paintRowsCard = (context: CanvasRenderingContext2D, options: ShareCardOptions, images: ShareImages, panel: Box): void => {+ paintHeadline(context, options, panel);++ if (pointValues(options.points).length === 0) {+ return;+ }++ const plot = headlinePlot(panel);++ paintRows(context, options, images, { x: plot.x - PLOT.gutter, y: plot.y, width: plot.width + PLOT.gutter, height: plot.height + PLOT.dates });+};diff --git a/resources/js/lib/shareCard/scale.ts b/resources/js/lib/shareCard/scale.tsnew file mode 100644index 000000000..8f20bdc1e--- /dev/null+++ b/resources/js/lib/shareCard/scale.ts@@ -0,0 +1,149 @@+import { CHART } from '@/lib/shareCard/theme';++/** d3's tick rule: the step is 10, 5, 2 or 1 times a power of ten, whichever lands closest to the asked count. */+const TICK_FACTORS: [number, number][] = [+ [Math.sqrt(50), 10],+ [Math.sqrt(10), 5],+ [Math.sqrt(2), 2],+];++/** The tick step's factor for how far the raw step is past its power of ten: 1 below every threshold. */+const tickFactor = (error: number): number => {+ const match = TICK_FACTORS.find(([threshold]) => error >= threshold);++ if (!match) {+ return 1;+ }++ return match[1];+};++/** How far `value` sits from `low` to `high`, 0 to 1; a flat range puts everything at its low end's height. */+export const shareOf = (value: number, low: number, high: number): number => (value - low) / (high - low || 1);++type ValueAxis = {+ ticks: number[];+ /** Where a value sits on the axis, from 0 at its start to 1 at its end. */+ at: (value: number) => number;+ /** Where the bars start: zero. */+ zero: number;+};++/**+ * A value axis like the page's unovis axes: the values' range with zero in+ * it, not rounded out, and d3's round ticks inside it.+ */+export const valueAxis = (values: number[], tickCount: number): ValueAxis => {+ const low = Math.min(0, ...values);+ const high = Math.max(0, ...values);+ const at = (value: number): number => shareOf(value, low, high);++ return { ticks: linearTicks(low, high, tickCount), at, zero: at(0) };+};++/** Where the `index`-th of `count` points sits across a plot, the first at its start and the last at its end, like unovis' line. */+export const spread = (index: number, count: number): number => {+ if (count <= 1) {+ return 0.5;+ }++ return index / (count - 1);+};++/** The ticks' run: the first and last multiples of `increment` inside the range, and whether the step divides (d3 keeps steps below 1 as a divisor, so 0.1 stays exact). */+type TickSpec = { first: number; last: number; increment: number; divides: boolean };++/** One past `index` when the multiple it stands for falls before the range, as d3 nudges its first tick in. */+const firstInside = (index: number, at: number, start: number): number => {+ if (at < start) {+ return index + 1;+ }++ return index;+};++/** One before `index` when the multiple it stands for falls past the range, as d3 nudges its last tick in. */+const lastInside = (index: number, at: number, stop: number): number => {+ if (at > stop) {+ return index - 1;+ }++ return index;+};++/** d3-array's `tickSpec`, line for line, so the card's ticks are exactly the page axes' ticks. */+const tickSpec = (start: number, stop: number, count: number): TickSpec => {+ const step = (stop - start) / Math.max(0, count);+ const power = Math.floor(Math.log10(step));+ const factor = tickFactor(step / 10 ** power);+ const spec = tickRun(start, stop, power, factor);++ if (spec.last < spec.first && count >= 0.5 && count < 2) {+ return tickSpec(start, stop, count * 2);+ }++ return spec;+};++/** The run of ticks for a step of `factor` times ten to `power`. */+const tickRun = (start: number, stop: number, power: number, factor: number): TickSpec => {+ if (power < 0) {+ const increment = 10 ** -power / factor;+ const first = Math.round(start * increment);+ const last = Math.round(stop * increment);++ return { first: firstInside(first, first / increment, start), last: lastInside(last, last / increment, stop), increment, divides: true };+ }++ const increment = 10 ** power * factor;+ const first = Math.round(start / increment);+ const last = Math.round(stop / increment);++ return { first: firstInside(first, first * increment, start), last: lastInside(last, last * increment, stop), increment, divides: false };+};++/** The value of the `index`-th tick of a run. */+const tickAt = (spec: TickSpec, index: number): number => {+ if (spec.divides) {+ return (spec.first + index) / spec.increment;+ }++ return (spec.first + index) * spec.increment;+};++/** Round ticks inside [start, stop], about `count` of them: d3-array's `ticks`, which the page's axes use. */+export const linearTicks = (start: number, stop: number, count: number): number[] => {+ if (!(count > 0) || stop < start) {+ return [];+ }++ if (start === stop) {+ return [start];+ }++ const spec = tickSpec(start, stop, count);++ if (spec.last < spec.first) {+ return [];+ }++ return Array.from({ length: spec.last - spec.first + 1 }, (_, index) => tickAt(spec, index));+};++/** Up to `CHART.maxDates` dates evenly spread over a line, like the page's date axes, on whole points only. */+export const evenDates = (count: number): number[] =>+ linearTicks(0, count - 1, Math.min(count, CHART.maxDates)).filter((tick) => Number.isInteger(tick));++/**+ * The days the channel chart dates, as its page axis does: d3's ticks over the+ * axis' `[-0.5, count - 0.5]` domain, keeping the whole days only.+ */+export const comboDates = (count: number): number[] =>+ linearTicks(-0.5, count - 0.5, Math.min(count, CHART.maxDates)).filter((tick) => Number.isInteger(tick));++/** Which of `count` columns get a label when only `fitting` fit: all of them, else every second or third, so none overlap. */+export const fittingColumns = (count: number, fitting: number): number[] => {+ const step = Math.ceil(count / Math.max(fitting, 1));++ return Array.from({ length: count }, (_, index) => index).filter((index) => index % step === 0);+};diff --git a/resources/js/lib/shareCard/stacked.ts b/resources/js/lib/shareCard/stacked.tsnew file mode 100644index 000000000..07ffd32c3--- /dev/null+++ b/resources/js/lib/shareCard/stacked.ts@@ -0,0 +1,111 @@++import { surface } from '@/lib/shareCard/colors';+import { barWidth } from '@/lib/shareCard/combo';+import { besideTicks, fillBar, paintDates, paintGrid } from '@/lib/shareCard/draw';+import { headlinePlot, paintHeadline, pointValues } from '@/lib/shareCard/frame';+import { fittingColumns, valueAxis } from '@/lib/shareCard/scale';+import { widest } from '@/lib/shareCard/text';+import { CHART, PLOT } from '@/lib/shareCard/theme';+import type { Box, ShareCardOptions, SharePoint, ShareSegment } from '@/lib/shareCard/types';+import { distinctCountLabels } from '@/lib/utils';++type Column = { middle: number; width: number };++/**+ * A column split by channel, bottom up in the page's order, with only its top+ * rounded like unovis' stacked bars.+ */+/** The page's Posts columns at 2x: 28px at most, each channel's part set apart by a 1.5px line of the card's white. */+const STACKED = { barMaxWidth: 56, separator: 3 };++/** The card's white line between two channels' parts of a column, where the lower one ends. */+const paintSeparator = (context: CanvasRenderingContext2D, column: Column, at: number): void => {+ context.fillStyle = surface();+ context.fillRect(column.middle - column.width / 2, at - STACKED.separator / 2, column.width, STACKED.separator);+};++const paintStack = (+ context: CanvasRenderingContext2D,+ segments: ShareSegment[],+ column: Column,+ y: (value: number) => number,+): void => {+ const parts = segments.filter((segment) => segment.value > 0);+ let base = 0;++ parts.forEach((segment, index) => {+ const top = base + segment.value;++ context.fillStyle = segment.color;++ if (index === parts.length - 1) {+ fillBar(context, y(base), y(top), column.middle, column.width, false);+ } else {+ context.fillRect(column.middle - column.width / 2, y(top), column.width, y(base) - y(top));+ }++ base = top;+ });++ parts.slice(0, -1).reduce((boundary, segment) => {+ const top = boundary + segment.value;++ paintSeparator(context, column, y(top));++ return top;+ }, 0);+};++/** One column per bucket from zero, split by channel in each channel's color. */+const paintBars = (+ context: CanvasRenderingContext2D,+ options: ShareCardOptions,+ plot: Box,+ x: (index: number) => number,+ y: (value: number) => number,+): void => {+ const width = barWidth(plot.width / options.points.length, 1, STACKED.barMaxWidth);++ options.points.forEach((point, index) => {+ if (point.segments && point.value) {+ paintStack(context, point.segments, { middle: x(index), width }, y);+ }+ });+};++/**+ * The columns that get a date: every one, like the page's Posts chart, unless+ * the card is too narrow for them all, then every second or third, so no two+ * dates ever overlap.+ */+const columnDates = (context: CanvasRenderingContext2D, points: SharePoint[], width: number): number[] => {+ const room = widest(context, points.map((point) => point.label), CHART.tickFont) + PLOT.dateGap;+ return fittingColumns(points.length, Math.floor(width / room));+};++/** The headline over one column per bucket, split by channel. */+export const paintStackedCard = (context: CanvasRenderingContext2D, options: ShareCardOptions, panel: Box): void => {+ paintHeadline(context, options, panel);++ const values = pointValues(options.points);++ if (values.length === 0) {+ return;+ }++ const axis = valueAxis(values, CHART.valueTicks);+ const plot = besideTicks(context, headlinePlot(panel), distinctCountLabels(axis.ticks));+ const slot = plot.width / options.points.length;+ const x = (index: number): number => plot.x + slot * (index + 0.5);+ const y = (value: number): number => plot.y + plot.height - axis.at(value) * plot.height;++ paintGrid(+ context,+ axis.ticks,+ (value) => [{ x: plot.x, y: y(value) }, { x: plot.x + plot.width, y: y(value) }],+ (value) => ({ x: plot.x - PLOT.tickGap, y: y(value) }),+ { align: 'right', baseline: 'middle' },+ );+ paintBars(context, options, plot, x, y);+ paintDates(context, options.points, columnDates(context, options.points, plot.width), x, plot);+};diff --git a/resources/js/lib/shareCard/summary.ts b/resources/js/lib/shareCard/summary.tsnew file mode 100644index 000000000..6fe4eddf8--- /dev/null+++ b/resources/js/lib/shareCard/summary.ts@@ -0,0 +1,198 @@+import type { MetricDelta } from '@/lib/channelMetrics';+import { ink, muted } from '@/lib/shareCard/colors';+import { CHANGE_ICON, changeWidth, paintChange, strokeLine } from '@/lib/shareCard/draw';+import { paintIdentity } from '@/lib/shareCard/frame';+import { ellipsise, writeText } from '@/lib/shareCard/text';+import { BORDER, heading, IDENTITY, PANEL, sans } from '@/lib/shareCard/theme';+import type { Box, Point, ShareCardOptions, ShareTile } from '@/lib/shareCard/types';++/** The Summary's grid under the identity; a tile is drawn for `tileHeight` and shrinks to fit. */+const SUMMARY = { top: 168, tileHeight: 185, inset: 36, crowdedInset: 24, crowdedColumns: 5, label: 50, labelSize: 24, figureGap: 6, changeGap: 16, changeSize: 24, changeBelow: 12, minTextShare: 0.7, figureOverhang: 2, crowdedFigure: 52, singleRowFigure: 84, figure: 64, crowdedFrom: 4 };++/** A tile's number in ink, or muted when the metric has no value yet. */+const tileFigureColor = (tile: ShareTile): string => {+ if (tile.missing) {+ return muted();+ }++ return ink();+};++/** How many columns the Summary's numbers take, like the page's grid. */+const tileColumns = (count: number): number => {+ if (count <= 3) {+ return Math.max(count, 1);+ }++ if (count === 4) {+ return 2;+ }++ if (count <= 6) {+ return 3;+ }++ if (count <= 8) {+ return 4;+ }++ return 5;+};++/** The space inside a tile's border: tighter in the five-column grid, whose tiles are the narrowest. */+const tileInset = (columns: number): number => {+ if (columns >= SUMMARY.crowdedColumns) {+ return SUMMARY.crowdedInset;+ }++ return SUMMARY.inset;+};++/** A tile's figure size before it shrinks to fit: smaller in a crowded grid, largest in a single row. */+const tileFigureSize = (columns: number, rows: number): number => {+ if (columns >= SUMMARY.crowdedFrom) {+ return SUMMARY.crowdedFigure;+ }++ if (rows === 1) {+ return SUMMARY.singleRowFigure;+ }++ return SUMMARY.figure;+};++/** How many tiles a row of the Summary holds: full rows, and the rest stretched over the last one so no tile is left empty. */+const tilesInRow = (row: number, rows: number, columns: number, count: number): number => {+ if (row < rows - 1) {+ return columns;+ }++ return count - columns * (rows - 1);+};++/**+ * Every number of the Summary, split by ink rules like a cover's settings+ * panel. More rows shrink every tile instead of dropping numbers, and every+ * label shares one size, the one they all fit in the narrowest tile.+ */+export const paintSummary = (context: CanvasRenderingContext2D, options: ShareCardOptions, panel: Box): void => {+ paintIdentity(+ context,+ options.subject,+ options.range,+ { x: panel.x + PANEL.padding, y: panel.y + IDENTITY.top },+ panel.width - PANEL.padding * 2,+ );++ const tiles = options.tiles;+ const columns = tileColumns(tiles.length);+ const rows = Math.ceil(tiles.length / columns);+ const grid = { x: panel.x, y: panel.y + SUMMARY.top, width: panel.width, height: panel.height - SUMMARY.top };+ const tileHeight = grid.height / Math.max(rows, 1);+ const fit = Math.min(1, tileHeight / SUMMARY.tileHeight);+ const figureSize = tileFigureSize(columns, rows) * fit;+ const rowSize = (row: number): number => tilesInRow(row, rows, columns, tiles.length);+ const inset = tileInset(columns) * fit;+ const tileWidth = (index: number): number => grid.width / rowSize(Math.floor(index / columns));+ const tileLimit = (index: number): number => tileWidth(index) - inset * 2;+ const labelSize = Math.min(+ ...tiles.map((tile) => fittingSize(context, tile.label, (size) => sans(500, size), SUMMARY.labelSize * fit, grid.width / columns - inset * 2)),+ );+ const labelFont = sans(500, labelSize);+ const changeSize = SUMMARY.changeSize * fit;+ const under = changesUnderFigures(context, tiles, heading(500, figureSize), changeSize, SUMMARY.changeGap * fit, tileLimit);++ context.strokeStyle = ink();+ context.lineWidth = BORDER;++ for (let row = 0; row < rows; row += 1) {+ const top = grid.y + tileHeight * row;+ const width = grid.width / rowSize(row);++ strokeLine(context, { x: grid.x, y: top }, { x: grid.x + grid.width, y: top });++ for (let column = 1; column < rowSize(row); column += 1) {+ strokeLine(context, { x: grid.x + width * column, y: top }, { x: grid.x + width * column, y: top + tileHeight });+ }+ }++ tiles.forEach((tile, index) => {+ const row = Math.floor(index / columns);+ const left = grid.x + tileWidth(index) * (index % columns) + inset;+ const limit = tileLimit(index);+ const labelLine = grid.y + tileHeight * row + SUMMARY.label * fit;+ const figureText = tile.figure;+ const figureFont = heading(500, fittingSize(context, figureText, (size) => heading(500, size), figureSize, limit));+ const baseline = labelLine + figureSize + SUMMARY.figureGap * fit;++ writeText(context, ellipsise(context, tile.label, labelFont, limit), { x: left, y: labelLine }, { font: labelFont, color: muted() });+ writeText(context, figureText, { x: left - SUMMARY.figureOverhang * fit, y: baseline }, {+ font: figureFont,+ color: tileFigureColor(tile),+ });++ if (tile.change) {+ paintTileChange(context, tile.change, { x: left, y: baseline }, { figureFont, figure: figureText, changeSize, fit, under });+ }+ });+};++/** The size, down to `SUMMARY.minTextShare` of `size`, at which `text` fits `limit` in the font `fontAt` gives. */+const fittingSize = (+ context: CanvasRenderingContext2D,+ text: string,+ fontAt: (size: number) => string,+ size: number,+ limit: number,+): number => {+ context.font = fontAt(size);+ const width = context.measureText(text).width;++ if (width <= limit) {+ return size;+ }++ return Math.max(size * SUMMARY.minTextShare, (size * limit) / width);+};++/**+ * Whether the changes go under the numbers: as soon as one tile has no room+ * for its change beside its number, every tile stacks them, as the page's+ * half-width cards do on a phone, so the grid reads the same throughout.+ */+const changesUnderFigures = (+ context: CanvasRenderingContext2D,+ tiles: ShareTile[],+ figureFont: string,+ changeSize: number,+ gap: number,+ limit: (index: number) => number,+): boolean =>+ tiles.some((tile, index) => {+ if (!tile.change) {+ return false;+ }++ context.font = figureFont;++ return context.measureText(tile.figure).width + gap + changeWidth(context, tile.change, changeSize) > limit(index);+ });++/** A tile's change: beside its number with its icon on the number's baseline, like the page's cards, or under it. */+const paintTileChange = (+ context: CanvasRenderingContext2D,+ change: MetricDelta,+ figureAt: Point,+ tile: { figureFont: string; figure: string; changeSize: number; fit: number; under: boolean },+): void => {+ if (tile.under) {+ paintChange(context, change, { x: figureAt.x, y: figureAt.y + SUMMARY.changeBelow * tile.fit }, tile.changeSize, 'left');++ return;+ }++ context.font = tile.figureFont;+ const besideFigure = figureAt.x - SUMMARY.figureOverhang * tile.fit + context.measureText(tile.figure).width + SUMMARY.changeGap * tile.fit;++ paintChange(context, change, { x: besideFigure, y: figureAt.y - tile.changeSize * CHANGE_ICON.scale }, tile.changeSize, 'left');+};diff --git a/resources/js/lib/shareCard/text.ts b/resources/js/lib/shareCard/text.tsnew file mode 100644index 000000000..b6f21daf0--- /dev/null+++ b/resources/js/lib/shareCard/text.ts@@ -0,0 +1,52 @@+import type { Point } from '@/lib/shareCard/types';++export type TextStyle = {+ font: string;+ color: string;+ /** Always a side, never `start` or `end`, so a right-to-left text keeps the card's left-to-right layout. */+ align?: 'left' | 'right' | 'center';+ baseline?: CanvasTextBaseline;+};++/** Writes one line of text in its own style, so no drawing step inherits another's. */+export const writeText = (+ context: CanvasRenderingContext2D,+ text: string,+ at: Point,+ { font, color, align = 'left', baseline = 'alphabetic' }: TextStyle,+): void => {+ context.font = font;+ context.fillStyle = color;+ context.textAlign = align;+ context.textBaseline = baseline;+ context.fillText(text, at.x, at.y);+};++/** The width of the widest of `texts` in `font`. */+export const widest = (context: CanvasRenderingContext2D, texts: string[], font: string): number => {+ context.font = font;++ return Math.max(0, ...texts.map((text) => context.measureText(text).width));+};++/** The text cut with an ellipsis to fit `limit` in `font`, one whole character (an emoji with its joiners included) at a time. */+export const ellipsise = (+ context: CanvasRenderingContext2D,+ text: string,+ font: string,+ limit: number,+): string => {+ context.font = font;++ if (context.measureText(text).width <= limit) {+ return text;+ }++ const characters = Array.from(new Intl.Segmenter().segment(text), (piece) => piece.segment);++ while (characters.length > 1 && context.measureText(`${characters.join('')}…`).width > limit) {+ characters.pop();+ }++ return `${characters.join('')}…`;+};diff --git a/resources/js/lib/shareCard/theme.ts b/resources/js/lib/shareCard/theme.tsnew file mode 100644index 000000000..04c7ddc23--- /dev/null+++ b/resources/js/lib/shareCard/theme.ts@@ -0,0 +1,80 @@+/** The light tints of the "What's New" covers, with the strong color the data is drawn in. */+export const SHARE_TINTS = [+ { key: 'violet', ground: '#d2c7fd', strong: '#6d28d9' },+ { key: 'purple', ground: '#ead9fb', strong: '#7e22ce' },+ { key: 'fuchsia', ground: '#f6dcfb', strong: '#a21caf' },+ { key: 'pink', ground: '#fce1ef', strong: '#db2777' },+ { key: 'red', ground: '#fde0e0', strong: '#dc2626' },+ { key: 'peach', ground: '#ffdbd6', strong: '#ea580c' },+ { key: 'orange', ground: '#ffe4c8', strong: '#c2410c' },+ { key: 'yellow', ground: '#fdefc3', strong: '#a16207' },+ { key: 'lime', ground: '#eaf7c8', strong: '#4d7c0f' },+ { key: 'green', ground: '#d9f1d1', strong: '#16a34a' },+ { key: 'teal', ground: '#ccf5ea', strong: '#0f766e' },+ { key: 'cyan', ground: '#cff4fc', strong: '#0e7490' },+ { key: 'blue', ground: '#def0ff', strong: '#2563eb' },+ { key: 'indigo', ground: '#dfe3fd', strong: '#4338ca' },+ { key: 'slate', ground: '#e3e8ef', strong: '#334155' },+ { key: 'neutral', ground: '#f4f1ec', strong: '#292928' },+] as const;++/** One of the card's tints. */+export type ShareTint = (typeof SHARE_TINTS)[number];++/** The card's size, 16:9, in the units every painter draws in. */+export const SHARE_CARD_SIZE = { width: 1200, height: 675 };++/** How many pixels the exported file draws per card unit, for sharp text on high-density screens. */+export const SHARE_EXPORT_SCALE = 2;++/** The ink border of the panel and the Summary's rules, like a cover's settings panel. */+export const BORDER = 2.5;++/** The app's body face, for labels and ticks. */+const SANS = "Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif";++/** The app's heading face (`--font-heading`), for names and numbers. */+const HEADING = "Outfit, Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif";++/** A body font at `weight` and `size`. */+export const sans = (weight: number, size: number): string => `${weight} ${size}px ${SANS}`;++/** A heading font at `weight` and `size`. */+export const heading = (weight: number, size: number): string => `${weight} ${size}px ${HEADING}`;++/**+ * The app's charts (`ChartContainer`, `ChannelMetricsChart`) at twice their+ * size, since the card is the page at 2x: a dashed `--border` grid, muted+ * ticks, bars without outline rounded at the data end, a 2px monotone line+ * with a dot on each point.+ */+export const CHART = {+ gridDash: [6, 6],+ gridWidth: 2,+ tickFont: sans(500, 22),+ barMaxWidth: 32,+ barMinWidth: 2,+ barPadding: 0.35,+ /** The page's bars round their data end 4px on 20px bars: the radius keeps that share of a bar's thickness. */+ barRoundness: 4 / 20,+ lineWidth: 4,+ dotRadius: 4,+ /** The page's value axes ask d3 for five ticks, its date axes for six. */+ valueTicks: 5,+ maxDates: 6,+};++/** `MetricChange`'s tones, as the app's text tokens. */+export const CHANGE_TOKENS = { up: 'var(--success-text)', down: 'var(--destructive-text)', flat: 'var(--muted-foreground)' } as const;++/** The white surface, inset from the tint like a cover's panel, over the signature's band. */+export const PANEL = { x: 56, y: 48, radius: 24, padding: 48, band: 92 };++/** The name and what-and-when lines at the panel's top, as baselines from where they start. */+export const IDENTITY = { top: 40, name: 34, nameSize: 36, detail: 76, detailSize: 22 };++/** The chart card's headline: the figure at the top right and its change under it. */+export const HEADLINE = { reserve: 380, figure: 100, figureSize: 68, change: 116, changeSize: 26 };++/** The plot under the headline, with a gutter for the value ticks and room for the dates under it. */+export const PLOT = { top: 212, bottom: 76, gutter: 72, tickGap: 18, dates: 40, dateGap: 24 };diff --git a/resources/js/lib/shareCard/types.ts b/resources/js/lib/shareCard/types.tsnew file mode 100644index 000000000..41ba7fd84--- /dev/null+++ b/resources/js/lib/shareCard/types.ts@@ -0,0 +1,103 @@+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';++/** The channel a `rows` bar belongs to, drawn next to its name like the page's chart. */+export type ShareChannel = {+ platform: string;+ /** The stored avatar the report sends; the card draws the network's logo when it cannot load it with CORS. */+ avatar: string | null;+ verified: VerifiedBadge | null;+};++/** One channel's part of a `stacked` column, in the channel's color. */+export type ShareSegment = { value: number; color: string };++/** A bucket over time, or a channel for `rows`, which may bring its own color. */+export type SharePoint = {+ label: string;+ value: number | null;+ color?: string;+ channel?: ShareChannel;+ /** A channel's number as its `rows` line prints it, before its bar. */+ figure?: string;+ /** The column's parts, bottom up, for `stacked`; `value` is their total. */+ segments?: ShareSegment[];+};++/** One channel's line over the points' dates for `lines`, ending in its avatar and latest number. */+export type ShareLine = {+ color: string;+ channel: ShareChannel;+ /** The channel's latest number as the line's label prints it. */+ figure: string;+ /** One value per point, null before the channel's first reading. */+ values: (number | null)[];+};++/**+ * One metric of the channel chart for `combo`, drawn the way the page draws+ * it: bars or a line on its own axis, in its color, for each period shown.+ */+export type ShareSeries = {+ metric: SeriesMetric;+ label: string;+ color: string;+ kind: 'bar' | 'line';+ axis: 'left' | 'right';+ /** One value per point, in this period and in the previous one. */+ current: (number | null)[];+ previous: (number | null)[];+ /** The period's totals as the page's legend prints them, and how the metric moved. */+ figure: string;+ previousFigure: string;+ change: MetricDelta | null;+};++/** The images a card draws, loaded before painting: a canvas only draws images already loaded. */+export type ShareImages = ReadonlyMap<string, HTMLImageElement>;++/** 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 };++/** 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';++/** One metric a share dialog can draw, with the post text it opens the composer with. */+export type ShareMetricOption = {+ key: ShareMetricKey;+ label: string;+ figure: string;+ change: MetricDelta | null;+ points: SharePoint[];+ shape: ShareShape;+ /** Every number of the Summary, for the summary card. */+ tiles: ShareTile[];+ /** One line per channel, for `lines`. */+ lines: ShareLine[];+ /** The channel chart's metrics, for `combo`. */+ series: ShareSeries[];+ /** The periods `combo` shows, as the page's chart toggle sets them. */+ chartMode: ChartMode;+ caption: string;+};++/** The metric to draw, and how: in which tint, for whom, over which period, signed how. */+export type ShareCardOptions = Omit<ShareMetricOption, 'caption'> & {+ tint: ShareTint;+ /** The workspace or channel the numbers belong to. */+ subject: string;+ /** The period, as the page prints it. */+ range: string;+ /** The signature: "Made with TryPost", translated. */+ mark: string;+};++export type Point = { x: number; y: number };++export type Box = Point & { width: number; height: number };diff --git a/resources/js/lib/utils.ts b/resources/js/lib/utils.tsindex e1a9c656d..8d1998406 100644--- a/resources/js/lib/utils.ts+++ b/resources/js/lib/utils.ts@@ -14,6 +14,17 @@ export const toUrl = (href: NonNullable<InertiaLinkProps['href']>) => {return typeof href === 'string' ? href : href?.url;};+/** Runs `task` once the browser is idle; Safari, without `requestIdleCallback`, runs it on the next tick. */+export const whenIdle = (task: () => void): void => {+ if ('requestIdleCallback' in window) {+ window.requestIdleCallback(task);++ return;+ }++ setTimeout(task, 0);+};+export const toNullableText = (value: unknown): string | null =>typeof value === 'string' && value.trim() ? value : null;@@ -21,22 +32,87 @@ export const formatNumber = (value: number): string => {return value.toLocaleString('en-US');};-export const formatNumberCompact = (value: number, digits = 1): string => {- return new Intl.NumberFormat(activeLocale.value, {- notation: 'compact',- compactDisplay: 'short',- maximumFractionDigits: digits,- }).format(value);-};+/** What a number reads while it has no value. */+const MISSING_VALUE = '—';++/** A number that may have no value yet; the formatters below read it as a dash. */+type MaybeNumber = number | null | undefined;++/** A number formatter that reads a missing value as a dash, so no caller checks for one. */+const withDash =+ <Args extends unknown[]>(format: (value: number, ...args: Args) => string) =>+ (value: MaybeNumber, ...args: Args): string => {+ if (value == null) {+ return MISSING_VALUE;+ }++ return format(value, ...args);+ };++export const formatNumberCompact = withDash(+ (value: number, digits: number = 1): string =>+ new Intl.NumberFormat(activeLocale.value, {+ notation: 'compact',+ compactDisplay: 'short',+ maximumFractionDigits: digits,+ }).format(value),+);++/** The most decimals a compact axis label takes before it falls back to whole numbers. */+const MAX_COMPACT_DIGITS = 2;++/**+ * Compact labels for a run of axis values, with the fewest decimals that+ * round none of them ("2.5", "9.33K"), else the exact values when two would+ * still read the same ("1,000.5" next to "1,001", never two "1,001").+ */+export const distinctCountLabels = (values: number[]): string[] => {+ const precise = values.map((value) => formatNumberCompact(value, MAX_COMPACT_DIGITS));++ if (new Set(precise).size !== precise.length) {+ return values.map((value) => formatFullNumber(value));+ }-export const formatPercent = (value: number): string => {- return new Intl.NumberFormat(activeLocale.value, {- style: 'percent',- maximumFractionDigits: 2,- }).format(value / 100);+ for (let digits = 0; digits < MAX_COMPACT_DIGITS; digits += 1) {+ const labels = values.map((value) => formatNumberCompact(value, digits));++ if (labels.every((label, index) => label === precise[index])) {+ return labels;+ }+ }++ return precise;};-export const formatPercentChange = (value: number): string => {+export const formatPercent = withDash(+ (value: number): string =>+ new Intl.NumberFormat(activeLocale.value, {+ style: 'percent',+ maximumFractionDigits: 2,+ }).format(value / 100),+);++/** A change in a count, signed and exact: "+1,234", "-3", "0". */+export const formatSignedNumber = (value: number): string =>+ new Intl.NumberFormat(activeLocale.value, { signDisplay: 'exceptZero' }).format(value);++/** A count in the reader's language, exact: "1,234". */+export const formatFullNumber = withDash(+ (value: number): string => value.toLocaleString(activeLocale.value),+);++/** A change in a count, signed and compact: "+1.2K", "-3", "0". */+export const formatCountChange = withDash(+ (value: number): string =>+ new Intl.NumberFormat(activeLocale.value, {+ notation: 'compact',+ compactDisplay: 'short',+ maximumFractionDigits: 1,+ signDisplay: 'exceptZero',+ }).format(value),+);++export const formatPercentChange = withDash((value: number): string => {const compact = Math.abs(value) >= 1000;return new Intl.NumberFormat(activeLocale.value, {@@ -45,7 +121,7 @@ export const formatPercentChange = (value: number): string => {notation: compact ? 'compact' : 'standard',maximumFractionDigits: compact ? 1 : 2,}).format(value / 100);-};+});export const formatMoney = (cents: number): string => {const dollars = cents / 100;@@ -88,6 +164,33 @@ export const copyToClipboard = async (return true;};+/** How long a download's object URL lives: long enough for the browser to start saving the file. */+const DOWNLOAD_URL_LIFETIME_MS = 60_000;++/**+ * Saves a file the way a download link would. The link's URL lives a minute:+ * revoked at once, some browsers cancel the download before it starts.+ */+export const downloadFile = (file: File): void => {+ const url = URL.createObjectURL(file);+ const link = document.createElement('a');++ link.href = url;+ link.download = file.name;+ link.click();+ window.setTimeout(() => URL.revokeObjectURL(url), DOWNLOAD_URL_LIFETIME_MS);+};++/**+ * Copies a PNG to the clipboard and leaves the feedback to the caller; it+ * rejects where the browser cannot copy images. Call it inside the click with+ * the image still a promise: Safari refuses a write that only starts once the+ * image is ready.+ */+export const copyImageToClipboard = async (image: Promise<Blob>): Promise<void> =>+ navigator.clipboard.write([new ClipboardItem({ 'image/png': image })]);++/** Mirrors ContentSanitizer::stripHtml(): the text a network receives for an HTML caption. */export const htmlToPlainText = (html: string): string => {const withBreaks = htmldiff --git a/resources/js/pages/channels/Insights.vue b/resources/js/pages/channels/Insights.vueindex 5e7508cda..b4390e99d 100644--- a/resources/js/pages/channels/Insights.vue+++ b/resources/js/pages/channels/Insights.vue@@ -16,8 +16,8 @@ import LabelFilter from '@/components/labels/LabelFilter.vue';import PublishHeader from '@/components/publish/PublishHeader.vue';import { useAnalyticsCoveragePoll } from '@/composables/useAnalyticsCoveragePoll';import { getPlatformLabel } from '@/composables/usePlatformLogo';-import date from '@/date';import AppLayout from '@/layouts/AppLayout.vue';+import { accountLabel } from '@/lib/analyticsAccounts';import { showsPostTypeFilter } from '@/lib/channelInsights';import { insights } from '@/routes/app/channels';import type {@@ -52,8 +52,14 @@ useAnalyticsCoveragePoll(() => props.report?.coverage, {});const url = computed(() => insights.url(props.channel.id));-const span = (range: { start: string; end: string }): string =>- `${date.formatDayMonthYear(range.start)} – ${date.formatDayMonthYear(range.end)}`;+/** The channel as the share cards name it: its name or handle, else its network. */+const shareChannel = computed((): string =>+ accountLabel({+ name: props.channel.display_name,+ username: props.channel.username,+ platform: props.channel.platform,+ }),+);const selectedLabelIds = ref<string[]>(props.filters?.labels ?? []);const selectedUntagged = ref<boolean>(props.filters?.untagged ?? false);const selectedTypes = ref<string[]>(props.filters?.types ?? []);@@ -208,6 +214,7 @@ watch(selectedTypes, applyFilters, { deep: true });v-model:untagged="selectedUntagged":labels="labels ?? []"test-id="insights-label"+ sheet-below-sm/><PostTypeFilterv-if="showsTypeFilter"@@ -245,14 +252,9 @@ watch(selectedTypes, applyFilters, { deep: true });<SummaryCards:report="report":available-metrics="availableMetrics ?? []"- :subtitle="- $t('analytics.ranges.compared_to', {- current: span(report.range),- previous: span(report.previous_range),- })- "subtitle-testid="insights-range-caption":network="getPlatformLabel(channel.platform)"+ :channel="shareChannel"/><ChannelPublicationTablev-if="filters"@@ -264,7 +266,10 @@ watch(selectedTypes, applyFilters, { deep: true });:url="url":platform="channel.platform"/>- <ChannelMetricsCard :series="metricSeries" />+ <ChannelMetricsCard+ :series="metricSeries"+ :channel="shareChannel"+ /></template></template></div>diff --git a/resources/js/pages/insights/Index.vue b/resources/js/pages/insights/Index.vueindex 3ddf52edf..b3a596b14 100644--- a/resources/js/pages/insights/Index.vue+++ b/resources/js/pages/insights/Index.vue@@ -17,7 +17,6 @@ import EmptyState from '@/components/EmptyState.vue';import HeaderTitle from '@/components/HeaderTitle.vue';import PostChannelFilter from '@/components/posts/PostChannelFilter.vue';import { useAnalyticsCoveragePoll } from '@/composables/useAnalyticsCoveragePoll';-import date from '@/date';import AppLayout from '@/layouts/AppLayout.vue';import { accountColor } from '@/lib/analyticsColors';import { insights as insightsRoute } from '@/routes/app';@@ -87,9 +86,6 @@ watch(useAnalyticsCoveragePoll(() => props.report.coverage);-const span = (range: { start: string; end: string }): string =>- `${date.formatDayMonthYear(range.start)} – ${date.formatDayMonthYear(range.end)}`;-const accountColors = computed<Record<string, string>>(() => {const keys = [...new Set([@@ -151,6 +147,7 @@ const accountColors = computed<Record<string, string>>(() => {v-model="selectedChannelIds":channels="channelOptions"test-id="analytics-channel"+ sheet-below-sm/></div></div>@@ -174,12 +171,6 @@ const accountColors = computed<Record<string, string>>(() => {<SummaryCards:report="report":available-metrics="availableMetrics ?? undefined"- :subtitle="- $t('analytics.ranges.compared_to', {- current: span(report.range),- previous: span(report.previous_range),- })- "subtitle-testid="insights-range-caption"/><TopPostsdiff --git a/resources/js/pages/posts/Calendar.vue b/resources/js/pages/posts/Calendar.vueindex ce266bee9..244cce01d 100644--- a/resources/js/pages/posts/Calendar.vue+++ b/resources/js/pages/posts/Calendar.vue@@ -1,6 +1,7 @@<script setup lang="ts">import { Head, router, usePage } from '@inertiajs/vue3';import {+ IconCheck,IconLayoutSidebarRightCollapse,IconLayoutSidebarRightExpand,IconPlus,@@ -287,6 +288,12 @@ const toggleUndated = (): void => {reload(['undatedDrafts'], ['undatedDrafts']);};+/** On a phone the undated drafts open from the filter menu, which closes first. */+const openUndatedFromMenu = (close: () => void): void => {+ close();+ toggleUndated();+};+const closeUndated = (): void => {if (undatedOpen.value) {toggleUndated();@@ -658,13 +665,14 @@ const goToDay = (key: string): void => {/><div- class="flex shrink-0 items-center gap-1 md:ms-auto md:gap-0"+ class="flex shrink-0 items-center gap-2 md:ms-auto md:gap-0"data-testid="calendar-filters"><PostChannelFilterv-if="scope === 'all' && filterAccounts.length"v-model="selectedChannelIds":channels="filterAccounts"+ sheet-below-sm/><div class="shrink-0 max-md:hidden"><LabelFilter@@ -687,8 +695,27 @@ const goToDay = (key: string): void => {"@update:timezone="setTimezone"@update:show-slots="toggleSlots"- />- <AppHeaderActions>+ >+ <template+ v-if="!isDesktop"+ #compact-items="{ rowClass, close }"+ >+ <button+ type="button"+ :aria-pressed="undatedOpen"+ :class="rowClass"+ data-testid="calendar-no-date-menu"+ @click="openUndatedFromMenu(close)"+ >+ {{ $t('calendar.undated.title') }}+ <IconCheck+ v-if="undatedOpen"+ class="ms-auto size-4"+ />+ </button>+ </template>+ </PublishFilterMenu>+ <AppHeaderActions :on-phones="!channel"><ScheduleViewSwitchactive-view="calendar":list-href="listHref"@@ -704,7 +731,7 @@ const goToDay = (key: string): void => {</AppHeaderActions><Buttonvariant="ghost"- class="shrink-0 max-xl:size-8 max-xl:px-0 max-sm:border max-sm:border-border-strong"+ class="shrink-0 max-xl:size-8 max-xl:px-0 max-md:hidden":class="{ 'bg-accent': undatedOpen }":aria-pressed="undatedOpen"data-testid="calendar-no-date"diff --git a/resources/js/pages/publish/Index.vue b/resources/js/pages/publish/Index.vueindex cdf0d0930..654201a17 100644--- a/resources/js/pages/publish/Index.vue+++ b/resources/js/pages/publish/Index.vue@@ -879,6 +879,7 @@ const submitComposition = (v-if="scope === 'all' && filterAccounts.length"v-model="selectedChannelIds":channels="filterAccounts"+ sheet-below-sm/><PublishFilterMenu:timezone="timezone"diff --git a/resources/js/pages/settings/workspace/Mcp.vue b/resources/js/pages/settings/workspace/Mcp.vueindex c05816fa6..3a235c6d6 100644--- a/resources/js/pages/settings/workspace/Mcp.vue+++ b/resources/js/pages/settings/workspace/Mcp.vue@@ -2,7 +2,7 @@import { Head, usePoll } from '@inertiajs/vue3';import {IconDotsVertical,- IconPlugConnected,+ IconMcp,IconPlus,IconTrash,} from '@tabler/icons-vue';@@ -24,7 +24,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import date from '@/date';import SettingsLayout from '@/layouts/SettingsLayout.vue';import { DOCS_URL } from '@/lib/docs';-import { mcpClients, otherMcpClient, type McpClient } from '@/lib/mcpClients';+import { mcpAppLogos, mcpClients, otherMcpClient, type McpClient } from '@/lib/mcpClients';import { disconnect as mcpDisconnect } from '@/routes/app/mcp';import { fireCelebration } from '@/utils/confetti';@@ -42,15 +42,14 @@ const props = defineProps<{const docsUrl = `${DOCS_URL}/ai/introduction`;-/** Shows the Claude or ChatGPT mark when the connected app is one of them. */+/** The app's brand mark when it is one we know. */const connectedRows = computed(() =>- props.connectedClients.map((client) => ({- ...client,- app:- mcpClients.find((app) =>- client.name.toLowerCase().includes(app.label.toLowerCase()),- ) ?? null,- })),+ props.connectedClients.map((client) => {+ const name = client.name.toLowerCase();+ const brand = mcpAppLogos.find((app) => name.includes(app.name)) ?? null;++ return { ...client, brand };+ }),);const deleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);@@ -139,18 +138,18 @@ onBeforeUnmount(() => {<SettingsListRowv-for="client in connectedRows":key="client.client_id"- :icon="client.app ? undefined : IconPlugConnected"+ :icon="client.brand ? undefined : IconMcp":data-testid="`mcp-connected-client-${client.client_id}`">- <template v-if="client.app" #media>+ <template v-if="client.brand" #media><spanclass="inline-flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted">- <img- :src="client.app.logo"- alt=""- :class="['size-5 object-contain', client.app.logoClass]"- :data-testid="`mcp-connected-logo-${client.app.id}`"+ <component+ :is="client.brand.logo"+ aria-hidden="true"+ :class="['size-5 text-foreground', client.brand.logoClass]"+ :data-testid="`mcp-connected-logo-${client.brand.id}`"/></span></template>@@ -234,10 +233,10 @@ onBeforeUnmount(() => {<spanclass="inline-flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted">- <img- :src="client.logo"- alt=""- :class="['size-5 object-contain', client.logoClass]"+ <component+ :is="client.logo"+ aria-hidden="true"+ class="size-5 text-foreground"/></span></template>diff --git a/resources/js/pages/welcome/Mcp.vue b/resources/js/pages/welcome/Mcp.vueindex 840b0dfc2..ad7cceab3 100644--- a/resources/js/pages/welcome/Mcp.vue+++ b/resources/js/pages/welcome/Mcp.vue@@ -346,10 +346,10 @@ const goToSchedule = (): void => {:data-testid="`welcome-mcp-connect-${client.id}`"@click="connectWith(client)">- <img- :src="client.monoLogo"- alt=""- class="size-4 invert dark:invert-0"+ <component+ :is="client.logo"+ aria-hidden="true"+ class="size-4 fill-current"/>{{client.labelKey@@ -417,10 +417,10 @@ const goToSchedule = (): void => {<spanclass="inline-flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted">- <img- :src="client.logo"- alt=""- :class="['size-5 object-contain', client.logoClass]"+ <component+ :is="client.logo"+ aria-hidden="true"+ class="size-5 text-foreground"/></span><span class="flex min-w-0 flex-1 flex-col gap-0.5">diff --git a/resources/js/posthog.ts b/resources/js/posthog.tsindex 5894f3544..921756a1a 100644--- a/resources/js/posthog.ts+++ b/resources/js/posthog.ts@@ -1,7 +1,7 @@import type { Page } from '@inertiajs/core';import posthog from 'posthog-js';-import type { Auth, Usage } from './types';+import type { Auth, Usage } from '@/types';const apiKey = import.meta.env.VITE_POSTHOG_API_KEY as string | undefined;const host = import.meta.env.VITE_POSTHOG_HOST as string | undefined;diff --git a/resources/js/preferences.ts b/resources/js/preferences.tsindex e7414a8d0..ac9c5ec72 100644--- a/resources/js/preferences.ts+++ b/resources/js/preferences.ts@@ -1,7 +1,7 @@import { ref } from 'vue';-import dayjs from './dayjs';-import type { Auth } from './types';+import dayjs from '@/dayjs';+import type { Auth } from '@/types';export type Theme = 'light' | 'dark' | 'system';export type TimeFormat = '12h' | '24h';diff --git a/resources/js/ssr.ts b/resources/js/ssr.tsindex 0c43b75eb..7e794107a 100644--- a/resources/js/ssr.ts+++ b/resources/js/ssr.ts@@ -4,7 +4,7 @@ import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';import { createSSRApp, DefineComponent, h } from 'vue';import { renderToString } from 'vue/server-renderer';-import { syncContentTypeMediaRules } from './lib/contentTypeMediaRules';+import { syncContentTypeMediaRules } from '@/lib/contentTypeMediaRules';const appName = import.meta.env.VITE_APP_NAME || 'Laravel';diff --git a/resources/js/types/analytics.ts b/resources/js/types/analytics.tsindex 061a9a60e..5d123bec7 100644--- a/resources/js/types/analytics.ts+++ b/resources/js/types/analytics.ts@@ -8,6 +8,12 @@ export interface Comparison {change: number | null;}+/** A span of days, both ends included, as `Y-m-d` dates. */+export interface DateRange {+ start: string;+ end: string;+}+export interface AccountIdentityData {social_account_key: string;platform: string;@@ -18,28 +24,42 @@ export interface AccountIdentityData {verified_badge?: VerifiedBadge | null;}+/** A channel with one number of its own, as a bar chart's row. */+export interface AccountMetricRow {+ account: AccountIdentityData;+ value: number | null;+}++/** How the Followers card is drawn: per channel, over time, or the change per channel. */+export type FollowersChartMode = 'bar' | 'line' | 'growth';++/** How the Posts card is drawn: per channel, or over time split by channel. */+export type PostsChartMode = 'bar' | 'stacked';++/** How long one bar of a chart over time covers. */+export type BucketResolution = 'daily' | 'weekly' | 'monthly';+export interface FollowerAccount extends AccountIdentityData {social_account_id: string | null;network: string;value: number | null;growth: number | null;net?: number | null;- provenance: string | null;}export interface PostAccount extends AccountIdentityData {count: number;}-export interface PostBucket {- start: string;- end: string;+export interface PostBucket extends DateRange {accounts: Record<string, number>;total: number;}export interface TopPost {id: string;+ /** Its place in the Top 5, from 1. */+ rank: number;post_id: string | null;social_account_key: string;platform: string;@@ -96,8 +116,8 @@ export interface CoverageRow {export interface AnalyticsReport {bounds: { min: string | null; max: string | null };- range: { start: string; end: string };- previous_range: { start: string; end: string };+ range: DateRange;+ previous_range: DateRange;summary: {posts: Comparison;followers: Comparison;@@ -123,7 +143,9 @@ export interface AnalyticsReport {series: { date: string; accounts: Record<string, number | null> }[];};posts: {- resolution: string;+ resolution: BucketResolution;+ /** Every post the channels sent over the period. */+ total: number;accounts: PostAccount[];buckets: PostBucket[];};@@ -193,17 +215,17 @@ export interface FollowerGrowthMonth {}export interface FollowerGrowthRate {- range: { start: string; end: string };+ range: DateRange;months: FollowerGrowthMonth[];latest: number | null;previous: number | null;}export interface ChannelMetricSeries {- resolution: 'daily' | 'weekly' | 'monthly';+ resolution: BucketResolution;metrics: SeriesMetric[];- range: { start: string; end: string };- previous_range: { start: string; end: string };+ range: DateRange;+ previous_range: DateRange;current: MetricSeriesPoint[];previous: MetricSeriesPoint[];totals: { current: SeriesValues; previous: SeriesValues };diff --git a/resources/js/types/index.d.ts b/resources/js/types/index.d.tsindex 40395126f..70495ccb1 100644--- a/resources/js/types/index.d.ts+++ b/resources/js/types/index.d.ts@@ -123,6 +123,9 @@ export type AppPageProps<T extends Record<string, unknown> = Record<string, unknown>,> = T & SharedData;+/** A provider people sign in with besides their password. */+export type SocialProvider = 'google' | 'github';+export interface User {id: string;name: string;diff --git a/resources/js/utils/chunkedUpload.ts b/resources/js/utils/chunkedUpload.tsindex 7fcb53273..6bb4de685 100644--- a/resources/js/utils/chunkedUpload.ts+++ b/resources/js/utils/chunkedUpload.ts@@ -1,6 +1,9 @@+import { objectOmit } from '@vueuse/core';+import { classifyBy, MediaType } from '@/lib/mediaType';import { uuid } from '@/lib/uuid';import { probeVideoDuration } from '@/lib/videoDuration';+import type { MediaItem } from '@/types/media';interface ChunkedUploadOptions {file: File;@@ -15,15 +18,8 @@ interface ChunkedUploadOptions {onError?: (error: any) => void;}-interface ChunkedUploadResult {- id: string;- path?: string;- url: string;- type: MediaType;- mime_type?: string;- original_filename: string;- [key: string]: any;-}+/** What the server answers a chunk with: more to send, or, on the last one, the uploaded media (its MediaResource). */+type ChunkAnswer = { done?: false } | (MediaItem & { done: true });/** The server answered a chunk with an error status; `message` is its first validation message, when it sent one. */export class ChunkedUploadError extends Error {@@ -61,7 +57,7 @@ const sendChunk = (chunk: Blob,signal: AbortSignal | undefined,onChunkProgress: (loaded: number) => void,-): Promise<any> =>+): Promise<ChunkAnswer> =>new Promise((resolve, reject) => {if (signal?.aborted) {reject(new DOMException('Aborted', 'AbortError'));@@ -106,7 +102,8 @@ const sendChunk = (xhr.send(chunk);});-export const uploadChunked = async (options: ChunkedUploadOptions): Promise<ChunkedUploadResult> => {+/** Uploads the file in chunks; the last answer is the server's MediaResource, returned as the media item. */+export const uploadChunked = async (options: ChunkedUploadOptions): Promise<MediaItem> => {const {file,url,@@ -158,7 +155,8 @@ export const uploadChunked = async (options: ChunkedUploadOptions): Promise<Chunif (data.done) {onComplete?.(data);- return data;++ return objectOmit(data, ['done']);}}diff --git a/resources/views/app.blade.php b/resources/views/app.blade.phpindex a41f219bc..11fd6344c 100644--- a/resources/views/app.blade.php+++ b/resources/views/app.blade.php@@ -50,7 +50,7 @@<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:[email protected]&family=Outfit:wght@400;500;600;700&family=Roboto+Slab:wght@700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">- @vite(['resources/js/app.ts'])+ @vite(['resources/css/app.css', 'resources/js/app.ts'])@inertiaHead</head><body class="font-sans antialiased">diff --git a/tests/Browser/CalendarDragAndDropTest.php b/tests/Browser/CalendarDragAndDropTest.phpindex b01c59cb5..3e55245f8 100644--- a/tests/Browser/CalendarDragAndDropTest.php+++ b/tests/Browser/CalendarDragAndDropTest.php@@ -860,8 +860,7 @@ test('a drag that ends on its own cell sends nothing', function () {test('a post in the repeated hour of a daylight saving change dropped on its own cell sends nothing', function () {[$user, $channel] = calendarDragSetup();- $fallBack = CarbonImmutable::parse('first sunday of november this year', 'America/New_York');- $fallBack = $fallBack->isFuture() ? $fallBack : CarbonImmutable::parse('first sunday of november next year', 'America/New_York');+ $fallBack = calendarDragNextDstSunday('first sunday of november');$key = $fallBack->format('Y-m-d');$at = CarbonImmutable::parse("{$key} 06:30", 'UTC');$post = calendarDragPost($channel, $at);@@ -2837,7 +2836,7 @@ test('an older move refused by the server and answered after a newer one still stest('a move answered after the view changed is not announced as done without knowing', function () {[$user, $channel] = calendarDragSetup();- $day = calendarDragDay();+ $day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(14)->toImmutable();$key = $day->format('Y-m-d');$post = calendarDragPost($channel, $day->setTime(10, 30));$this->actingAs($user);@@ -2855,6 +2854,7 @@ test('a move answered after the view changed is not announced as done without kn$page->click('@calendar-view-month');waitForPath($page, route('app.calendar', ['view' => 'month'], absolute: false));waitFor($page, '@calendar-month-grid');+ $page->assertMissing("@calendar-day-{$key}");$post->forceFill(['status' => PostStatus::PendingApproval])->saveQuietly();$page->script('window.__releaseHeldRequests()');diff --git a/tests/Browser/ChannelMetricsCardTest.php b/tests/Browser/ChannelMetricsCardTest.phpindex d7ef9c222..eadec04c3 100644--- a/tests/Browser/ChannelMetricsCardTest.php+++ b/tests/Browser/ChannelMetricsCardTest.php@@ -14,32 +14,6 @@ use App\Models\Workspace;use Carbon\CarbonImmutable;use Illuminate\Support\Facades\Queue;-function waitForMetricsCardTestId(mixed $page, string $testId): void-{- $page->script(<<<JS- (async () => {- const selector = '[data-testid="{$testId}"]';- for (let attempt = 0; attempt < 600; attempt++) {- const element = document.querySelector(selector);- if (element && element.getBoundingClientRect().height > 0) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}--function waitForMetricsCardScript(mixed $page, string $condition): void-{- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 400; attempt++) {- if ({$condition}) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}-/*** @param array<string, mixed> $metrics*/@@ -118,7 +92,7 @@ beforeEach(function () {test('the metrics card loads after the page and opens on content impact', function () {$page = visit(route('app.channels.insights', $this->instagram));- waitForMetricsCardTestId($page, 'insights-metrics-chart');+ waitFor($page, '@insights-metrics-chart');$page->assertMissing('@insights-metrics-skeleton')->assertAttribute('@insights-preset-content_impact', 'aria-pressed', 'true')@@ -126,6 +100,10 @@ test('the metrics card loads after the page and opens on content impact', functi->assertVisible('@insights-preset-visibility')->assertVisible('@insights-preset-follower_growth_rate')->assertSeeIn('@insights-metrics-legend-posts-value', '6')+ ->assertSeeIn('@insights-metrics-legend-posts-change', '+500%')+ ->assertSeeIn('@insights-metrics-legend-followers-change', '+150')+ ->assertSeeIn('@insights-card-net_followers-value', '150')+ ->assertScript('/Posts|Followers/.test(document.querySelector("[data-testid=insights-metrics-chart]").textContent)', false)->assertVisible('@insights-metrics-legend-followers')->assertPresent('@insights-metrics-table')->assertScript('document.querySelectorAll("[data-testid=insights-metrics-bar]").length > 0', true)@@ -133,7 +111,7 @@ test('the metrics card loads after the page and opens on content impact', functi->assertMissing('@followers-bar')->assertMissing('@posts-chart-bar');- waitForMetricsCardTestId($page, 'insights-posts');+ waitFor($page, '@insights-posts');$page->assertScript('Boolean(document.querySelector("[data-testid=insights-posts]").compareDocumentPosition(document.querySelector("[data-testid=insights-metrics]")) & Node.DOCUMENT_POSITION_FOLLOWING)', true)->assertScript(<<<'JS'@@ -155,7 +133,7 @@ test('the metrics card loads after the page and opens on content impact', functitest('the card shows a skeleton while the series reloads for a new range', function () {$page = visit(route('app.channels.insights', $this->instagram));- waitForMetricsCardTestId($page, 'insights-metrics-chart');+ waitFor($page, '@insights-metrics-chart');$page->script(<<<'JS'window.__sawMetricsSkeleton = false;@@ -166,7 +144,7 @@ test('the card shows a skeleton while the series reloads for a new range', funct}).observe(document.body, { childList: true, subtree: true });JS);$page->click('@insights-range-7d');- waitForMetricsCardScript($page, 'new URLSearchParams(location.search).get("range") === "7d" && window.__sawMetricsSkeleton && document.querySelector("[data-testid=insights-metrics-chart]")');+ waitForCondition($page, 'new URLSearchParams(location.search).get("range") === "7d" && window.__sawMetricsSkeleton && document.querySelector("[data-testid=insights-metrics-chart]")');$page->assertScript('window.__sawMetricsSkeleton', true)->assertVisible('@insights-metrics-chart')@@ -175,10 +153,10 @@ test('the card shows a skeleton while the series reloads for a new range', functtest('the metric menu lists the channel metrics and switches the chart to one metric', function () {$page = visit(route('app.channels.insights', $this->instagram));- waitForMetricsCardTestId($page, 'insights-metric-menu');+ waitFor($page, '@insights-metric-menu');$page->click('@insights-metric-menu');- waitForMetricsCardTestId($page, 'insights-metric-option-reach');+ waitFor($page, '@insights-metric-option-reach');$page->assertScript('[...document.querySelectorAll("[data-testid^=insights-metric-option-]:not([data-testid$=-check])")].map((item) => item.dataset.testid.replace("insights-metric-option-", "")).join(",")', 'followers,reach,profile_visits,posts,net_followers')->assertSeeIn('@insights-metric-option-profile_visits', 'Profile Views')->assertSeeIn('@insights-metric-option-net_followers', 'Net New Followers')@@ -186,7 +164,7 @@ test('the metric menu lists the channel metrics and switches the chart to one me->assertMissing('@insights-metric-option-views')->assertMissing('@insights-metric-option-impressions')->click('@insights-metric-option-reach');- waitForMetricsCardTestId($page, 'insights-metrics-legend-reach');+ waitFor($page, '@insights-metrics-legend-reach');$page->assertAttribute('@insights-metric-primary', 'aria-pressed', 'true')->assertAttribute('@insights-preset-content_impact', 'aria-pressed', 'false')@@ -196,7 +174,7 @@ test('the metric menu lists the channel metrics and switches the chart to one me->assertSeeIn('@insights-metrics-legend-reach-value', '1.4K')->assertVisible('@insights-metrics-post-totals-note')->click('@insights-metric-menu');- waitForMetricsCardTestId($page, 'insights-metric-option-reach-check');+ waitFor($page, '@insights-metric-option-reach-check');$page->assertMissing('@insights-metric-option-posts-check')->assertNoJavaScriptErrors();@@ -204,10 +182,10 @@ test('the metric menu lists the channel metrics and switches the chart to one metest('the follower growth rate preset draws the last twelve months and ignores the filters', function () {$page = visit(route('app.channels.insights', ['account' => $this->instagram, 'range' => '7d']));- waitForMetricsCardTestId($page, 'insights-preset-follower_growth_rate');+ waitFor($page, '@insights-preset-follower_growth_rate');$page->click('@insights-preset-follower_growth_rate');- waitForMetricsCardTestId($page, 'insights-metrics-legend-growth_rate');+ waitFor($page, '@insights-metrics-legend-growth_rate');$page->assertAttribute('@insights-preset-follower_growth_rate', 'aria-pressed', 'true')->assertSeeIn('@insights-metrics-legend-growth_rate', 'Growth Rate')@@ -218,7 +196,7 @@ test('the follower growth rate preset draws the last twelve months and ignores t->assertScript('document.querySelectorAll("[data-testid=insights-metrics-table] tbody tr").length', 12)->assertScript('document.querySelector("[data-testid=insights-metrics-insight]").dataset.insight.startsWith("growth_rate.")', true)->click('@insights-preset-audience_growth');- waitForMetricsCardTestId($page, 'insights-metrics-modes');+ waitFor($page, '@insights-metrics-modes');$page->assertMissing('@insights-metrics-filters-note')->assertNoJavaScriptErrors();@@ -226,16 +204,16 @@ test('the follower growth rate preset draws the last twelve months and ignores ttest('presets swap the chart series and the selected preset and period survive a filter change', function () {$page = visit(route('app.channels.insights', $this->instagram));- waitForMetricsCardTestId($page, 'insights-preset-audience_growth');+ waitFor($page, '@insights-preset-audience_growth');$page->click('@insights-preset-audience_growth')->click('@insights-metrics-mode-both');- waitForMetricsCardTestId($page, 'insights-metrics-legend-net_followers-previous');+ waitFor($page, '@insights-metrics-legend-net_followers-previous');$page->click('@insights-post-type-filter');- waitForMetricsCardTestId($page, 'insights-post-type-option-instagram_reel');+ waitFor($page, '@insights-post-type-option-instagram_reel');$page->click('@insights-post-type-option-instagram_reel');- waitForMetricsCardScript($page, 'new URLSearchParams(location.search).getAll("types[]").includes("instagram_reel") && document.querySelector("[data-testid=insights-metrics-chart]") && document.querySelector("[data-testid=insights-preset-audience_growth]")?.getAttribute("aria-pressed") === "true" && document.querySelector("[data-testid=insights-metrics-mode-both]")?.getAttribute("aria-pressed") === "true" && document.querySelector("[data-testid=insights-metrics-legend-net_followers-previous]")');+ waitForCondition($page, 'new URLSearchParams(location.search).getAll("types[]").includes("instagram_reel") && document.querySelector("[data-testid=insights-metrics-chart]") && document.querySelector("[data-testid=insights-preset-audience_growth]")?.getAttribute("aria-pressed") === "true" && document.querySelector("[data-testid=insights-metrics-mode-both]")?.getAttribute("aria-pressed") === "true" && document.querySelector("[data-testid=insights-metrics-legend-net_followers-previous]")');$page->assertScript('decodeURIComponent(location.search).includes("instagram_reel")', true)->assertAttribute('@insights-preset-audience_growth', 'aria-pressed', 'true')@@ -245,7 +223,7 @@ test('presets swap the chart series and the selected preset and period survive a->assertMissing('@insights-metrics-legend-posts');$page->click('@insights-preset-visibility');- waitForMetricsCardTestId($page, 'insights-metrics-legend-profile_visits');+ waitFor($page, '@insights-metrics-legend-profile_visits');$page->assertVisible('@insights-metrics-legend-followers')->assertNoJavaScriptErrors();});@@ -253,7 +231,7 @@ test('presets swap the chart series and the selected preset and period survive atest('a one-day range still draws the posts of that day', function () {$today = CarbonImmutable::today('UTC');$page = visit(route('app.channels.insights', ['account' => $this->instagram, 'range' => 'custom', 'start' => $today->subDays(2)->toDateString(), 'end' => $today->subDays(2)->toDateString()]));- waitForMetricsCardTestId($page, 'insights-metrics-legend-posts-value');+ waitFor($page, '@insights-metrics-legend-posts-value');$page->assertSeeIn('@insights-metrics-legend-posts-value', '1')->assertVisible('@insights-metrics-chart')@@ -263,51 +241,51 @@ test('a one-day range still draws the posts of that day', function () {test('the mode toggle shows the comparison period and both periods', function () {$page = visit(route('app.channels.insights', $this->instagram));- waitForMetricsCardTestId($page, 'insights-metrics-mode-both');+ waitFor($page, '@insights-metrics-mode-both');$page->assertMissing('@insights-metrics-legend-posts-previous')->assertSeeIn('@insights-metrics-mode-previous', 'Comparison')->click('@insights-metrics-mode-both');- waitForMetricsCardTestId($page, 'insights-metrics-legend-posts-previous');+ waitFor($page, '@insights-metrics-legend-posts-previous');$page->assertSeeIn('@insights-metrics-legend-posts-previous', '1')->assertSeeIn('@insights-metrics-legend-posts-value', '6')->assertAttribute('@insights-metrics-mode-both', 'aria-pressed', 'true')->assertScript('document.querySelectorAll("[data-testid=insights-metrics-bar]").length > 0', true)->click('@insights-metrics-mode-previous');- waitForMetricsCardScript($page, 'document.querySelector("[data-testid=insights-metrics-legend-posts-value]")?.textContent.trim() === "1"');+ waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-legend-posts-value]")?.textContent.trim() === "1"');$page->assertSeeIn('@insights-metrics-legend-posts-value', '1')->assertMissing('@insights-metrics-legend-posts-previous')- ->assertScript('document.querySelector("[data-testid=insights-metrics-chart]").textContent.includes("Posts (comparison)")', true)+ ->assertMissing('@insights-metrics-legend-posts-change')->assertNoJavaScriptErrors();});test('the insight banner reads the selected chart against the previous period', function () {$page = visit(route('app.channels.insights', $this->instagram));- waitForMetricsCardTestId($page, 'insights-metrics-insight');+ waitFor($page, '@insights-metrics-insight');$page->assertAttribute('@insights-metrics-insight', 'data-insight', 'content_impact.down')->assertSeeIn('@insights-metrics-insight', 'Your content impact dropped this period.')->click('@insights-metric-primary');- waitForMetricsCardScript($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "posts.up"');+ waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "posts.up"');$page->assertSeeIn('@insights-metrics-insight', 'You posted more than last period.')->click('@insights-preset-audience_growth');- waitForMetricsCardScript($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "audience.up"');+ waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "audience.up"');$page->assertSeeIn('@insights-metrics-insight', 'Your audience grew this period.')->assertMissing('@insights-metrics-post-totals-note')->click('@insights-metrics-mode-previous');- waitForMetricsCardScript($page, 'document.querySelector("[data-testid=insights-metrics-mode-previous]")?.getAttribute("aria-pressed") === "true"');+ waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-mode-previous]")?.getAttribute("aria-pressed") === "true"');$page->assertAttribute('@insights-metrics-insight', 'data-insight', 'audience.up')->click('@insights-metrics-mode-both');- waitForMetricsCardScript($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight.startsWith("audience_compared")');+ waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight.startsWith("audience_compared")');$page->assertSeeIn('@insights-metrics-insight', 'Your audience grew')->click('@insights-preset-visibility');- waitForMetricsCardScript($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "visibility.up"');+ waitForCondition($page, 'document.querySelector("[data-testid=insights-metrics-insight]")?.dataset.insight === "visibility.up"');$page->assertSeeIn('@insights-metrics-insight', 'More people discovered you than last period.')->assertNoJavaScriptErrors();@@ -315,7 +293,7 @@ test('the insight banner reads the selected chart against the previous period',test('on a phone the presets wrap and the mode toggle sits under the legend', function () {$page = visit(route('app.channels.insights', $this->instagram))->resize(390, 844);- waitForMetricsCardTestId($page, 'insights-metrics-chart');+ waitFor($page, '@insights-metrics-chart');$page->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)->assertScript(<<<'JS'@@ -337,27 +315,150 @@ test('on a phone the presets wrap and the mode toggle sits under the legend', futest('the column chooser hides and adds columns and remembers the choice', function () {$page = visit(route('app.channels.insights', $this->instagram));- waitForMetricsCardTestId($page, 'insights-columns-trigger');+ waitFor($page, '@insights-columns-trigger');$page->assertVisible('@insights-sort-views')->assertMissing('@insights-column-head-watch_time_minutes')->click('@insights-columns-trigger');- waitForMetricsCardTestId($page, 'insights-column-views');+ waitFor($page, '@insights-column-views');$page->assertMissing('@insights-column-impressions')->click('@insights-column-views');- waitForMetricsCardScript($page, '!document.querySelector("[data-testid=insights-sort-views]")');+ waitForCondition($page, '!document.querySelector("[data-testid=insights-sort-views]")');$page->click('@insights-column-watch_time_minutes');- waitForMetricsCardTestId($page, 'insights-column-head-watch_time_minutes');+ waitFor($page, '@insights-column-head-watch_time_minutes');$page->assertMissing('@insights-sort-views')->assertVisible('@insights-column-head-watch_time_minutes')->assertVisible('@insights-column-views');$page->refresh();- waitForMetricsCardTestId($page, 'insights-column-head-watch_time_minutes');+ waitFor($page, '@insights-column-head-watch_time_minutes');$page->assertMissing('@insights-sort-views')->assertVisible('@insights-sort-reactions')->assertNoJavaScriptErrors();});++test('a chart whose metrics have nothing in the previous period offers no comparison', function () {+ $fresh = SocialAccount::factory()->create([+ 'workspace_id' => $this->instagram->workspace_id,+ 'platform' => Platform::Instagram,+ ]);+ $today = CarbonImmutable::today('UTC');++ foreach (range(0, 9) as $daysAgo) {+ metricsCardFollowers($fresh, $today->subDays($daysAgo), 500 - $daysAgo);+ }++ $page = visit(route('app.channels.insights', $fresh));+ waitFor($page, '@insights-metric-menu');+ $page->click('@insights-metric-menu');+ waitFor($page, '@insights-metric-option-followers');+ $page->click('@insights-metric-option-followers');+ waitFor($page, '@insights-metrics-legend-followers');++ $page->assertMissing('@insights-metrics-mode-current')+ ->assertMissing('@insights-metrics-mode-both')+ ->assertSeeIn('@insights-metrics-legend-followers-change', '+9')+ ->assertNoJavaScriptErrors();+});++test('the axis prints each tick exactly, with the decimals a half step needs', function () {+ $busy = SocialAccount::factory()->create([+ 'workspace_id' => $this->instagram->workspace_id,+ 'platform' => Platform::Instagram,+ ]);+ $day = CarbonImmutable::today('UTC')->subDays(3)->setTime(10, 0);++ foreach (range(1, 9) as $minutes) {+ metricsCardPublication($busy, $day->addMinutes($minutes), ['reactions_count' => 1]);+ }++ $page = visit(route('app.channels.insights', $busy));+ waitFor($page, '@insights-metrics-left-tick');++ $page->assertScript('Array.from(document.querySelectorAll("[data-testid=insights-metrics-left-tick]"), (tick) => tick.textContent.trim()).join(",")', '0,2.5,5,7.5,10')+ ->assertNoJavaScriptErrors();+});++test('net new followers change by a count, never a percentage', function () {+ $page = visit(route('app.channels.insights', $this->instagram));+ waitFor($page, '@insights-metric-menu');+ $page->click('@insights-metric-menu');+ waitFor($page, '@insights-metric-option-net_followers');+ $page->click('@insights-metric-option-net_followers');+ waitFor($page, '@insights-metrics-legend-net_followers-change');++ expect($page->script('document.querySelector(\'[data-testid="insights-metrics-legend-net_followers-change"]\').innerText.trim()'))->toMatch('/^[+-]?\d+$/');+ $page->assertNoJavaScriptErrors();+});++test('a metric shows no change when the previous period had none of it', function () {+ $fresh = SocialAccount::factory()->create([+ 'workspace_id' => $this->instagram->workspace_id,+ 'platform' => Platform::Instagram,+ ]);+ $today = CarbonImmutable::today('UTC');+ metricsCardFollowers($fresh, $today->subDays(1), 400);++ foreach ([3, 1] as $daysAgo) {+ metricsCardPublication($fresh, $today->subDays($daysAgo)->setTime(10, 0), ['reactions_count' => 1]);+ }++ $page = visit(route('app.channels.insights', $fresh));+ waitFor($page, '@insights-metrics-legend-posts-value');++ $page->assertSeeIn('@insights-metrics-legend-posts-value', '2')+ ->assertMissing('@insights-metrics-legend-posts-change')+ ->assertNoJavaScriptErrors();+});++test('the channel chart shares the period the view shows: the previous one in Comparison, both in Both', function (string $mode) {+ $page = visit(route('app.channels.insights', $this->instagram));+ waitFor($page, '@insights-metrics-legend-followers-value');+ $current = trim((string) $page->script('document.querySelector(\'[data-testid="insights-metrics-legend-followers-value"]\').innerText'));+ $page->click("@insights-metrics-mode-{$mode}");+ waitForState($page, "@insights-metrics-mode-{$mode}", "element.getAttribute('aria-pressed') === 'true'");+ recordCanvasDrawing($page);+ $page->click('@share-channel-metrics');+ waitForState($page, '@share-chart-preview', "element.dataset.state === 'ready'");++ $drawn = $page->script('window.__drawn.map((entry) => entry.text)');++ expect($page->script('window.__patterns > 0'))->toBeTrue()+ ->and(in_array($current, $drawn, true))->toBe($mode === 'both')+ ->and(in_array('+500%', $drawn, true))->toBe($mode === 'both');+ $page->assertAttribute('@share-chart-preview', 'data-shape', 'combo')+ ->assertNoJavaScriptErrors();+})->with(['previous', 'both']);++test('a wide legend in the Both view shrinks on the share card to leave the channel’s name its room', function () {+ $wide = SocialAccount::factory()->create([+ 'workspace_id' => $this->instagram->workspace_id,+ 'platform' => Platform::Instagram,+ 'display_name' => 'Castellano Creative Studio',+ ]);+ $today = CarbonImmutable::today('UTC');++ foreach (range(0, 94) as $daysAgo) {+ metricsCardFollowers($wide, $today->subDays($daysAgo), 987654 - $daysAgo * 1111);+ }++ foreach (range(1, 60, 3) as $daysAgo) {+ metricsCardPublication($wide, $today->subDays($daysAgo)->setTime(10, 0), ['reactions_count' => 1]);+ }++ $page = visit(route('app.channels.insights', $wide));+ waitFor($page, '@insights-metrics-mode-both');+ $page->click('@insights-metrics-mode-both');+ waitForState($page, '@insights-metrics-mode-both', "element.getAttribute('aria-pressed') === 'true'");+ recordCanvasDrawing($page);+ $page->click('@share-channel-metrics');+ waitForState($page, '@share-chart-preview', "element.dataset.state === 'ready'");++ $figureSize = $page->script('Number(window.__drawn.findLast((entry) => entry.text === "987.7K").font.match(/(\\d+(?:\\.\\d+)?)px/)[1])');++ expect($figureSize)->toBeLessThan(52);+ $page->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/ComposerMediaSourcesTest.php b/tests/Browser/ComposerMediaSourcesTest.phpindex 74bcb0ae4..7837643f1 100644--- a/tests/Browser/ComposerMediaSourcesTest.php+++ b/tests/Browser/ComposerMediaSourcesTest.php@@ -177,7 +177,13 @@ test('the toolbar has one media button whose menu lists the upload first, then texpect($page->script("Array.from(document.querySelectorAll('[data-testid=\"composer-base-media-source-list\"] [data-testid^=\"media-source-\"]')).map((item) => item.dataset.testid)"))->toBe(['media-source-upload', 'media-source-canva', 'media-source-unsplash']);- $page->assertPresent('[data-testid="media-source-unsplash"] svg[fill="currentColor"]');+ expect($page->script(<<<'JS'+ (() => {+ const mark = document.querySelector('[data-testid="media-source-unsplash"] svg');++ return getComputedStyle(mark).fill === getComputedStyle(mark).color;+ })()+ JS))->toBeTrue();$page->click('@media-source-unsplash');waitForComposerMediaSourcesTestId($page, 'unsplash-dialog');diff --git a/tests/Browser/CreateIdeasBoardTest.php b/tests/Browser/CreateIdeasBoardTest.phpindex 3595fc02e..96cf06c29 100644--- a/tests/Browser/CreateIdeasBoardTest.php+++ b/tests/Browser/CreateIdeasBoardTest.php@@ -9,37 +9,6 @@ use App\Models\Workspace;use App\Models\WorkspaceLabel;use Pest\Browser\Playwright\Client;-function waitForCreateIdeasBoardTestId(mixed $page, string $testId): void-{- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}--function waitForCreateIdeasBoardCondition(mixed $page, string $condition): void-{- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if ({$condition}) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}--function waitForCreateIdeasBoardDatabase(mixed $page, Closure $condition): void-{- for ($attempt = 0; $attempt < 50 && ! $condition(); $attempt++) {- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');- }-}-/*** @return array{0: User, 1: Workspace, 2: array<string, IdeaStage>}*/@@ -162,9 +131,9 @@ test('dragging a card onto another in the same column reorders it', function ()$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-{$b->id}");+ waitFor($page, "@idea-card-{$b->id}");$page->drag("@idea-card-{$b->id}", "@idea-card-{$a->id}");- waitForCreateIdeasBoardDatabase($page, fn (): bool => $b->refresh()->position < $a->refresh()->position);+ waitForDatabase($page, fn (): bool => $b->refresh()->position < $a->refresh()->position);expect($b->refresh()->position)->toBeLessThan($a->refresh()->position);$page->assertNoJavaScriptErrors();@@ -176,9 +145,9 @@ test('dragging a card onto an empty column moves it there', function () {$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-{$a->id}");+ waitFor($page, "@idea-card-{$a->id}");$page->drag("@idea-card-{$a->id}", "@idea-column-{$stages['done']->id}");- waitForCreateIdeasBoardDatabase($page, fn (): bool => $a->refresh()->idea_stage_id === $stages['done']->id);+ waitForDatabase($page, fn (): bool => $a->refresh()->idea_stage_id === $stages['done']->id);expect($a->refresh()->idea_stage_id)->toBe($stages['done']->id);$page->assertNoJavaScriptErrors();@@ -189,21 +158,21 @@ test('a new stage is created on enter and nothing is created on escape', functio$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, 'idea-stage-new');+ waitFor($page, '@idea-stage-new');$page->click('@idea-stage-new');- waitForCreateIdeasBoardTestId($page, 'idea-stage-new-input');+ waitFor($page, '@idea-stage-new-input');$page->type('@idea-stage-new-input', 'Reviewed')->keys('@idea-stage-new-input', 'Enter');- waitForCreateIdeasBoardDatabase($page, fn (): bool => $workspace->ideaStages()->where('name', 'Reviewed')->exists());+ waitForDatabase($page, fn (): bool => $workspace->ideaStages()->where('name', 'Reviewed')->exists());$stage = $workspace->ideaStages()->where('name', 'Reviewed')->firstOrFail();- waitForCreateIdeasBoardTestId($page, "idea-column-{$stage->id}");+ waitFor($page, "@idea-column-{$stage->id}");$page->assertVisible("@idea-column-{$stage->id}");- waitForCreateIdeasBoardTestId($page, 'idea-stage-new');+ waitFor($page, '@idea-stage-new');$page->click('@idea-stage-new');- waitForCreateIdeasBoardTestId($page, 'idea-stage-new-input');+ waitFor($page, '@idea-stage-new-input');$page->type('@idea-stage-new-input', 'Discarded')->keys('@idea-stage-new-input', 'Escape');- waitForCreateIdeasBoardTestId($page, 'idea-stage-new');+ waitFor($page, '@idea-stage-new');expect($workspace->ideaStages()->count())->toBe(4);$page->assertMissing('@idea-stage-new-input')@@ -216,14 +185,14 @@ test('deleting a stage keeps its ideas under unassigned', function () {$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-column-menu-{$stages['todo']->id}");+ waitFor($page, "@idea-column-menu-{$stages['todo']->id}");$page->click("@idea-column-menu-{$stages['todo']->id}");- waitForCreateIdeasBoardTestId($page, "idea-stage-delete-{$stages['todo']->id}");+ waitFor($page, "@idea-stage-delete-{$stages['todo']->id}");$page->click("@idea-stage-delete-{$stages['todo']->id}");- waitForCreateIdeasBoardTestId($page, 'confirm-delete-action');+ waitFor($page, '@confirm-delete-action');$page->assertMissing('@confirm-delete-input')->click('@confirm-delete-action');- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"idea-column-{$stages['todo']->id}\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"idea-column-{$stages['todo']->id}\"]')");$page->assertMissing("@idea-column-{$stages['todo']->id}");expect($page->script("!!document.querySelector('[data-testid=\"idea-column-unassigned\"] [data-testid=\"idea-card-{$a->id}\"]')"))->toBeTrue()@@ -236,10 +205,10 @@ test('dragging a stage handle onto another column reorders the stages', function$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-stage-handle-{$stages['done']->id}");+ waitFor($page, "@idea-stage-handle-{$stages['done']->id}");$page->hover("@idea-column-{$stages['done']->id}");$page->drag("@idea-stage-handle-{$stages['done']->id}", "@idea-column-{$stages['todo']->id}");- waitForCreateIdeasBoardDatabase($page, fn (): bool => $stages['done']->refresh()->position < $stages['in_progress']->refresh()->position);+ waitForDatabase($page, fn (): bool => $stages['done']->refresh()->position < $stages['in_progress']->refresh()->position);expect($stages['done']->refresh()->position)->toBeLessThan($stages['in_progress']->refresh()->position);$page->assertNoJavaScriptErrors();@@ -253,31 +222,31 @@ test('selected ideas are deleted in bulk and the selection can be cleared', func$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-menu-{$a->id}");+ waitFor($page, "@idea-card-menu-{$a->id}");$page->click("@idea-card-menu-{$a->id}");- waitForCreateIdeasBoardTestId($page, "idea-select-{$a->id}");+ waitFor($page, "@idea-select-{$a->id}");$page->click("@idea-select-{$a->id}");- waitForCreateIdeasBoardTestId($page, "idea-card-checkbox-{$b->id}");+ waitFor($page, "@idea-card-checkbox-{$b->id}");$page->click("@idea-card-checkbox-{$b->id}");- waitForCreateIdeasBoardTestId($page, 'ideas-bulk-delete');+ waitFor($page, '@ideas-bulk-delete');$page->assertSeeIn('@ideas-bulk-delete', '2')->click('@ideas-bulk-delete');- waitForCreateIdeasBoardTestId($page, 'ideas-bulk-delete-confirm');+ waitFor($page, '@ideas-bulk-delete-confirm');$page->assertMissing('@confirm-delete-input')->click('@ideas-bulk-delete-confirm');- waitForCreateIdeasBoardDatabase($page, fn (): bool => Idea::whereKey([$a->id, $b->id])->doesntExist());+ waitForDatabase($page, fn (): bool => Idea::whereKey([$a->id, $b->id])->doesntExist());expect(Idea::whereKey([$a->id, $b->id])->exists())->toBeFalse()->and(Idea::whereKey($c->id)->exists())->toBeTrue();- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");$page->assertMissing('@ideas-bulk-bar');$page->click("@idea-card-menu-{$c->id}");- waitForCreateIdeasBoardTestId($page, "idea-select-{$c->id}");+ waitFor($page, "@idea-select-{$c->id}");$page->click("@idea-select-{$c->id}");- waitForCreateIdeasBoardTestId($page, 'ideas-clear-selection');+ waitFor($page, '@ideas-clear-selection');$page->click('@ideas-clear-selection');- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");$page->assertMissing('@ideas-bulk-bar')->assertMissing("@idea-card-checkbox-{$c->id}")@@ -294,9 +263,9 @@ test('the gallery view lists ideas and filters them by label and stage', functio$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, 'ideas-view-gallery');+ waitFor($page, '@ideas-view-gallery');$page->click('@ideas-view-gallery');- waitForCreateIdeasBoardTestId($page, 'ideas-gallery');+ waitFor($page, '@ideas-gallery');$page->assertVisible("@idea-card-{$tagged->id}")->assertVisible("@idea-card-{$inDone->id}")@@ -304,34 +273,34 @@ test('the gallery view lists ideas and filters them by label and stage', functioexpect($page->script('location.search'))->toContain('view=gallery');$page->click('@ideas-filter-labels-filter');- waitForCreateIdeasBoardTestId($page, "ideas-filter-labels-option-{$label->id}");+ waitFor($page, "@ideas-filter-labels-option-{$label->id}");$page->click("@ideas-filter-labels-option-{$label->id}");- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$loose->id}\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$loose->id}\"]')");$page->assertVisible("@idea-card-{$tagged->id}")->assertMissing("@idea-card-{$loose->id}")->assertMissing("@idea-card-{$inDone->id}");$page->click("@ideas-filter-labels-option-{$label->id}");- waitForCreateIdeasBoardTestId($page, "idea-card-{$loose->id}");+ waitFor($page, "@idea-card-{$loose->id}");$page->click('@ideas-filter-labels-untagged-checkbox');- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$tagged->id}\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$tagged->id}\"]')");$page->assertVisible("@idea-card-{$loose->id}")->assertMissing("@idea-card-{$tagged->id}");expect($page->script('location.search'))->toContain('untagged=1');$page->click('@ideas-filter-labels-clear');- waitForCreateIdeasBoardTestId($page, "idea-card-{$tagged->id}");+ waitFor($page, "@idea-card-{$tagged->id}");$page->assertVisible("@idea-card-{$loose->id}")->assertPresent('@ideas-filter-labels-settings');$page->keys('@ideas-filter-labels-search', 'Escape');- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"ideas-filter-labels-search\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-filter-labels-search\"]')");$page->click('@ideas-filter-stages-filter');- waitForCreateIdeasBoardTestId($page, "ideas-filter-stages-option-{$stages['done']->id}");+ waitFor($page, "@ideas-filter-stages-option-{$stages['done']->id}");$page->assertScript("document.querySelector('[data-testid=\"ideas-filter-stages-option-{$stages['done']->id}\"]').getBoundingClientRect().height <= 32", true);$page->click("@ideas-filter-stages-option-{$stages['done']->id}");- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$loose->id}\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$loose->id}\"]')");$page->assertVisible("@idea-card-{$inDone->id}")->assertMissing("@idea-card-{$tagged->id}")@@ -346,7 +315,7 @@ test('a drop made while a move is in flight is applied after the first move comp$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-{$b->id}");+ waitFor($page, "@idea-card-{$b->id}");$page->script(<<<'JS'(() => {const open = XMLHttpRequest.prototype.open;@@ -369,16 +338,16 @@ test('a drop made while a move is in flight is applied after the first move compJS);$page->drag("@idea-card-{$a->id}", "@idea-column-{$stages['done']->id}");- waitForCreateIdeasBoardCondition($page, 'window.__ideaMoves.length === 1');+ waitForCondition($page, 'window.__ideaMoves.length === 1');$page->drag("@idea-card-{$b->id}", "@idea-column-{$stages['done']->id}");- waitForCreateIdeasBoardCondition($page, "!!document.querySelector('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-idea-id=\"{$b->id}\"]')");+ waitForCondition($page, "!!document.querySelector('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-idea-id=\"{$b->id}\"]')");expect($page->script('window.__ideaMoves.length'))->toBe(1)->and($a->refresh()->idea_stage_id)->toBe($stages['todo']->id)->and($b->refresh()->idea_stage_id)->toBe($stages['todo']->id);$page->script('window.__releaseIdeaMove()');- waitForCreateIdeasBoardDatabase($page, fn (): bool => $b->refresh()->idea_stage_id === $stages['done']->id);+ waitForDatabase($page, fn (): bool => $b->refresh()->idea_stage_id === $stages['done']->id);$order = $page->script("[...document.querySelectorAll('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-idea-id]')].map((el) => el.dataset.ideaId)");expect($page->script('window.__ideaMoves.length'))->toBe(2)@@ -397,18 +366,18 @@ test('move to stage works on a filtered board and appends to the end of the stag$this->actingAs($user);$page = visit(route('app.create.ideas.index', ['labels' => [$label->id]]));- waitForCreateIdeasBoardTestId($page, 'ideas-drag-disabled-hint');- waitForCreateIdeasBoardTestId($page, "idea-card-menu-{$a->id}");+ waitFor($page, '@ideas-drag-disabled-hint');+ waitFor($page, "@idea-card-menu-{$a->id}");$page->click("@idea-card-menu-{$a->id}");- waitForCreateIdeasBoardTestId($page, "idea-move-{$a->id}");+ waitFor($page, "@idea-move-{$a->id}");$page->click("@idea-move-{$a->id}");- waitForCreateIdeasBoardTestId($page, "idea-move-to-{$a->id}-{$stages['done']->id}");+ waitFor($page, "@idea-move-to-{$a->id}-{$stages['done']->id}");$page->click("@idea-move-to-{$a->id}-{$stages['done']->id}");- waitForCreateIdeasBoardDatabase($page, fn (): bool => $a->refresh()->idea_stage_id === $stages['done']->id);+ waitForDatabase($page, fn (): bool => $a->refresh()->idea_stage_id === $stages['done']->id);expect($a->refresh()->idea_stage_id)->toBe($stages['done']->id)->and($a->position)->toBeGreaterThan($existing->refresh()->position);- waitForCreateIdeasBoardCondition($page, "!!document.querySelector('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-testid=\"idea-card-{$a->id}\"]')");+ waitForCondition($page, "!!document.querySelector('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-testid=\"idea-card-{$a->id}\"]')");expect($page->script("!!document.querySelector('[data-testid=\"idea-column-{$stages['done']->id}\"] [data-testid=\"idea-card-{$a->id}\"]')"))->toBeTrue();$page->assertNoJavaScriptErrors();});@@ -420,17 +389,17 @@ test('changing a filter clears the selection', function () {$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-menu-{$a->id}");+ waitFor($page, "@idea-card-menu-{$a->id}");$page->click("@idea-card-menu-{$a->id}");- waitForCreateIdeasBoardTestId($page, "idea-select-{$a->id}");+ waitFor($page, "@idea-select-{$a->id}");$page->click("@idea-select-{$a->id}");- waitForCreateIdeasBoardTestId($page, 'ideas-bulk-bar');- waitForCreateIdeasBoardCondition($page, "document.body.style.pointerEvents !== 'none' && !document.querySelector('[role=\"menu\"]')");+ waitFor($page, '@ideas-bulk-bar');+ waitForCondition($page, "document.body.style.pointerEvents !== 'none' && !document.querySelector('[role=\"menu\"]')");$page->click('@ideas-filter-labels-filter');- waitForCreateIdeasBoardTestId($page, 'ideas-filter-labels-untagged-checkbox');+ waitFor($page, '@ideas-filter-labels-untagged-checkbox');$page->click('@ideas-filter-labels-untagged-checkbox');- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-bulk-bar\"]')");$page->assertMissing('@ideas-bulk-bar')->assertNoJavaScriptErrors();@@ -442,11 +411,11 @@ test('deleting a single idea asks for confirmation without typing a keyword', fu$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-menu-{$a->id}");+ waitFor($page, "@idea-card-menu-{$a->id}");$page->click("@idea-card-menu-{$a->id}");- waitForCreateIdeasBoardTestId($page, "idea-delete-{$a->id}");+ waitFor($page, "@idea-delete-{$a->id}");$page->click("@idea-delete-{$a->id}");- waitForCreateIdeasBoardTestId($page, 'confirm-delete-action');+ waitFor($page, '@confirm-delete-action');expect(trim($page->script("document.querySelector('[data-testid=\"confirm-delete-modal\"] [data-slot=\"dialog-description\"]')?.textContent ?? ''")))->toBe(__('create.ideas.delete_confirm_body'));@@ -454,7 +423,7 @@ test('deleting a single idea asks for confirmation without typing a keyword', fu$page->assertMissing('@confirm-delete-input')->click('@confirm-delete-action');- waitForCreateIdeasBoardDatabase($page, fn (): bool => Idea::whereKey($a->id)->doesntExist());+ waitForDatabase($page, fn (): bool => Idea::whereKey($a->id)->doesntExist());expect(Idea::whereKey($a->id)->exists())->toBeFalse();$page->assertNoJavaScriptErrors();@@ -471,12 +440,12 @@ test('a lifted placeholder shows where a dragged card lands, in its own column a$done = $stages['done']->id;$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-{$d->id}");+ waitFor($page, "@idea-card-{$d->id}");$height = $page->script("document.querySelector('[data-testid=\"idea-card-{$c->id}\"]').parentElement.offsetHeight");createIdeasBoardRecordDragImages($page);createIdeasBoardPickUp($page, "idea-card-{$c->id}");- waitForCreateIdeasBoardTestId($page, 'idea-card-placeholder');+ waitFor($page, '@idea-card-placeholder');expect($page->script('window.__dragImages'))->toBe(['data:image'])->and($page->script("document.querySelector('[data-testid=\"idea-card-placeholder-preview\"]')?.textContent"))->toContain('Idea C')@@ -496,11 +465,11 @@ test('a lifted placeholder shows where a dragged card lands, in its own column a->and(createIdeasBoardIsDropTarget($page, $todo))->toBeFalse();createIdeasBoardMouse($page, 'mouseUp', ['button' => 'left', 'clickCount' => 1]);- waitForCreateIdeasBoardDatabase($page, fn (): bool => $c->refresh()->idea_stage_id === $done);+ waitForDatabase($page, fn (): bool => $c->refresh()->idea_stage_id === $done);expect($c->refresh()->idea_stage_id)->toBe($done)->and(Idea::where('idea_stage_id', $done)->orderBy('position')->pluck('id')->all())->toBe([$d->id, $c->id]);- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"idea-card-placeholder\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-placeholder\"]')");expect(createIdeasBoardCardSlots($page, $done))->toBe([$d->id, $c->id]);$page->assertNoJavaScriptErrors();});@@ -513,10 +482,10 @@ test('a card dropped outside every column goes back where it was', function () {$todo = $stages['todo']->id;$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-{$b->id}");+ waitFor($page, "@idea-card-{$b->id}");createIdeasBoardPickUp($page, "idea-card-{$b->id}");- waitForCreateIdeasBoardTestId($page, 'idea-card-placeholder');+ waitFor($page, '@idea-card-placeholder');createIdeasBoardMoveTo($page, "idea-card-{$a->id}", 0.5, 0.25);expect(createIdeasBoardCardSlots($page, $todo))->toBe(['placeholder', $a->id]);@@ -542,13 +511,13 @@ test('a dragged stage leaves a column-sized placeholder where it will land', fun$done = $stages['done']->id;$page = visit(route('app.create.ideas.index'))->resize(1440, 900);- waitForCreateIdeasBoardTestId($page, "idea-column-{$done}");+ waitFor($page, "@idea-column-{$done}");$width = $page->script("document.querySelector('[data-testid=\"idea-column-{$done}\"]').offsetWidth");createIdeasBoardRecordDragImages($page);$page->hover("@idea-column-{$done}");createIdeasBoardPickUp($page, "idea-stage-handle-{$done}");- waitForCreateIdeasBoardTestId($page, 'idea-stage-placeholder');+ waitFor($page, '@idea-stage-placeholder');expect($page->script('window.__dragImages'))->toBe(['data:image'])->and($page->script("document.querySelector('[data-testid=\"idea-stage-placeholder\"]').offsetWidth"))->toBe($width)@@ -560,10 +529,10 @@ test('a dragged stage leaves a column-sized placeholder where it will land', funexpect(createIdeasBoardStageSlots($page))->toBe(['placeholder', $todo, $progress]);createIdeasBoardMouse($page, 'mouseUp', ['button' => 'left', 'clickCount' => 1]);- waitForCreateIdeasBoardDatabase($page, fn (): bool => $stages['done']->refresh()->position < $stages['todo']->refresh()->position);+ waitForDatabase($page, fn (): bool => $stages['done']->refresh()->position < $stages['todo']->refresh()->position);expect($stages['done']->refresh()->position)->toBeLessThan($stages['todo']->refresh()->position);- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"idea-stage-placeholder\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"idea-stage-placeholder\"]')");expect(createIdeasBoardStageSlots($page))->toBe([$done, $todo, $progress]);$page->assertNoJavaScriptErrors();});@@ -576,15 +545,15 @@ test('the gallery stage filter has an unassigned option that combines with stage$this->actingAs($user);$page = visit(route('app.create.ideas.index', ['view' => 'gallery']));- waitForCreateIdeasBoardTestId($page, 'ideas-filter-stages-filter');+ waitFor($page, '@ideas-filter-stages-filter');$page->click('@ideas-filter-stages-filter');- waitForCreateIdeasBoardTestId($page, 'ideas-filter-stages-unassigned');+ waitFor($page, '@ideas-filter-stages-unassigned');expect($page->script("(() => { const rows = [...document.querySelector('[data-testid=\"ideas-filter-stages-unassigned\"]').parentElement.parentElement.querySelectorAll('[data-testid=\"ideas-filter-stages-unassigned\"], [data-testid^=\"ideas-filter-stages-option-\"]')]; return rows[0].dataset.testid; })()"))->toBe('ideas-filter-stages-unassigned')->and($page->script("document.querySelector('[data-testid=\"ideas-filter-stages-unassigned\"]').getBoundingClientRect().height"))->toBeLessThanOrEqual(32);$page->click('@ideas-filter-stages-unassigned-checkbox');- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$inTodo->id}\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"idea-card-{$inTodo->id}\"]')");$page->assertVisible("@idea-card-{$loose->id}")->assertMissing("@idea-card-{$inDone->id}")@@ -592,14 +561,14 @@ test('the gallery stage filter has an unassigned option that combines with stageexpect($page->script('location.search'))->toContain('unassigned=1');$page->click("@ideas-filter-stages-option-{$stages['todo']->id}");- waitForCreateIdeasBoardTestId($page, "idea-card-{$inTodo->id}");+ waitFor($page, "@idea-card-{$inTodo->id}");$page->assertVisible("@idea-card-{$loose->id}")->assertMissing("@idea-card-{$inDone->id}")->assertSeeIn('@ideas-filter-stages-count', '2');$page->click('@ideas-filter-stages-toggle-all');- waitForCreateIdeasBoardTestId($page, "idea-card-{$inDone->id}");+ waitFor($page, "@idea-card-{$inDone->id}");$page->assertVisible("@idea-card-{$loose->id}")->assertVisible("@idea-card-{$inTodo->id}")@@ -614,7 +583,7 @@ test('the new stage button turns into an empty column in place and escape brings$done = $stages['done']->id;$page = visit(route('app.create.ideas.index'))->resize(1600, 900);- waitForCreateIdeasBoardTestId($page, 'idea-stage-new');+ waitFor($page, '@idea-stage-new');$before = $page->script("(() => { const rect = document.querySelector('[data-testid=\"idea-stage-new\"]').getBoundingClientRect(); return { left: rect.left, top: rect.top }; })()");$page->click('@idea-stage-new');@@ -678,8 +647,8 @@ test('on a phone the label filter shows only its icon and the page does not scro$this->actingAs($user);$page = visit(route('app.create.ideas.index'))->resize(390, 844);- waitForCreateIdeasBoardTestId($page, 'ideas-filter-labels-filter');- waitForCreateIdeasBoardTestId($page, 'ideas-board');+ waitFor($page, '@ideas-filter-labels-filter');+ waitFor($page, '@ideas-board');expect($page->script(<<<'JS'(() => {@@ -696,7 +665,7 @@ test('on a phone the label filter shows only its icon and the page does not scroJS))->toBe(['visibleText' => 0, 'label' => true, 'overflow' => 0, 'boardScrolls' => true]);$page->resize(1280, 900);- waitForCreateIdeasBoardCondition($page, "[...document.querySelector('[data-testid=\"ideas-filter-labels-filter\"]').querySelectorAll('span')].some((span) => span.offsetParent !== null && span.textContent.trim() !== '')");+ waitForCondition($page, "[...document.querySelector('[data-testid=\"ideas-filter-labels-filter\"]').querySelectorAll('span')].some((span) => span.offsetParent !== null && span.textContent.trim() !== '')");expect($page->script("[...document.querySelector('[data-testid=\"ideas-filter-labels-filter\"]').querySelectorAll('span')].some((span) => span.offsetParent !== null && span.textContent.trim() !== '')"))->toBeTrue();$page->assertNoJavaScriptErrors();});@@ -708,13 +677,13 @@ test('scrolling a column loads its next ten ideas and the count comes from the d$page = visit(route('app.create.ideas.index'));$column = $stages['todo']->id;- waitForCreateIdeasBoardTestId($page, "idea-card-{$ideas[9]->id}");+ waitFor($page, "@idea-card-{$ideas[9]->id}");expect(createIdeasBoardCardSlots($page, $column))->toBe($ideas->take(10)->pluck('id')->all());$page->assertSeeIn("@idea-column-count-{$column}", '15');$page->script("document.querySelector('[data-testid=\"idea-column-scroll-{$column}\"]').scrollTop = 100000");- waitForCreateIdeasBoardCondition($page, "document.querySelectorAll('[data-testid=\"idea-column-list-{$column}\"] [data-sortable-idea]').length === 15");+ waitForCondition($page, "document.querySelectorAll('[data-testid=\"idea-column-list-{$column}\"] [data-sortable-idea]').length === 15");expect(createIdeasBoardCardSlots($page, $column))->toBe($ideas->pluck('id')->all());$page->assertSeeIn("@idea-column-count-{$column}", '15')@@ -728,9 +697,9 @@ test('dragging a card into a partly loaded column keeps the unloaded ideas in or$this->actingAs($user);$page = visit(route('app.create.ideas.index'));- waitForCreateIdeasBoardTestId($page, "idea-card-{$done[1]->id}");+ waitFor($page, "@idea-card-{$done[1]->id}");$page->drag("@idea-card-{$moving->id}", "@idea-card-{$done[1]->id}");- waitForCreateIdeasBoardDatabase($page, fn (): bool => $moving->refresh()->idea_stage_id === $stages['done']->id);+ waitForDatabase($page, fn (): bool => $moving->refresh()->idea_stage_id === $stages['done']->id);$order = Idea::where('idea_stage_id', $stages['done']->id)->orderBy('position')->get(['id', 'position']);$shown = createIdeasBoardCardSlots($page, $stages['done']->id);@@ -739,7 +708,7 @@ test('dragging a card into a partly loaded column keeps the unloaded ideas in or->and($order->pluck('id')->reject(fn (string $id): bool => $id === $moving->id)->values()->all())->toBe($done->pluck('id')->all())->and(array_slice($order->pluck('id')->all(), 0, count($shown)))->toBe($shown)->and($shown)->toContain($moving->id);- waitForCreateIdeasBoardCondition($page, "document.querySelector('[data-testid=\"idea-column-count-{$stages['done']->id}\"]').textContent.trim() === '13'");+ waitForCondition($page, "document.querySelector('[data-testid=\"idea-column-count-{$stages['done']->id}\"]').textContent.trim() === '13'");$page->assertSeeIn("@idea-column-count-{$stages['done']->id}", '13')->assertNoJavaScriptErrors();});@@ -750,11 +719,11 @@ test('the gallery stage filter search ignores accents and matches each word in a$this->actingAs($user);$page = visit(route('app.create.ideas.index', ['view' => 'gallery']));- waitForCreateIdeasBoardTestId($page, 'ideas-filter-stages-filter');+ waitFor($page, '@ideas-filter-stages-filter');$page->click('@ideas-filter-stages-filter');- waitForCreateIdeasBoardTestId($page, 'ideas-filter-stages-search');+ waitFor($page, '@ideas-filter-stages-search');$page->type('@ideas-filter-stages-search', 'FINAL revisao');- waitForCreateIdeasBoardCondition($page, "!document.querySelector('[data-testid=\"ideas-filter-stages-option-{$stages['todo']->id}\"]')");+ waitForCondition($page, "!document.querySelector('[data-testid=\"ideas-filter-stages-option-{$stages['todo']->id}\"]')");$page->assertPresent("@ideas-filter-stages-option-{$stages['in_progress']->id}")->assertMissing("@ideas-filter-stages-option-{$stages['todo']->id}")@@ -762,3 +731,17 @@ test('the gallery stage filter search ignores accents and matches each word in a->assertMissing('@ideas-filter-stages-unassigned')->assertNoJavaScriptErrors();});++test('on a phone the label filter opens as a sheet', function () {+ [$user, $workspace] = createIdeasBoardSetup();+ WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id]);+ $this->actingAs($user);++ $page = visit(route('app.create.ideas.index'))->resize(390, 844);+ waitFor($page, '@ideas-filter-labels-filter');+ $page->click('@ideas-filter-labels-filter');+ waitFor($page, '@ideas-filter-labels-sheet');++ $page->assertVisible('@ideas-filter-labels-sheet')+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/InsightsChannelFilterTest.php b/tests/Browser/InsightsChannelFilterTest.phpindex 6dbd95c5a..8fc1bd9e0 100644--- a/tests/Browser/InsightsChannelFilterTest.php+++ b/tests/Browser/InsightsChannelFilterTest.php@@ -13,20 +13,6 @@ use App\Models\User;use App\Models\Workspace;use Illuminate\Support\Facades\Queue;-function waitForInsightsChannelTestId(mixed $page, string $testId): void-{- $page->script(<<<JS- (async () => {- const selector = '[data-testid="{$testId}"]';- for (let attempt = 0; attempt < 200; attempt++) {- const element = document.querySelector(selector);- if (element && element.getBoundingClientRect().height > 0) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}-/** @return array{0: User, 1: list<SocialAccount>} */function insightsChannelFilterFixture(): array{@@ -84,10 +70,10 @@ test('the channel filter scopes the dashboard and keeps the channel in the url',$this->actingAs($user);$page = visit(route('app.insights'));- waitForInsightsChannelTestId($page, 'analytics-channel-filter');+ waitFor($page, '@analytics-channel-filter');$page->assertScript('document.querySelectorAll("[data-testid=analytics-performance-caption]").length', 1)->click('@analytics-channel-filter');- waitForInsightsChannelTestId($page, "analytics-channel-checkbox-{$alpha->id}");+ waitFor($page, "@analytics-channel-checkbox-{$alpha->id}");$page->click("@analytics-channel-checkbox-{$alpha->id}");$page->script(<<<'JS'(async () => {@@ -97,7 +83,7 @@ test('the channel filter scopes the dashboard and keeps the channel in the url',}})();JS);- waitForInsightsChannelTestId($page, 'insights-card-followers');+ waitFor($page, '@insights-card-followers');$page->assertScript('[...new URLSearchParams(location.search)].filter(([key]) => key.startsWith("channels")).map(([, value]) => value)', [$alpha->id])->assertScript('document.querySelector("[data-testid=insights-card-followers]")?.innerText.includes("120")', true)@@ -118,30 +104,82 @@ test('the channel filter scopes the dashboard and keeps the channel in the url',->assertNoJavaScriptErrors();});-test('the follower bar tooltip shows a series swatch and the toolbar fits a 390px viewport', function () {+test('the follower bar tooltip shows the verified mark of an X channel', function () {+ [$user, $accounts] = insightsChannelFilterFixture();+ $accounts[0]->update(['platform' => Platform::X, 'meta' => ['x_verified_type' => 'blue']]);+ AnalyticsAccountDailySnapshot::query()->where('social_account_id', $accounts[0]->id)->update(['platform' => Platform::X, 'network' => Platform::X->network()]);+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@analytics-account-bar');+ $page->hover('[data-testid="analytics-account-bar"] >> nth=1');+ waitFor($page, '@analytics-chart-tooltip [data-verified="blue"]');++ $page->assertPresent('[data-testid="analytics-chart-tooltip"] [data-verified="blue"]')+ ->assertNoJavaScriptErrors();+});++test('the followers chart prints each channel’s number next to its bar or at the end of its line', function () {[$user] = insightsChannelFilterFixture();$this->actingAs($user);$page = visit(route('app.insights'));- waitForInsightsChannelTestId($page, 'analytics-account-bar');+ waitFor($page, '@analytics-account-value');++ $values = 'Array.from(document.querySelector("[data-testid=accounts-unovis-bar-chart]").querySelectorAll("[data-testid=analytics-account-value]"), (value) => value.innerText).sort().join(",")';+ $aligned = '(() => { const chart = document.querySelector("[data-testid=accounts-unovis-bar-chart]"); const edges = Array.from(chart.querySelectorAll("[data-testid=analytics-account-value]"), (value) => Math.round(value.getBoundingClientRect().right)); const barStart = Math.min(...Array.from(chart.querySelectorAll("[data-testid=analytics-account-bar]"), (bar) => bar.getBoundingClientRect().left)); return new Set(edges).size === 1 && edges[0] < barStart; })()';++ $page->assertScript($values, '120,30')+ ->assertScript('document.querySelector("[data-testid=analytics-axis-channel]").closest("[aria-hidden=true]") === null', true)+ ->assertSeeIn('@analytics-followers-change', '+20')+ ->assertScript($aligned, true);++ $page->click('@followers-growth');+ waitForText($page, '@analytics-account-value', '+10');++ $page->assertScript($values, '+10,+10');++ $page->click('@followers-line');+ waitForText($page, '@analytics-line-end-value', '120');++ $page->assertScript('Array.from(document.querySelectorAll("[data-testid=analytics-line-end-value]"), (value) => value.innerText).sort().join(",")', '120,30')+ ->assertScript('(() => { const chart = document.querySelector("[data-testid=followers-unovis-chart]").getBoundingClientRect(); return Array.from(document.querySelectorAll("[data-testid=followers-line-end]")).every((label) => label.getBoundingClientRect().left >= chart.left + chart.width / 2); })()', true);++ $page->hover('[data-testid="followers-line-end"] >> nth=0');+ waitForState($page, '@followers-unovis-chart', "element.querySelectorAll('[data-dimmed=true]').length > 0");++ $page->assertScript('document.querySelectorAll("[data-testid=followers-unovis-chart] [data-dimmed=true]").length > 0', true)+ ->assertNoJavaScriptErrors();+});++test('the follower bar tooltip lists where the channel started and the toolbar fits a 390px viewport', function () {+ [$user] = insightsChannelFilterFixture();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@analytics-account-bar');$page->assertScript('document.querySelector("[data-testid=followers-bar]")?.getAttribute("aria-pressed")', 'true')- ->assertScript('document.querySelectorAll("[data-testid=analytics-legend-swatch]").length >= 2', true)->hover('[data-testid="analytics-account-bar"] >> nth=0');- waitForInsightsChannelTestId($page, 'analytics-tooltip-swatch');+ waitFor($page, '@analytics-tooltip-detail');- $page->assertPresent('@analytics-tooltip-swatch')- ->assertScript('document.querySelector("[data-testid=analytics-tooltip-value]")?.innerText', '120')- ->assertScript('document.querySelector("[data-testid=analytics-tooltip-detail]")?.innerText.includes("110")', true)+ $page->assertScript('document.querySelector("[data-testid=analytics-tooltip-value]")?.innerText', '120')+ ->assertScript('document.querySelectorAll("[data-testid=analytics-tooltip-detail-label]").length', 2)+ ->assertScript('document.querySelector("[data-testid=analytics-tooltip-detail-value]")?.innerText', '110')->assertNoJavaScriptErrors();$page->resize(390, 844);- waitForInsightsChannelTestId($page, 'insights-range-custom');+ waitFor($page, '@insights-range-custom');$page->assertScript('(() => { const group = document.querySelector("[data-testid=insights-range-presets] [role=group]"); return group.scrollWidth <= group.clientWidth + 1; })()', true)->assertScript('document.querySelector("[data-testid=insights-range-custom]").getBoundingClientRect().right <= window.innerWidth', true)->assertScript('document.querySelector("[data-testid=analytics-channel-filter]").getBoundingClientRect().right <= window.innerWidth', true)->assertScript('document.documentElement.scrollWidth <= window.innerWidth + 2', true)+ ->assertScript('Array.from(document.querySelectorAll("[data-testid=analytics-account-name]")).every((name) => name.offsetParent === null)', true)+ ->assertScript('(() => { const grid = document.querySelector("[data-testid=analytics-summary]").getBoundingClientRect(); const last = document.querySelector("[data-testid=analytics-summary] > :last-child").getBoundingClientRect(); return Math.abs(last.width - grid.width) < 2; })()', true)+ ->assertScript('(() => { const value = document.querySelector("[data-testid=analytics-summary-engagement_rate-value]").getBoundingClientRect(); const change = document.querySelector("[data-testid=analytics-summary-engagement_rate-change]")?.getBoundingClientRect(); return !change || Math.abs((change.top + change.bottom) / 2 - (value.top + value.bottom) / 2) < 8; })()', true)+ ->assertScript('(() => { const card = document.querySelector("[data-testid=analytics-summary-posts]"); const change = card.querySelector("[data-testid=analytics-summary-posts-change]"); const value = card.querySelector("[data-testid=analytics-summary-posts-value]"); return !change || change.getBoundingClientRect().top >= value.getBoundingClientRect().bottom - 1; })()', true)+ ->assertScript('Array.from(document.querySelectorAll("[data-testid=accounts-unovis-bar-chart] [data-testid=analytics-account-value]")).every((value) => value.offsetParent !== null)', true)->assertNoJavaScriptErrors();});@@ -155,7 +193,7 @@ test('a channel without data shows the filtered empty state and history navigati$this->actingAs($user);$page = visit(route('app.insights'));- waitForInsightsChannelTestId($page, 'insights-range-7d');+ waitFor($page, '@insights-range-7d');$page->click('@insights-range-7d');$page->script(<<<'JS'(async () => {@@ -165,11 +203,11 @@ test('a channel without data shows the filtered empty state and history navigati}})();JS);- waitForInsightsChannelTestId($page, 'analytics-channel-filter');+ waitFor($page, '@analytics-channel-filter');$page->click('@analytics-channel-filter');- waitForInsightsChannelTestId($page, "analytics-channel-checkbox-{$silent->id}");+ waitFor($page, "@analytics-channel-checkbox-{$silent->id}");$page->click("@analytics-channel-checkbox-{$silent->id}");- waitForInsightsChannelTestId($page, 'analytics-filtered-empty-state');+ waitFor($page, '@analytics-filtered-empty-state');$page->assertPresent('@analytics-filtered-empty-state')->assertMissing('@analytics-empty-state')@@ -185,7 +223,7 @@ test('a channel without data shows the filtered empty state and history navigati}})();JS);- waitForInsightsChannelTestId($page, 'analytics-summary-followers');+ waitFor($page, '@analytics-summary-followers');$page->assertScript('location.pathname.endsWith("/insights") && !location.search.includes("channels")', true)->assertPresent('@analytics-summary-followers')@@ -193,3 +231,136 @@ test('a channel without data shows the filtered empty state and history navigati->assertMissing('@analytics-filtered-empty-state')->assertNoJavaScriptErrors();});++test('a channel that lost followers reads as a loss in the tooltip, the Growth view and the headline', function () {+ [$user, $accounts] = insightsChannelFilterFixture();+ AnalyticsAccountDailySnapshot::query()+ ->where('social_account_id', $accounts[1]->id)+ ->where('date', now('UTC')->subDays(2)->toDateString())+ ->update(['followers_count' => 5]);+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@analytics-account-bar');++ $page->assertSeeIn('@analytics-followers-change', '-5')+ ->hover('[data-testid="analytics-account-bar"] >> nth=1');+ waitForText($page, '@analytics-tooltip-detail', 'Lost in range');++ $page->assertSeeIn('@analytics-tooltip-detail', '-15 (-75%)')+ ->click('@followers-growth');+ waitForText($page, '@analytics-account-value', '-15');++ $page->assertScript('Array.from(document.querySelector("[data-testid=accounts-unovis-bar-chart]").querySelectorAll("[data-testid=analytics-account-value]"), (value) => value.innerText).sort().join(",")', '+10,-15')+ ->assertNoJavaScriptErrors();+});++test('the posts card heads with every channel’s posts and lists the channels only when stacked', function () {+ [$user] = insightsChannelFilterFixture();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@analytics-posts-total');++ $page->assertSeeIn('@analytics-posts-total', '2')+ ->assertMissing('@analytics-posts-legend')+ ->click('@posts-stacked');+ waitFor($page, '@analytics-posts-legend');++ $page->assertSeeIn('@analytics-posts-total', '2')+ ->click('@posts-bar');+ waitForGone($page, '@analytics-posts-legend');++ $page->assertNoJavaScriptErrors();+});++test('on a phone the channel, label and post type filters open as sheets', function () {+ [$user, $accounts] = insightsChannelFilterFixture();+ $this->actingAs($user);++ $page = visit(route('app.insights'))->resize(390, 844);+ waitFor($page, '@analytics-channel-filter');+ $page->click('@analytics-channel-filter');+ waitFor($page, '@analytics-channel-sheet');++ $page->assertVisible('@analytics-channel-sheet')+ ->assertNoJavaScriptErrors();++ $channel = visit(route('app.channels.insights', $accounts[0]))->resize(390, 844);+ waitFor($channel, '@insights-label-filter');+ $channel->click('@insights-label-filter');+ waitFor($channel, '@insights-label-sheet');++ $channel->assertVisible('@insights-label-sheet')+ ->assertNoJavaScriptErrors();++ $types = visit(route('app.channels.insights', $accounts[0]))->resize(390, 844);+ waitFor($types, '@insights-post-type-filter');+ $types->click('@insights-post-type-filter');+ waitFor($types, '@insights-post-type-sheet');++ $types->assertVisible('@insights-post-type-sheet')+ ->assertNoJavaScriptErrors();+});++test('the followers line axis never prints two ticks alike when the counts are close', function () {+ [$user, $accounts] = insightsChannelFilterFixture();+ AnalyticsAccountDailySnapshot::query()->where('social_account_id', $accounts[1]->id)->delete();+ $accounts[1]->delete();+ AnalyticsAccountDailySnapshot::query()->where('social_account_id', $accounts[0]->id)->orderBy('date')->get()+ ->each(fn (AnalyticsAccountDailySnapshot $snapshot, int $index) => $snapshot->update(['followers_count' => [9990, 10010][$index]]));+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@followers-line');+ $page->click('@followers-line');+ waitFor($page, '@followers-unovis-chart [data-value-tick]');++ $ticks = $page->script('Array.from(document.querySelectorAll(\'[data-testid="followers-unovis-chart"] [data-value-tick]\'), (tick) => tick.textContent.trim())');++ expect(count($ticks))->toBeGreaterThan(2)+ ->and(array_unique($ticks))->toHaveCount(count($ticks));+ $page->assertNoJavaScriptErrors();+});++test('a channel without a follower reading in the period gets no label at the end of the lines', function () {+ [$user, $accounts] = insightsChannelFilterFixture();+ AnalyticsAccountDailySnapshot::query()->where('social_account_id', $accounts[1]->id)->delete();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@followers-line');+ $page->click('@followers-line');+ waitFor($page, '@analytics-line-end-value');++ $page->assertScript('Array.from(document.querySelectorAll("[data-testid=analytics-line-end-value]"), (value) => value.innerText).join(",")', '120')+ ->assertNoJavaScriptErrors();+});++test('on a touch screen a tap on a line’s label, which never leaves it, fades no other line', function () {+ [$user] = insightsChannelFilterFixture();+ $this->actingAs($user);++ $page = visit(route('app.insights'))->on()->mobile();+ waitFor($page, '@followers-line');+ $page->click('@followers-line');+ waitFor($page, '@followers-line-end');+ $dimmed = $page->script(<<<'JS'+ (async () => {+ document.querySelector('[data-testid="followers-line-end"]').dispatchEvent(new MouseEvent('mouseenter'));+ const started = performance.now();+ let most = 0;++ while (performance.now() - started < 500) {+ await new Promise((resolve) => requestAnimationFrame(resolve));+ most = Math.max(most, document.querySelectorAll('[data-testid="followers-unovis-chart"] [data-dimmed="true"]').length);+ }++ return most;+ })()+ JS);++ expect($page->script('window.matchMedia("(hover: hover)").matches'))->toBeFalse()+ ->and($dimmed)->toBe(0);+ $page->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/InsightsParityTest.php b/tests/Browser/InsightsParityTest.phpindex a0ea9c722..6e2d00718 100644--- a/tests/Browser/InsightsParityTest.php+++ b/tests/Browser/InsightsParityTest.php@@ -68,6 +68,7 @@ function insightsParitySetup(): array'network' => $platform->network(),'platform_user_id' => $account->platform_user_id,'account_username' => $username,+ 'account_display_name' => ucfirst($username),'account_avatar_url' => $platform === Platform::Instagram ? INSIGHTS_PARITY_AVATAR : null,'date' => now('UTC')->subDays(2)->toDateString(),'followers_count' => $followers,@@ -85,6 +86,7 @@ function insightsParitySetup(): array'platform' => $platform,'network' => $platform->network(),'account_username' => $username,+ 'account_display_name' => ucfirst($username),'account_avatar_url' => $platform === Platform::Instagram ? INSIGHTS_PARITY_AVATAR : null,'excerpt' => "Insights parity post {$username}",'provider_published_at' => now('UTC')->subDays(3),@@ -219,7 +221,7 @@ test('the insights dashboard shows channel avatars, explains itself, sorts and cwaitForInsightsParityTestId($page, 'analytics-performance-sort-reactions');- $order = 'Array.from(document.querySelectorAll("tbody th[scope=row]")).map((cell) => (cell.innerText.match(/@\\w+/) || [""])[0]).join(",")';+ $order = 'Array.from(document.querySelectorAll("tbody th[scope=row]")).map((cell) => (cell.innerText.match(/Alpha|Bravo/) || [""])[0]).join(",")';$page->assertScript('document.querySelector("[data-testid=analytics-performance-columns]").closest("table") === null', true)->click('@analytics-performance-sort-reactions');@@ -230,13 +232,13 @@ test('the insights dashboard shows channel avatars, explains itself, sorts and cwaitForInsightsParityCondition($page, 'document.querySelector("[data-testid=analytics-performance-column-reactions]").getAttribute("aria-sort") === "ascending"');$ascending = $page->script($order);- expect($descending)->toContain('@alpha')+ expect($descending)->toContain('Alpha')->and($ascending)->toBe(implode(',', array_reverse(explode(',', $descending))));$page->click('@analytics-performance-sort-channel');waitForInsightsParityCondition($page, 'document.querySelector("[data-testid=analytics-performance-channel-header]").getAttribute("aria-sort") === "ascending"');- expect($page->script($order))->toBe('@alpha,@bravo');+ expect($page->script($order))->toBe('Alpha,Bravo');$page->assertNoJavaScriptErrors();waitForInsightsParityTestId($page, 'analytics-performance-columns');diff --git a/tests/Browser/InsightsShareChartTest.php b/tests/Browser/InsightsShareChartTest.phpnew file mode 100644index 000000000..552c70753--- /dev/null+++ b/tests/Browser/InsightsShareChartTest.php@@ -0,0 +1,609 @@+<?php++declare(strict_types=1);++use App\Enums\SocialAccount\Platform;+use App\Enums\User\Locale;+use App\Enums\User\Theme;+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\Media;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Facades\Storage;+use Symfony\Component\HttpFoundation\Response;++function insightsShareBrowserUser(): array+{+ $user = User::factory()->create();+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id, 'name' => 'Acme Studio']);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($user->account);++ $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);++ foreach ([5, 3] as $daysAgo) {+ AnalyticsAccountDailySnapshot::factory()->create([+ 'workspace_id' => $workspace->id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'platform_user_id' => $account->platform_user_id,+ 'date' => now('UTC')->subDays($daysAgo)->toDateString(),+ 'followers_count' => 120 + $daysAgo,+ ]);+ }++ return [$user->fresh(), $account];+}++/** The photo the test channels get: a picture the test server serves, unlike the faked storage disk. */+const INSIGHTS_SHARE_AVATAR = '/images/accounts/linkedin.png';++/** Gives the channel a photo the page can load, on the follower readings Insights reads it from. */+function insightsShareAvatar(SocialAccount $account): void+{+ AnalyticsAccountDailySnapshot::query()+ ->where('social_account_id', $account->id)+ ->update(['account_avatar_url' => INSIGHTS_SHARE_AVATAR]);+}++/** Opens the share dialog from `$button` and waits for its preview to be drawn. */+function openShareCard(mixed $page, string $button): void+{+ waitFor($page, $button);+ $page->click($button);+ waitForState($page, '@share-chart-preview', "element.dataset.state === 'ready'");+ $page->assertAttribute('@share-chart-preview', 'data-state', 'ready');+}++beforeEach(function () {+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);+ Storage::fake();+ Http::fake(['*' => Http::response('', Response::HTTP_NOT_FOUND)]);+});++test('the followers chart opens a share card in a TryPost tint that turns into a post with the image', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ openShareCard($page, '@share-followers');++ $page->click('@share-chart-color-green')+ ->assertAttribute('@share-chart-color-green', 'aria-checked', 'true');+ waitForCondition($page, <<<'JS'+ (() => {+ const canvas = document.querySelector('[data-testid="share-chart-preview"]');+ const [r, g, b] = canvas.getContext('2d').getImageData(2, Math.round(canvas.height / 2), 1, 1).data;++ return `${r},${g},${b}` === '217,241,209';+ })()+ JS);+ $page->click('@share-chart-post');++ waitFor($page, '@post-composer-dialog');+ waitForGone($page, '@share-chart-dialog');++ expect(Media::query()->where('original_filename', 'like', 'trypost-followers-%')->exists())->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('copying the share card writes a PNG to the clipboard', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@share-summary');+ $page->script(<<<'JS'+ window.__copied = [];+ Object.defineProperty(navigator, 'clipboard', {+ value: { write: async (items) => { window.__copied.push(...items.flatMap((item) => item.types)); } },+ });+ JS);+ openShareCard($page, '@share-summary');+ $page->click('@share-chart-copy');+ waitForText($page, '[data-sonner-toast]', trans('analytics.share.copied'));++ expect($page->script('window.__copied'))->toBe(['image/png']);+ $page->assertSeeIn('[data-sonner-toast]', trans('analytics.share.copied'))+ ->assertNoJavaScriptErrors();+});++test('the followers card copies with a channel photo drawn on it', function () {+ [$user, $account] = insightsShareBrowserUser();+ insightsShareAvatar($account);+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@share-followers');+ $page->script(<<<'JS'+ window.__copied = [];+ Object.defineProperty(navigator, 'clipboard', {+ value: { write: async (items) => { for (const item of items) { window.__copied.push((await item.getType('image/png')).size); } } },+ });+ JS);+ openShareCard($page, '@share-followers');+ $page->click('@share-chart-copy');+ waitForText($page, '[data-sonner-toast]', trans('analytics.share.copied'));++ expect($page->script('window.__copied.length'))->toBe(1);+ $page->assertSeeIn('[data-sonner-toast]', trans('analytics.share.copied'))+ ->assertNoJavaScriptErrors();+});++test('the share card loads each channel photo before the dialog opens and draws it fetched with CORS', function () {+ [$user, $account] = insightsShareBrowserUser();+ insightsShareAvatar($account);+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitForState($page, '@share-followers', "element.dataset.state === 'ready'");++ $page->assertAttribute('@share-followers', 'data-state', 'ready')+ ->assertMissing('@share-chart-dialog');++ recordCanvasDrawing($page);+ openShareCard($page, '@share-followers');++ expect($page->script('window.__images.some((source) => source.includes("/images/accounts/linkedin.png") && source.includes("cors=1"))'))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('the share card draws the change and verified icons from the Tabler components the page shows', function () {+ [$user, $account] = insightsShareBrowserUser();+ $account->update(['platform' => Platform::X, 'meta' => ['x_verified_type' => 'blue']]);+ AnalyticsAccountDailySnapshot::query()+ ->where('social_account_id', $account->id)+ ->update(['platform' => Platform::X, 'network' => Platform::X->network()]);+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@share-followers');+ recordCanvasDrawing($page);+ openShareCard($page, '@share-followers');++ expect($page->script('window.__paths.includes("M3 7l6 6l4 -4l8 8") && window.__paths.includes("M21 10l0 7l-7 0")'))->toBeTrue()+ ->and($page->script('window.__paths.some((path) => path.startsWith("M12.01 2.011a3.2 3.2 0 0 1 2.113 .797"))'))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('a browser that cannot copy images is told to download the card instead', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@share-summary');+ $page->script('delete window.ClipboardItem');+ openShareCard($page, '@share-summary');+ $page->click('@share-chart-copy');+ waitForText($page, '[data-sonner-toast]', trans('analytics.share.copy_failed'));++ $page->assertSeeIn('[data-sonner-toast]', trans('analytics.share.copy_failed'))+ ->assertNoJavaScriptErrors();+});++test('the summary shares as one card of its numbers', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ openShareCard($page, '@share-summary');++ $page->assertAttribute('@share-chart-preview', 'data-shape', 'tiles')+ ->assertVisible('@share-chart-download')+ ->assertVisible('@share-chart-copy')+ ->assertNoJavaScriptErrors();+});++test('the channel metrics card shares the chart as it is drawn', function () {+ [$user, $account] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.channels.insights', $account));+ openShareCard($page, '@share-channel-metrics');++ $page->assertAttribute('@share-chart-preview', 'data-shape', 'combo')+ ->assertVisible('@share-chart-post')+ ->assertNoJavaScriptErrors();+});++test('the followers share card follows the chart mode the user picked', function (string $mode, string $shape) {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, "@followers-{$mode}");+ $page->click("@followers-{$mode}");+ openShareCard($page, '@share-followers');++ $page->assertAttribute('@share-chart-preview', 'data-shape', $shape)+ ->assertNoJavaScriptErrors();+})->with([+ 'bar' => ['bar', 'rows'],+ 'line' => ['line', 'lines'],+ 'growth' => ['growth', 'rows'],+]);++test('the posts share card follows the chart mode the user picked', function (string $mode, string $shape) {+ [$user, $account] = insightsShareBrowserUser();+ insightsShareAvatar($account);++ foreach ([12, 9, 9, 4] as $daysAgo) {+ $publication = AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'provider_published_at' => now()->subDays($daysAgo)->setTime(10, 0),+ ]);+ AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $publication->id]);+ }++ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, "@posts-{$mode}");+ $page->click("@posts-{$mode}");+ openShareCard($page, '@share-posts');++ $page->assertAttribute('@share-chart-preview', 'data-shape', $shape)+ ->assertNoJavaScriptErrors();+})->with([+ 'bar' => ['bar', 'rows'],+ 'stacked' => ['stacked', 'stacked'],+]);++test('the followers chart offers no share card while it has no follower data', function () {+ $user = User::factory()->create();+ $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);+ $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);+ AnalyticsPublication::factory()->create([+ 'workspace_id' => $workspace->id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'provider_published_at' => now()->subDays(2)->setTime(10, 0),+ ]);+ $this->actingAs($user->fresh());++ $page = visit(route('app.insights'));+ waitFor($page, '@analytics-followers-empty');++ $page->assertMissing('@share-followers')+ ->assertNoJavaScriptErrors();+});++/** The text the composer opened with. */+function composerText(mixed $page): string+{+ waitFor($page, '@composer-base-content');++ return (string) $page->script('document.querySelector(\'[data-testid="composer-base-content"]\').value');+}++test('Create post opens the composer with the card’s number as the post text', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ openShareCard($page, '@share-followers');+ $page->click('@share-chart-post');++ expect(composerText($page))->toStartWith('Followers across our channels: 123 (');+ $page->assertNoJavaScriptErrors();+});++test('the channel chart’s post text leaves out a metric that has no value', function () {+ [$user, $account] = insightsShareBrowserUser();+ $quiet = SocialAccount::factory()->instagram()->create(['workspace_id' => $account->workspace_id, 'display_name' => 'Quiet Channel']);++ foreach ([4, 2] as $daysAgo) {+ AnalyticsPublication::factory()->create([+ 'workspace_id' => $quiet->workspace_id,+ 'social_account_id' => $quiet->id,+ 'social_account_key' => $quiet->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'provider_published_at' => now()->subDays($daysAgo)->setTime(10, 0),+ ]);+ }++ $this->actingAs($user);++ $page = visit(route('app.channels.insights', $quiet));+ openShareCard($page, '@share-channel-metrics');+ $page->click('@share-chart-post');+ $text = composerText($page);++ expect($text)->toContain('📈 Posts 2')+ ->not->toContain('Followers')+ ->not->toContain('—');+ $page->assertNoJavaScriptErrors();+});++test('downloading the share card saves a PNG named after the metric and today', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ openShareCard($page, '@share-followers');+ $page->script(<<<'JS'+ if (!window.__downloads) {+ window.__downloads = [];+ const createObjectURL = URL.createObjectURL.bind(URL);+ URL.createObjectURL = (file) => {+ window.__downloads.push(file.name);++ return createObjectURL(file);+ };+ }+ JS);+ $page->click('@share-chart-download');+ waitForCondition($page, 'window.__downloads.length > 0');++ expect($page->script('window.__downloads[0]'))->toMatch('/^trypost-followers-\d{4}-\d{2}-\d{2}\.png$/');+ $page->assertNoJavaScriptErrors();+});++test('closing the dialog while Create post uploads stops it, with no composer and no error', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ openShareCard($page, '@share-followers');+ $page->script(<<<'JS'+ window.__sent = 0;+ XMLHttpRequest.prototype.send = function () { window.__sent += 1; };+ XMLHttpRequest.prototype.abort = function () { window.__abortedAt = performance.now(); };+ JS);+ $page->click('@share-chart-post');+ waitForCondition($page, 'window.__sent > 0');+ $page->keys('@share-chart-dialog', 'Escape');+ waitForGone($page, '@share-chart-dialog');+ waitForCondition($page, 'window.__abortedAt !== undefined && performance.now() - window.__abortedAt > 500');++ expect($page->script('document.querySelectorAll("[data-sonner-toast]").length'))->toBe(0);+ $page->assertMissing('@post-composer-dialog')+ ->assertNoJavaScriptErrors();+});++test('a dark page still draws the share card in the light palette', function () {+ [$user] = insightsShareBrowserUser();+ $user->update(['theme' => Theme::Dark]);+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ openShareCard($page, '@share-followers');++ $palettes = $page->script(<<<'JS'+ (() => {+ const read = (light) => Array.from({ length: 10 }, (_, index) => {+ const probe = document.createElement('span');+ if (light) probe.dataset.lightTheme = '';+ probe.style.color = `var(--series-${index + 1})`;+ document.body.append(probe);+ const [r, g, b] = getComputedStyle(probe).color.match(/\d+/g).map(Number);+ probe.remove();+ return `${r},${g},${b}`;+ });+ const canvas = document.querySelector('[data-testid="share-chart-preview"]');+ const { data } = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);+ const painted = new Set();+ for (let index = 0; index < data.length; index += 4) {+ painted.add(`${data[index]},${data[index + 1]},${data[index + 2]}`);+ }+ return {+ dark: document.documentElement.classList.contains('dark'),+ light: read(true).filter((color) => painted.has(color)).length,+ darkOnly: read(false).filter((color, index) => color !== read(true)[index] && painted.has(color)).length,+ };+ })()+ JS);++ expect($palettes)->toBe(['dark' => true, 'light' => 1, 'darkOnly' => 0]);+ $page->assertNoJavaScriptErrors();+});++test('a channel with neither name nor handle is shared under its network’s name', function () {+ [$user, $account] = insightsShareBrowserUser();+ $account->update(['display_name' => null, 'username' => null]);+ $this->actingAs($user);++ $page = visit(route('app.channels.insights', $account));+ openShareCard($page, '@share-summary');+ $page->click('@share-chart-post');++ expect(composerText($page))->toStartWith('Our numbers on Instagram for ');+ $page->assertNoJavaScriptErrors();+});++/** Adds channels with one follower reading each, named by `$name`, so the per channel card fills up. */+function insightsShareChannels(SocialAccount $account, int $count, Closure $name): void+{+ foreach (range(1, $count) as $index) {+ $channel = SocialAccount::factory()->instagram()->create([+ 'workspace_id' => $account->workspace_id,+ 'display_name' => $name($index),+ ]);+ AnalyticsAccountDailySnapshot::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $channel->id,+ 'social_account_key' => $channel->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'platform_user_id' => $channel->platform_user_id,+ 'date' => now('UTC')->subDays(3)->toDateString(),+ 'followers_count' => 1000 + $index,+ 'account_display_name' => $name($index),+ ]);+ }+}++test('a long channel name is cut between whole characters, never inside an emoji', function () {+ [$user, $account] = insightsShareBrowserUser();+ $name = str_repeat('Team 🚀 ', 20);+ insightsShareChannels($account, 11, fn (int $index): string => $index === 1 ? $name : sprintf('Channel %02d', $index));+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@share-followers');+ recordCanvasDrawing($page);+ openShareCard($page, '@share-followers');++ $cut = $page->script(<<<JS+ (() => {+ const full = '{$name}';+ const label = window.__drawn.map((entry) => entry.text).find((text) => text.endsWith('…') && full.startsWith(text.slice(0, -1)));+ const kept = label.slice(0, -1);+ const boundaries = new Set(Array.from(new Intl.Segmenter().segment(full), (piece) => piece.index));++ return { cut: kept.length < full.length, wholeCharacters: boundaries.has(kept.length), wellFormed: label.isWellFormed() };+ })()+ JS);++ expect($cut)->toBe(['cut' => true, 'wholeCharacters' => true, 'wellFormed' => true]);+ $page->assertNoJavaScriptErrors();+});++test('in a right-to-left language every text of the card runs right to left, preview and file alike', function () {+ [$user] = insightsShareBrowserUser();+ $user->update(['locale' => Locale::Arabic]);+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@share-followers');+ recordCanvasDrawing($page);+ openShareCard($page, '@share-followers');+ $preview = $page->script('window.__drawn.length');+ $page->click('@share-chart-download');+ waitForCondition($page, "window.__drawn.length > {$preview}");++ expect($page->script('document.documentElement.dir'))->toBe('rtl')+ ->and($page->script('[...new Set(window.__drawn.map((entry) => entry.direction))]'))->toBe(['rtl'])+ ->and($page->script('window.__drawn.every((entry) => ["left", "right", "center"].includes(entry.align))'))->toBeTrue();+ $page->assertNoJavaScriptErrors();+});++test('the per channel card draws the twelve channels with the most followers', function () {+ [$user, $account] = insightsShareBrowserUser();++ insightsShareChannels($account, 12, fn (int $index): string => sprintf('Channel %02d', $index));++ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@share-followers');+ recordCanvasDrawing($page);+ openShareCard($page, '@share-followers');++ $names = $page->script('[...new Set(window.__drawn.map((entry) => entry.text).filter((text) => /^Channel \\d{2}$/.test(text)))].sort()');++ expect($names)->toHaveCount(12)+ ->and($page->script('window.__drawn.some((entry) => entry.text === "123")'))->toBeFalse();+ $page->assertNoJavaScriptErrors();+});++test('the stacked posts card keeps its week labels apart over a long range', function () {+ [$user, $account] = insightsShareBrowserUser();++ foreach ([89, 60, 30, 1] as $daysAgo) {+ AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'provider_published_at' => now()->subDays($daysAgo)->setTime(10, 0),+ ]);+ }++ $this->actingAs($user);++ $page = visit(route('app.insights', ['start' => now()->subDays(89)->toDateString(), 'end' => now()->subDay()->toDateString()]));+ waitFor($page, '@posts-stacked');+ $page->click('@posts-stacked');+ recordCanvasDrawing($page);+ openShareCard($page, '@share-posts');++ $dates = $page->script(<<<'JS'+ (() => {+ const centred = window.__drawn.filter((entry) => entry.align === 'center' && entry.text.includes('–'));+ const unique = [...new Map(centred.map((entry) => [`${entry.text}|${entry.x}`, entry])).values()].sort((a, b) => a.x - b.x);+ const overlaps = unique.slice(1).filter((entry, index) => entry.x - entry.width / 2 < unique[index].x + unique[index].width / 2).length;++ return { shown: unique.length, overlaps };+ })()+ JS);++ expect($dates['shown'])->toBeGreaterThan(1)+ ->and($dates['overlaps'])->toBe(0);+ $page->assertNoJavaScriptErrors();+});++test('a share of some of the channels says how many of them it counts', function () {+ [$user, $account] = insightsShareBrowserUser();+ insightsShareChannels($account, 1, fn (): string => 'Other Channel');+ $this->actingAs($user);++ $page = visit(route('app.insights', ['channels' => [$account->id]]));+ openShareCard($page, '@share-followers');+ $page->click('@share-chart-post');++ expect(composerText($page))->toEndWith('· 1 of 2 channels) 📈');+ $page->assertNoJavaScriptErrors();+});++test('a browser that cannot draw the card stops loading the preview and is told so', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ waitFor($page, '@share-followers');+ $page->script('(() => { CanvasRenderingContext2D.prototype.roundRect = undefined; })()');+ $page->click('@share-followers');+ waitForText($page, '[data-sonner-toast]', 'Couldn');++ $page->assertAttribute('@share-chart-preview', 'data-state', 'ready');+ expect($page->script('document.querySelectorAll("[data-sonner-toast]").length'))->toBe(1);+});++test('a Create post stopped by closing the dialog never unblocks the next one', function () {+ [$user] = insightsShareBrowserUser();+ $this->actingAs($user);++ $page = visit(route('app.insights'));+ openShareCard($page, '@share-followers');+ $page->script(<<<'JS'+ (() => {+ window.__encoded = 0;+ const toBlob = HTMLCanvasElement.prototype.toBlob;+ HTMLCanvasElement.prototype.toBlob = function (callback, ...rest) {+ toBlob.call(this, (blob) => window.setTimeout(() => { window.__encoded += 1; callback(blob); }, 800), ...rest);+ };+ XMLHttpRequest.prototype.send = function () {};+ })()+ JS);+ $page->click('@share-chart-post');+ $page->keys('@share-chart-dialog', 'Escape');+ waitForGone($page, '@share-chart-dialog');+ openShareCard($page, '@share-followers');+ $page->click('@share-chart-post');+ waitForCondition($page, 'window.__encoded >= 1');++ $page->assertAttribute('@share-chart-post', 'disabled', '')+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/McpSettingsTest.php b/tests/Browser/McpSettingsTest.phpindex d9846938e..46fcbdd79 100644--- a/tests/Browser/McpSettingsTest.php+++ b/tests/Browser/McpSettingsTest.php@@ -86,6 +86,31 @@ test('disconnecting an MCP app asks for the translated disconnect keyword, not texpect(AccessToken::query()->where('client_id', $clientId)->where('revoked', false)->exists())->toBeFalse();});+test('a connected app shows its brand logo, and one without a logo shows the MCP mark', function () {+ $user = User::factory()->create();+ $workspace = Workspace::factory()->create([+ 'account_id' => $user->account_id,+ 'user_id' => $user->id,+ ]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($user->account);++ $cursor = mcpOauthClient('Cursor');+ $unknown = mcpOauthClient('Muse Code');+ mcpAccessToken($user, $cursor, $workspace);+ mcpAccessToken($user, $unknown, $workspace);++ $this->actingAs($user->fresh());++ $page = visit(route('app.mcp.index'));+ waitFor($page, "@mcp-connected-client-{$unknown}");++ $page->assertVisible("[data-testid=\"mcp-connected-client-{$cursor}\"] [data-testid=\"mcp-connected-logo-cursor\"]")+ ->assertPresent("[data-testid=\"mcp-connected-client-{$unknown}\"] svg.tabler-icon-mcp")+ ->assertNoJavaScriptErrors();+});+test('the MCP settings open on the connected tab, whose empty state leads to the connect tab', function () {$user = User::factory()->create();$workspace = Workspace::factory()->create([diff --git a/tests/Browser/ProfileTabsTest.php b/tests/Browser/ProfileTabsTest.phpindex 4db929280..9fafcc3dd 100644--- a/tests/Browser/ProfileTabsTest.php+++ b/tests/Browser/ProfileTabsTest.php@@ -120,14 +120,23 @@ test('the apple logo of a mac session turns light on the dark theme', function ($page->assertNoJavaScriptErrors();});-test('the github mark turns light on the dark theme while google keeps its colors', function () {+test('the github mark is drawn in the text color on the dark theme while google keeps its colors', function () {$this->actingAs(User::factory()->create(['theme' => Theme::Dark]));$page = visit(route('app.profile.edit', ['tab' => 'login']));waitForProfileTabsTestId($page, 'connected-account-icon-github');- expect($page->script('getComputedStyle(document.querySelector(\'[data-testid="connected-account-icon-github"]\')).filter'))->toBe('invert(1)')- ->and($page->script('getComputedStyle(document.querySelector(\'[data-testid="connected-account-icon-google"]\')).filter'))->toBe('none');+ $github = $page->script(<<<'JS'+ (() => {+ const mark = document.querySelector('[data-testid="connected-account-icon-github"]');++ return { fill: getComputedStyle(mark.querySelector('path')).fill, text: getComputedStyle(mark).color, page: getComputedStyle(document.body).backgroundColor };+ })()+ JS);++ expect($github['fill'])->toBe($github['text'])+ ->and($github['fill'])->not->toBe($github['page'])+ ->and($page->script('[...document.querySelectorAll(\'[data-testid="connected-account-icon-google"] path\')].some((path) => getComputedStyle(path).fill.startsWith("url("))'))->toBeTrue();$page->assertNoJavaScriptErrors();});diff --git a/tests/Browser/PublishPageTest.php b/tests/Browser/PublishPageTest.phpindex c743aae80..1094bd20a 100644--- a/tests/Browser/PublishPageTest.php+++ b/tests/Browser/PublishPageTest.php@@ -18,37 +18,6 @@ use App\Models\Workspace;use App\Models\WorkspaceLabel;use App\Support\PostingSchedule;-function waitForPublishPageTestId(mixed $page, string $testId): void-{- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if (document.querySelector('[data-testid="{$testId}"]')?.getBoundingClientRect().height > 0) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}--function waitForPublishPageScript(mixed $page, string $condition): void-{- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if ({$condition}) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}--function waitForPublishPagePostStatus(mixed $page, Post $post, PostStatus $status): void-{- for ($attempt = 0; $attempt < 50 && $post->refresh()->status !== $status; $attempt++) {- $page->script('new Promise((resolve) => setTimeout(resolve, 100))');- }-}-/*** @return array{0: User, 1: Workspace, 2: SocialAccount}*/@@ -107,7 +76,7 @@ test('the weekly goal shows its progress, fills the pie and opens a popover with$this->actingAs($user);$page = visit(route('app.channels.publish', $channel));- waitForPublishPageTestId($page, 'publish-goal-progress');+ waitFor($page, '@publish-goal-progress');expect($page->script('new URL(document.querySelector(\'[data-testid="schedule-view-calendar"]\').href).search'))->toBe('')->and($page->script('new URL(document.querySelector(\'[data-testid="schedule-view-calendar"]\').href).pathname'))->toBe(route('app.channels.calendar', ['account' => $channel->id, 'view' => 'week'], false));@@ -116,7 +85,7 @@ test('the weekly goal shows its progress, fills the pie and opens a popover withexpect($page->script("document.querySelectorAll('[data-testid=\"publish-goal-pie\"] circle').length"))->toBe(2);$page->click('@publish-goal-progress');- waitForPublishPageTestId($page, 'publish-goal-popover');+ waitFor($page, '@publish-goal-popover');$page->assertSeeIn('@publish-goal-popover', trans_choice('posts.publish.goal_popover.per_week', 3, ['count' => 3]))->assertVisible('@publish-goal-edit')@@ -132,13 +101,13 @@ test('a draft is added to the queue from the drafts tab, which stays open', func$this->actingAs($user);$page = visit(route('app.channels.publish', $channel));- waitForPublishPageTestId($page, 'publish-tab-drafts');+ waitFor($page, '@publish-tab-drafts');$page->click('@publish-tab-drafts');- waitForPublishPageTestId($page, "post-add-to-queue-{$draft->id}");+ waitFor($page, "@post-add-to-queue-{$draft->id}");$page->assertVisible("@post-card-{$draft->id}")->click("@post-add-to-queue-{$draft->id}");- waitForPublishPagePostStatus($page, $draft, PostStatus::Scheduled);+ waitForDatabase($page, fn (): bool => $draft->refresh()->status === PostStatus::Scheduled);expect($draft->refresh()->status)->toBe(PostStatus::Scheduled)->and($draft->schedule_mode)->toBe(ScheduleMode::Queue);@@ -160,11 +129,11 @@ test('add to queue explains how to set up the queue when the channel has no post$this->actingAs($user);$page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'drafts']));- waitForPublishPageTestId($page, "post-add-to-queue-{$draft->id}");+ waitFor($page, "@post-add-to-queue-{$draft->id}");$page->assertEnabled("@post-add-to-queue-{$draft->id}")->click("@post-add-to-queue-{$draft->id}");- waitForPublishPageTestId($page, "post-queue-setup-{$draft->id}");+ waitFor($page, "@post-queue-setup-{$draft->id}");$page->assertVisible("@post-queue-setup-illustration-{$draft->id}")->assertSeeIn("@post-queue-setup-{$draft->id}", __('posts.publish.actions.queue_setup.title'))@@ -173,7 +142,7 @@ test('add to queue explains how to set up the queue when the channel has no postexpect($draft->refresh()->status)->toBe(PostStatus::Draft);$page->click("@post-queue-setup-action-{$draft->id}");- waitForPublishPageTestId($page, 'channel-settings-page');+ waitFor($page, '@channel-settings-page');$page->assertPathIs(route('app.channels.settings', $channel, absolute: false))->assertNoJavaScriptErrors();@@ -192,9 +161,9 @@ test('a member who cannot manage channels is told to ask an admin for posting ti$this->actingAs($member);$page = visit(route('app.posts.index', ['tab' => 'drafts']));- waitForPublishPageTestId($page, "post-add-to-queue-{$draft->id}");+ waitFor($page, "@post-add-to-queue-{$draft->id}");$page->click("@post-add-to-queue-{$draft->id}");- waitForPublishPageTestId($page, "post-queue-setup-{$draft->id}");+ waitFor($page, "@post-queue-setup-{$draft->id}");$page->assertSeeIn("@post-queue-setup-{$draft->id}", __('posts.publish.actions.queue_setup.body_member'))->assertMissing("@post-queue-setup-action-{$draft->id}")@@ -210,9 +179,9 @@ test('add to queue explains where the post goes when the channel has posting tim$this->actingAs($user);$page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'drafts']));- waitForPublishPageTestId($page, "post-add-to-queue-{$draft->id}");+ waitFor($page, "@post-add-to-queue-{$draft->id}");$page->hover("@post-add-to-queue-{$draft->id}");- waitForPublishPageTestId($page, "post-add-to-queue-tooltip-{$draft->id}");+ waitFor($page, "@post-add-to-queue-tooltip-{$draft->id}");$page->assertSeeIn("@post-add-to-queue-tooltip-{$draft->id}", __('posts.publish.actions.add_to_queue_hint'))->assertNoJavaScriptErrors();@@ -224,9 +193,9 @@ test('editing a draft from a channel page keeps the channel page and tab', funct$this->actingAs($user);$page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'drafts']));- waitForPublishPageTestId($page, "post-edit-{$draft->id}");+ waitFor($page, "@post-edit-{$draft->id}");$page->click("@post-edit-{$draft->id}");- waitForPublishPageTestId($page, 'post-composer-dialog');+ waitFor($page, '@post-composer-dialog');expect($page->script('location.pathname'))->toBe(route('app.channels.publish', $channel, absolute: false))->and($page->script('new URLSearchParams(location.search).get("tab")'))->toBe('drafts')@@ -240,9 +209,9 @@ test('saving a queued post edited on a channel page returns to that page and tab$this->actingAs($user);$page = visit(route('app.channels.publish', ['account' => $channel, 'tab' => 'queue']));- waitForPublishPageTestId($page, "post-edit-{$queued->id}");+ waitFor($page, "@post-edit-{$queued->id}");$page->click("@post-edit-{$queued->id}");- waitForPublishPageTestId($page, 'composer-submit');+ waitFor($page, '@composer-submit');$page->click('@composer-submit');$page->script(<<<'JS'@@ -253,7 +222,7 @@ test('saving a queued post edited on a channel page returns to that page and tab}})();JS);- waitForPublishPageTestId($page, "post-card-{$queued->id}");+ waitFor($page, "@post-card-{$queued->id}");expect($page->script('location.pathname'))->toBe(route('app.channels.publish', $channel, absolute: false))->and($page->script('new URLSearchParams(location.search).get("tab")'))->toBe('queue')@@ -293,7 +262,7 @@ test('a sent card shows the metrics band in order and links to the publication i$this->actingAs($user);$page = visit(route('app.posts.index', ['tab' => 'sent']));- waitForPublishPageTestId($page, "post-metrics-{$post->id}");+ waitFor($page, "@post-metrics-{$post->id}");expect($page->script("[...document.querySelectorAll('[data-testid=\"post-metrics-{$post->id}\"] dd')].map((value) => value.textContent.trim())"))->toBe(['40', '7', '5.5%', '900', '3'])@@ -318,7 +287,7 @@ test('the approvals tab groups pending posts by day with unscheduled requests la$this->actingAs($user);$page = visit(route('app.posts.index', ['tab' => 'approvals']));- waitForPublishPageTestId($page, "post-card-{$queued->id}");+ waitFor($page, "@post-card-{$queued->id}");$timedDay = $timed->scheduled_at->utc()->format('Y-m-d');@@ -338,14 +307,14 @@ test('an empty tab shows its illustration, copy and a new post button that opens$this->actingAs($user);$page = visit(route('app.posts.index', ['tab' => $tab]));- waitForPublishPageTestId($page, 'publish-empty-illustration');+ waitFor($page, '@publish-empty-illustration');$page->assertSeeIn('@empty-state', __("posts.publish.empty.{$tab}.title"))->assertSeeIn('@empty-state', __("posts.publish.empty.{$tab}.description"))->assertSeeIn('@publish-empty-connect-more', __('posts.publish.welcome.connect_more'))->assertMissing('@publish-welcome')->click("@publish-empty-new-post-{$tab}");- waitForPublishPageTestId($page, 'post-composer-dialog');+ waitFor($page, '@post-composer-dialog');$page->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();})->with(['drafts']);@@ -362,20 +331,20 @@ test('a workspace without channels is welcomed with connect and invite actions',$this->actingAs($user);$page = visit(route('app.posts.index', ['tab' => 'drafts']));- waitForPublishPageTestId($page, 'publish-welcome');+ waitFor($page, '@publish-welcome');$page->assertSeeIn('@publish-welcome', __('posts.publish.welcome.title'))->assertSeeIn('@publish-welcome-invite', __('posts.publish.welcome.invite'))->assertMissing('@publish-empty-new-post-drafts')->click('@publish-welcome-invite');- waitForPublishPageTestId($page, 'invite-member-dialog');+ waitFor($page, '@invite-member-dialog');$page->assertVisible('@invite-email')->click('@invite-member-cancel');- waitForPublishPageTestId($page, 'publish-welcome-connect');+ waitFor($page, '@publish-welcome-connect');$page->click('@publish-welcome-connect');- waitForPublishPageTestId($page, 'connect-channel-dialog');+ waitFor($page, '@connect-channel-dialog');$page->assertVisible('@connect-channel-dialog')->assertNoJavaScriptErrors();});@@ -386,7 +355,7 @@ test('an active label filter shows its count in the primary color', function ()$this->actingAs($user);$page = visit(route('app.posts.index', ['tab' => 'drafts', 'labels' => [$label->id]]));- waitForPublishPageTestId($page, 'posts-label-count');+ waitFor($page, '@posts-label-count');$page->assertSeeIn('@posts-label-count', '1')->assertScript(<<<'JS'@@ -407,7 +376,7 @@ test('the tabs row border keeps the page padding instead of touching the panel e$this->actingAs($user);$page = visit(route('app.posts.index'))->resize(1440, 900);- waitForPublishPageTestId($page, 'publish-filters');+ waitFor($page, '@publish-filters');$edges = $page->script(<<<'JS'(() => {@@ -427,23 +396,21 @@ test('the calendar keeps its filters in one menu until the screen is wide enough$this->actingAs($user);$page = visit(route('app.calendar', ['view' => 'week']))->resize(390, 844);- waitForPublishPageTestId($page, 'calendar-menu');- waitForPublishPageTestId($page, 'posts-channel-filter');+ waitFor($page, '@calendar-menu');+ waitFor($page, '@posts-channel-filter');$measure = <<<'JS'(() => {const rect = (id) => document.querySelector(`[data-testid="${id}"]`).getBoundingClientRect();const middle = (box) => Math.round(box.top + box.height / 2);- const row = ['posts-channel-filter', 'calendar-menu', 'schedule-view-list', 'calendar-no-date'].map(rect);- const noDate = rect('calendar-no-date');+ const row = ['posts-channel-filter', 'calendar-menu'].map(rect);const channelFilter = document.querySelector('[data-testid="posts-channel-filter"]');const visible = (node) => node.getClientRects().length > 0 && getComputedStyle(node).display !== 'none';return {oneRow: row.every((box) => Math.abs(middle(box) - middle(row[0])) <= 2),- noDateLast: row.every((box) => box.right <= noDate.right),- noDateSquare: Math.round(noDate.width) === Math.round(noDate.height),- noDateLabelHidden: document.querySelector('[data-testid="calendar-no-date"] span').getBoundingClientRect().width <= 1,+ viewSwitchInHeader: Boolean(document.querySelector('[data-testid="app-header"] [data-testid="schedule-view-list"]')?.getClientRects().length),+ noDateButton: visible(document.querySelector('[data-testid="calendar-no-date"]')),channelText: [...channelFilter.querySelectorAll('span')].filter((span) => visible(span) && span.textContent.trim() !== '').length,tags: Boolean(document.querySelector('[data-testid="posts-label-filter"]')?.getClientRects().length),overflow: document.documentElement.scrollWidth > window.innerWidth,@@ -453,26 +420,37 @@ test('the calendar keeps its filters in one menu until the screen is wide enoughexpect($page->script($measure))->toBe(['oneRow' => true,- 'noDateLast' => true,- 'noDateSquare' => true,- 'noDateLabelHidden' => true,+ 'viewSwitchInHeader' => true,+ 'noDateButton' => false,'channelText' => 0,'tags' => false,'overflow' => false,]);$page->click('@calendar-menu');- waitForPublishPageTestId($page, 'calendar-menu-content');- waitForPublishPageScript($page, 'Math.abs(window.innerHeight - document.querySelector(\'[data-testid="calendar-menu-content"]\').getBoundingClientRect().bottom) <= 1');+ waitFor($page, '@calendar-menu-content');+ waitForCondition($page, 'Math.abs(window.innerHeight - document.querySelector(\'[data-testid="calendar-menu-content"]\').getBoundingClientRect().bottom) <= 1');$page->assertVisible('@calendar-status-drafts')->assertVisible('@publish-timezone-trigger')- ->assertVisible('@calendar-toggle-slots');+ ->assertVisible('@calendar-toggle-slots')+ ->assertAttribute('@calendar-no-date-menu', 'aria-pressed', 'false')+ ->click('@calendar-no-date-menu');++ waitFor($page, '@calendar-undated-panel');+ waitForGone($page, '@calendar-menu-content');+ $page->assertVisible('@calendar-undated-panel')+ ->assertMissing('@calendar-menu-content')+ ->click('@calendar-menu');+ waitFor($page, '@calendar-no-date-menu');+ $page->assertAttribute('@calendar-no-date-menu', 'aria-pressed', 'true')+ ->click('@calendar-no-date-menu');+ waitForGone($page, '@calendar-undated-panel');+ $page->assertMissing('@calendar-undated-panel');- $page->keys('@calendar-menu-content', 'Escape');$page->resize(900, 900);- waitForPublishPageScript($page, 'Boolean(document.querySelector(\'[data-testid="posts-label-filter"]\')?.getClientRects().length)');- waitForPublishPageScript($page, '!document.querySelector(\'[data-testid="calendar-status-filter"]\')');+ waitForCondition($page, 'Boolean(document.querySelector(\'[data-testid="posts-label-filter"]\')?.getClientRects().length)');+ waitForCondition($page, '!document.querySelector(\'[data-testid="calendar-status-filter"]\')');expect($page->script('Boolean(document.querySelector(\'[data-testid="calendar-status-filter"]\'))'))->toBeFalse()->and($page->script('Boolean(document.querySelector(\'[data-testid="calendar-menu"]\')?.getClientRects().length)'))->toBeTrue()@@ -480,7 +458,7 @@ test('the calendar keeps its filters in one menu until the screen is wide enough$page->resize(1600, 900);- waitForPublishPageScript($page, 'Boolean(document.querySelector(\'[data-testid="calendar-status-filter"]\'))');+ waitForCondition($page, 'Boolean(document.querySelector(\'[data-testid="calendar-status-filter"]\'))');$order = $page->script(<<<'JS'(() => ['posts-channel-filter', 'posts-label-filter', 'calendar-status-filter', 'publish-timezone-trigger', 'calendar-no-date', 'calendar-menu']@@ -517,16 +495,16 @@ test('the channel page adapts its filters, tabs, calendar link and notes button$calendarPath = 'new URL(document.querySelector(\'[data-testid="schedule-view-calendar"]\').href).pathname';$page = visit(route('app.channels.publish', $channel))->resize(900, 800);- waitForPublishPageTestId($page, "post-notes-trigger-{$post->id}");+ waitFor($page, "@post-notes-trigger-{$post->id}");expect($page->script($notes))->toBe(['inside' => true, 'beside' => false]);$page->resize(1280, 800);- waitForPublishPageTestId($page, "post-notes-trigger-{$post->id}");+ waitFor($page, "@post-notes-trigger-{$post->id}");expect($page->script($notes))->toBe(['inside' => true, 'beside' => false]);$page->resize(390, 844);- waitForPublishPageTestId($page, 'publish-tabs-mobile-trigger');- waitForPublishPageScript($page, '!document.querySelector(\'[data-testid="posts-label-filter"]\')');+ waitFor($page, '@publish-tabs-mobile-trigger');+ waitForCondition($page, '!document.querySelector(\'[data-testid="posts-label-filter"]\')');$phone = $page->script(<<<'JS'(() => {@@ -548,8 +526,8 @@ test('the channel page adapts its filters, tabs, calendar link and notes button->and($page->script('Boolean(document.querySelector(\'[data-testid="publish-timezone-trigger"]\'))'))->toBeFalse();$page->click('@publish-menu');- waitForPublishPageTestId($page, 'publish-menu-content');- waitForPublishPageScript($page, 'Math.abs(window.innerHeight - document.querySelector(\'[data-testid="publish-menu-content"]\').getBoundingClientRect().bottom) <= 1');+ waitFor($page, '@publish-menu-content');+ waitForCondition($page, 'Math.abs(window.innerHeight - document.querySelector(\'[data-testid="publish-menu-content"]\').getBoundingClientRect().bottom) <= 1');$pressed = 'document.querySelector(\'[data-testid="publish-toggle-slots"]\').getAttribute("aria-pressed")';$before = $page->script($pressed);@@ -561,8 +539,8 @@ test('the channel page adapts its filters, tabs, calendar link and notes button->toBe(route('app.channels.settings', $channel, false));$page->resize(1280, 800);- waitForPublishPageScript($page, '!document.querySelector(\'[data-testid="publish-menu-content"]\')');- waitForPublishPageTestId($page, 'publish-timezone-trigger');+ waitForCondition($page, '!document.querySelector(\'[data-testid="publish-menu-content"]\')');+ waitFor($page, '@publish-timezone-trigger');$desktop = $page->script(<<<'JS'(() => {@@ -580,31 +558,31 @@ test('the channel page adapts its filters, tabs, calendar link and notes buttonexpect($desktop)->toBe(['switchInHeader' => true, 'newPostInHeader' => true, 'order' => true]);$page->click('@publish-menu');- waitForPublishPageTestId($page, 'publish-toggle-slots');+ waitFor($page, '@publish-toggle-slots');$page->assertVisible('@publish-manage-slots');$page->resize(390, 844);- waitForPublishPageTestId($page, 'publish-tabs-mobile-trigger');+ waitFor($page, '@publish-tabs-mobile-trigger');expect($page->script('document.querySelector(\'[data-testid="posts-tabs"]\').getBoundingClientRect().height'))->toBe(0);$page->assertSeeIn('@publish-tabs-mobile-trigger', trans('posts.publish.tabs.queue'))->click('@publish-tabs-mobile-trigger');- waitForPublishPageTestId($page, 'publish-tabs-sheet');+ waitFor($page, '@publish-tabs-sheet');$page->assertPresent('@publish-tab-sheet-queue-check')->assertMissing('@publish-tab-sheet-drafts-check')->click('@publish-tab-sheet-drafts');- waitForPublishPageScript($page, 'new URLSearchParams(location.search).get("tab") === "drafts"');+ waitForCondition($page, 'new URLSearchParams(location.search).get("tab") === "drafts"');$page->assertSeeIn('@publish-tabs-mobile-trigger', trans('posts.publish.tabs.drafts'))->assertMissing('@publish-tabs-sheet');$page->navigate(route('app.posts.index'));- waitForPublishPageTestId($page, 'schedule-view-calendar');+ waitFor($page, '@schedule-view-calendar');expect($page->script($calendarPath))->toBe(route('app.calendar', ['view' => 'days'], false));$page->resize(1280, 800);- waitForPublishPageScript($page, $calendarPath.'.endsWith("/week")');+ waitForCondition($page, $calendarPath.'.endsWith("/week")');expect($page->script($calendarPath))->toBe(route('app.calendar', ['view' => 'week'], false));$page->assertNoJavaScriptErrors();@@ -622,7 +600,7 @@ test('a draft without a channel shows no add to queue button', function () {$this->actingAs($user);$page = visit(route('app.posts.index', ['tab' => 'drafts']));- waitForPublishPageTestId($page, "post-card-{$draft->id}");+ waitFor($page, "@post-card-{$draft->id}");$page->assertVisible("@post-card-{$draft->id}")->assertMissing("@post-add-to-queue-{$draft->id}")@@ -637,7 +615,7 @@ test('on a phone the view switch and the new post button fit inside the card, on$url = $allChannels ? route('app.posts.index', ['tab' => $tab]) : route('app.channels.publish', ['account' => $channel, 'tab' => $tab]);$page = visit($url)->resize(390, 844);- waitForPublishPageTestId($page, 'posts-new-post');+ waitFor($page, '@posts-new-post');$fits = $page->script(<<<'JS'(() => {@@ -664,8 +642,22 @@ test('the reel and story badges on a post card show a 16px icon', function (Cont$this->actingAs($user);$page = visit(route('app.posts.index', ['tab' => 'drafts']));- waitForPublishPageTestId($page, "post-content-type-icon-{$post->id}");+ waitFor($page, "@post-content-type-icon-{$post->id}");expect($page->script("(() => { const box = document.querySelector('[data-testid=\"post-content-type-icon-{$post->id}\"]').getBoundingClientRect(); return [Math.round(box.width), Math.round(box.height)]; })()"))->toBe([16, 16]);$page->assertNoJavaScriptErrors();})->with([ContentType::InstagramReel, ContentType::InstagramStory]);++test('on a phone the channel filter opens as a sheet on the publish page and the calendar', function (string $route) {+ [$user, $workspace] = publishPageSetup();+ SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']);+ $this->actingAs($user);++ $page = visit(route($route))->resize(390, 844);+ waitFor($page, '@posts-channel-filter');+ $page->click('@posts-channel-filter');+ waitFor($page, '@posts-channel-sheet');++ $page->assertVisible('@posts-channel-sheet')+ ->assertNoJavaScriptErrors();+})->with(['app.posts.index', 'app.calendar']);diff --git a/tests/Browser/SettingsSidebarTest.php b/tests/Browser/SettingsSidebarTest.phpindex 111426752..d144f6f32 100644--- a/tests/Browser/SettingsSidebarTest.php+++ b/tests/Browser/SettingsSidebarTest.php@@ -107,7 +107,7 @@ test('settings pages swap the app sidebar for the settings sidebar', function ()->assertPresent('[data-testid="settings-nav-api-keys"] svg.tabler-icon-code')->assertMissing('@settings-nav-authentication')->assertPresent('[data-testid="settings-nav-general"] svg.tabler-icon-building')- ->assertPresent('[data-testid="settings-nav-mcp"] svg.tabler-icon-plug')+ ->assertPresent('[data-testid="settings-nav-mcp"] svg.tabler-icon-mcp')->assertSeeIn('@settings-sidebar', 'Content')->assertDontSeeIn('@settings-sidebar', 'Features')->assertSeeIn('@settings-sidebar', 'Integrations')diff --git a/tests/Browser/WelcomeMcpTest.php b/tests/Browser/WelcomeMcpTest.phpindex 0e70526a5..a58402b4c 100644--- a/tests/Browser/WelcomeMcpTest.php+++ b/tests/Browser/WelcomeMcpTest.php@@ -302,6 +302,10 @@ test('the MCP step opens a dialog with the steps and the app link, and can be skexpect(collect(welcomeMcpTops($page, '[data-testid^=welcome-mcp-connect-]:not([data-testid=welcome-mcp-connect-ai])'))->map(fn (float|int $top): float => round($top))->unique()->count())->toBe(1);+ expect($page->script(<<<'JS'+ [...document.querySelectorAll('[data-testid^="welcome-mcp-connect-"]:not([data-testid="welcome-mcp-connect-ai"]) svg')].every((mark) => getComputedStyle(mark).fill === getComputedStyle(mark).color)+ JS))->toBeTrue();+$page->assertSeeIn('@welcome-mcp-connect-claude', 'Connect with Claude')->assertMissing('@welcome-mcp-copy')->assertMissing('@mcp-dialog')diff --git a/tests/Browser/WorkspaceInsightsTest.php b/tests/Browser/WorkspaceInsightsTest.phpindex 5e4151a17..65684ad43 100644--- a/tests/Browser/WorkspaceInsightsTest.php+++ b/tests/Browser/WorkspaceInsightsTest.php@@ -19,54 +19,11 @@ use App\Models\User;use App\Models\Workspace;use Illuminate\Support\Facades\Queue;-function waitForWorkspaceInsightsTestId(mixed $page, string $testId): void-{- $page->script(<<<JS- (async () => {- const selector = '[data-testid="{$testId}"]';- for (let attempt = 0; attempt < 600; attempt++) {- const element = document.querySelector(selector);- if (element && element.getBoundingClientRect().height > 0) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- })();- JS);-}-function workspaceInsightsTestIdSelector(string $testId): string{return json_encode("[data-testid=\"{$testId}\"]");}-function waitForWorkspaceInsightsTestIdGone(mixed $page, string $testId): void-{- $selector = workspaceInsightsTestIdSelector($testId);-- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if (!document.querySelector({$selector})) return;- await new Promise((resolve) => setTimeout(resolve, 100));- }- })();- JS);-}--function waitForWorkspaceInsightsQueryParameter(mixed $page, string $name, string $value): void-{- $name = json_encode($name);- $value = json_encode($value);-- $page->script(<<<JS- (async () => {- for (let attempt = 0; attempt < 100; attempt++) {- if (new URLSearchParams(location.search).get({$name}) === {$value}) return;- await new Promise((resolve) => setTimeout(resolve, 100));- }- })();- JS);-}-function clickWorkspaceInsightsTestIdUntilDialogOpens(mixed $page, string $testId): void{$selector = workspaceInsightsTestIdSelector($testId);@@ -239,7 +196,7 @@ test('workspace dashboard separates accounts and switches follower and post char$this->actingAs($user);$page = visit(route('app.insights'));- waitForWorkspaceInsightsTestId($page, 'analytics-summary-followers');+ waitFor($page, '@analytics-summary-followers');$page->assertVisible('@analytics-summary-followers');@@ -251,6 +208,8 @@ test('workspace dashboard separates accounts and switches follower and post char->assertPresent('@analytics-top-post')->assertPresent('@header-icon')->assertPresent('@insights-range-caption')+ ->assertSeeIn('[data-testid="insights-range-caption"] [data-testid="analytics-range-previous"]', 'vs')+ ->assertSeeIn('[data-testid="analytics-performance-caption"] [data-testid="analytics-range-previous"]', 'vs')->assertSee('Performance')->assertPresent('@accounts-unovis-bar-chart')->hover('[data-testid="analytics-account-bar"] >> nth=0')@@ -264,7 +223,12 @@ test('workspace dashboard separates accounts and switches follower and post char->assertPresent('@accounts-unovis-bar-chart')->click('@posts-stacked')->assertVisible('@posts-unovis-chart')- ->hover('[data-testid="analytics-post-bar"] >> nth=0')+ ->assertScript('document.querySelector("[data-testid=posts-unovis-chart]").textContent.includes("Posts")', false)+ ->hover('[data-testid="analytics-post-bar"] >> nth=0');+ waitFor($page, '@analytics-tooltip-total');++ $page->assertSeeIn('@analytics-tooltip-total', 'Total Posts')+ ->assertSeeIn('@analytics-tooltip-total', '2')->assertPresent('@analytics-tooltip-avatar')->click('@top-comments');@@ -290,7 +254,7 @@ test('workspace dashboard explains the empty state without inventing follower to$this->actingAs($user);$page = visit(route('app.insights'));- waitForWorkspaceInsightsTestId($page, 'analytics-empty-state');+ waitFor($page, '@analytics-empty-state');$page->assertVisible('@analytics-empty-state')->assertPresent('@app-layout-content')@@ -309,7 +273,7 @@ test('workspace dashboard explains the empty state without inventing follower to$page->click('@analytics-empty-connect');- waitForWorkspaceInsightsTestId($page, 'connect-channel-dialog');+ waitFor($page, '@connect-channel-dialog');$page->assertVisible('@connect-channel-dialog')->resize(375, 812);@@ -331,7 +295,7 @@ test('the empty insights hero explains pending data once a channel is connected'$this->actingAs($user);$page = visit(route('app.insights'));- waitForWorkspaceInsightsTestId($page, 'analytics-empty-state');+ waitFor($page, '@analytics-empty-state');$page->assertVisible('@analytics-empty-state')->assertSee('Your analytics history is being prepared')@@ -369,7 +333,7 @@ test('the custom preset opens the calendar with quick ranges that apply a custom$this->actingAs($user);$page = visit(route('app.insights', ['start' => $firstDay->toDateString(), 'end' => $firstDay->addMonth()->toDateString()]));- waitForWorkspaceInsightsTestId($page, 'insights-range-custom');+ waitFor($page, '@insights-range-custom');$page->assertMissing('@date-range-picker-trigger')->assertAttribute('@insights-range-custom', 'aria-pressed', 'true')@@ -380,7 +344,7 @@ test('the custom preset opens the calendar with quick ranges that apply a custom$page->assertPresent('[role=dialog]')->assertSeeIn('@date-range-preset-last_7_days', __('common.date_range_picker.last_7_days', [], 'pt-BR'))->click('@date-range-preset-last_7_days');- waitForWorkspaceInsightsQueryParameter($page, 'start', $latestDay->subDays(6)->toDateString());+ waitForQueryParameter($page, 'start', $latestDay->subDays(6)->toDateString());$page->assertQueryStringHas('range', 'custom')->assertQueryStringHas('start', $latestDay->subDays(6)->toDateString())@@ -410,10 +374,10 @@ test('a range preset on the workspace dashboard reloads with that range', functi$this->actingAs($user);$page = visit(route('app.insights'));- waitForWorkspaceInsightsTestId($page, 'insights-range-7d');+ waitFor($page, '@insights-range-7d');$page->click('@insights-range-7d');- waitForWorkspaceInsightsQueryParameter($page, 'range', '7d');+ waitForQueryParameter($page, 'range', '7d');$page->assertQueryStringHas('range', '7d')->assertAttribute('@insights-range-7d', 'aria-pressed', 'true')@@ -432,7 +396,7 @@ test('dashboard refreshes when the first analytics snapshot arrives after openin$this->actingAs($user);$page = visit(route('app.insights'));- waitForWorkspaceInsightsTestId($page, 'analytics-empty-state');+ waitFor($page, '@analytics-empty-state');$page->assertVisible('@analytics-empty-state');AnalyticsAccountDailySnapshot::factory()->create([@@ -446,7 +410,7 @@ test('dashboard refreshes when the first analytics snapshot arrives after openin'followers_count' => 123,]);- waitForWorkspaceInsightsTestId($page, 'analytics-summary-followers');+ waitFor($page, '@analytics-summary-followers');$page->assertVisible('@analytics-summary-followers')->assertNoJavaScriptErrors()@@ -470,11 +434,11 @@ test('import progress disappears after the queued backfill finishes without navi$this->actingAs($user);$page = visit(route('app.insights'));- waitForWorkspaceInsightsTestId($page, 'analytics-import-coverage');+ waitFor($page, '@analytics-import-coverage');$page->assertVisible('@analytics-import-coverage');$state->update(['status' => SyncStatus::Complete]);- waitForWorkspaceInsightsTestIdGone($page, 'analytics-import-coverage');+ waitForGone($page, '@analytics-import-coverage');$page->assertMissing('@analytics-import-coverage')->assertNoJavaScriptErrors()@@ -554,7 +518,7 @@ test('workspace dashboard abbreviates large percentage changes in the user local$this->actingAs($user);$page = visit(route('app.insights', ['start' => $rangeStart->toDateString(), 'end' => $rangeEnd->toDateString()]));- waitForWorkspaceInsightsTestId($page, 'analytics-summary-reactions-change');+ waitFor($page, '@analytics-summary-reactions-change');expect(workspaceInsightsInnerText($page, 'analytics-summary-reactions-change'))->toContain($expectedChange);@@ -574,14 +538,14 @@ test('the channel filter offers to connect a channel when the workspace has none$this->actingAs($user);$page = visit(route('app.insights'));- waitForWorkspaceInsightsTestId($page, 'analytics-channel-filter');+ waitFor($page, '@analytics-channel-filter');$page->click('@analytics-channel-filter');- waitForWorkspaceInsightsTestId($page, 'analytics-channel-connect');+ waitFor($page, '@analytics-channel-connect');$page->assertSeeIn('@analytics-channel-connect', __('channels.connect'))->click('@analytics-channel-connect');- waitForWorkspaceInsightsTestId($page, 'connect-channel-dialog');+ waitFor($page, '@connect-channel-dialog');$page->assertVisible('@connect-channel-dialog')->assertNoJavaScriptErrors();});@@ -607,18 +571,18 @@ test('on a phone the workspace insights range presets collapse into a dropdown',$this->actingAs($user);$page = visit(route('app.insights'))->resize(390, 844);- waitForWorkspaceInsightsTestId($page, 'insights-range-mobile-trigger');+ waitFor($page, '@insights-range-mobile-trigger');expect(workspaceInsightsRect($page, 'insights-range-7d')['height'] ?? null)->toBe(0);$page->assertSeeIn('@insights-range-mobile-trigger', '30 Days')->click('@insights-range-mobile-trigger');- waitForWorkspaceInsightsTestId($page, 'insights-range-mobile-30d-check');+ waitFor($page, '@insights-range-mobile-30d-check');$page->assertPresent('@insights-range-mobile-30d-check')->assertMissing('@insights-range-mobile-7d-check')->click('@insights-range-mobile-7d');- waitForWorkspaceInsightsQueryParameter($page, 'range', '7d');+ waitForQueryParameter($page, 'range', '7d');$page->assertQueryStringHas('range', '7d')->assertSeeIn('@insights-range-mobile-trigger', '7 Days')@@ -660,6 +624,8 @@ test('the custom range calendar opens under Custom on desktop and as a bottom sh$page->assertNoJavaScriptErrors();$phone = visit(route('app.insights'))->resize(390, 844);+ waitFor($phone, '@insights-range-mobile-trigger');+ $phone->click('@insights-range-mobile-trigger');waitFor($phone, '@insights-range-mobile-custom');$phone->click('@insights-range-mobile-custom');waitForState($phone, '@date-range-picker-sheet', 'element.getBoundingClientRect().bottom >= window.innerHeight - 1');@@ -708,8 +674,8 @@ test('charts keep their width while the sidebar animates and resize once it sett$this->actingAs($user);$page = visit(route('app.insights'))->resize(1440, 900);- waitForWorkspaceInsightsTestId($page, 'accounts-unovis-bar-chart');- waitForWorkspaceInsightsTestId($page, 'sidebar-footer-toggle');+ waitFor($page, '@accounts-unovis-bar-chart');+ waitFor($page, '@sidebar-footer-toggle');$widths = workspaceInsightsChartWidthsAroundSidebarToggle($page);@@ -762,7 +728,7 @@ test('top posts name the network each post went out on and leave the post type o->assertSeeIn("@analytics-top-post-published-via-{$publications['tiktok']->id}", 'TikTok')->assertPresent("[data-testid=\"analytics-top-post-channel\"] [data-testid=\"channel-avatar-verified-{$verified->id}\"]")->assertMissing("[data-testid=\"analytics-top-post-channel\"] [data-testid=\"channel-avatar-verified-{$publications['tiktok']->social_account_id}\"]")- ->assertScript("document.querySelectorAll('[data-testid=\"analytics-section\"] [data-testid=\"channel-avatar-verified-{$verified->id}\"]').length >= 4", true)+ ->assertScript("document.querySelectorAll('[data-testid=\"analytics-section\"] [data-testid=\"channel-avatar-verified-{$verified->id}\"]').length >= 3", true)->assertMissing("@analytics-top-post-type-{$publications['reel']->id}")->assertDontSee('Published on the social network')->assertNoJavaScriptErrors();@@ -795,9 +761,111 @@ test('top posts show the post media from our bucket, a video by its cover frame'$this->actingAs($user);$page = visit(route('app.insights'));- waitForWorkspaceInsightsTestId($page, "analytics-top-post-video-{$publications['video']->id}");+ waitFor($page, "@analytics-top-post-video-{$publications['video']->id}");$page->assertAttribute("@analytics-top-post-video-{$publications['video']->id}", 'src', 'https://cdn.trypost.test/medias/reel.mp4#t=0.1')->assertScript("Array.from(document.querySelectorAll('[data-testid=\"analytics-top-post\"] img')).map((image) => image.getAttribute('src')).includes('http://trypost.test/storage/medias/a.jpg')", true)->assertNoJavaScriptErrors();});++test('the range caption names each period in full at its edges', function (string $start, string $end, string $current, string $previous, Locale $locale = Locale::DEFAULT) {+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);+ $user = User::factory()->create(['locale' => $locale]);+ $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);+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);+ foreach ([$start, $end] as $day) {+ AnalyticsPublication::factory()->create([+ 'workspace_id' => $workspace->id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'provider_published_at' => "{$day} 10:00:00",+ ]);+ }++ $this->actingAs($user);+ $page = visit(route('app.insights', ['start' => $start, 'end' => $end]));+ waitFor($page, '@insights-range-caption');++ expect(workspaceInsightsInnerText($page, 'analytics-range-current'))->toBe($current)+ ->and(trim((string) $page->script('document.querySelector(\'[data-testid="insights-range-caption"] [data-testid="analytics-range-previous"]\')?.innerText ?? ""')))->toBe($previous);++ $page->assertNoJavaScriptErrors();+})->with([+ 'one day' => ['2026-01-10', '2026-01-10', '10 Jan 2026', 'vs 9 Jan'],+ 'a previous period across New Year' => ['2026-01-04', '2026-01-10', '4 – 10 Jan 2026', 'vs 28 Dec 2025 – 3 Jan 2026'],+ 'periods across a month' => ['2026-10-02', '2026-10-08', '2 – 8 Oct 2026', 'vs 25 Sep – 1 Oct'],+ 'in Portuguese' => ['2026-10-02', '2026-10-08', '2 – 8 out 2026', 'vs. 25 set – 1 out', Locale::PortugueseBrazil],+]);++test('on a phone the custom range applies the two days picked in its sheet', function () {+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);+ $user = User::factory()->create();+ $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);+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);++ foreach (range(0, 40) as $daysAgo) {+ AnalyticsAccountDailySnapshot::factory()->create([+ 'workspace_id' => $workspace->id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => Platform::Instagram,+ 'network' => Platform::Instagram->network(),+ 'platform_user_id' => $account->platform_user_id,+ 'date' => now('UTC')->subDays($daysAgo)->toDateString(),+ 'followers_count' => 100,+ ]);+ }++ $this->actingAs($user);+ $page = visit(route('app.insights'))->resize(390, 844);+ waitFor($page, '@insights-range-mobile-trigger');+ $page->click('@insights-range-mobile-trigger');+ waitFor($page, '@insights-range-mobile-custom');+ $page->click('@insights-range-mobile-custom');+ waitFor($page, '@date-range-picker-sheet [data-slot="range-calendar-trigger"]');++ $days = $page->script(<<<'JS'+ Array.from(document.querySelectorAll('[data-testid="date-range-picker-sheet"] [data-slot="range-calendar-trigger"]'))+ .filter((day) => !day.hasAttribute('data-disabled') && !day.hasAttribute('data-outside-view'))+ .slice(0, 2)+ .map((day) => day.dataset.value)+ JS);++ foreach ($days as $day) {+ $page->click("[data-testid=\"date-range-picker-sheet\"] [data-slot=\"range-calendar-trigger\"][data-value=\"{$day}\"]");+ }++ waitForCondition($page, "new URLSearchParams(location.search).get('end') === '{$days[1]}'");++ $page->assertQueryStringHas('range', 'custom')+ ->assertQueryStringHas('start', $days[0])+ ->assertQueryStringHas('end', $days[1])+ ->assertNoJavaScriptErrors();+});++test('on a phone the custom range stays off until the workspace has data', function () {+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);+ $user = User::factory()->create();+ $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);+ SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);++ $this->actingAs($user);+ $page = visit(route('app.insights'))->resize(390, 844);+ waitFor($page, '@insights-range-mobile-trigger');+ $page->click('@insights-range-mobile-trigger');+ waitFor($page, '@insights-range-mobile-custom');++ $page->assertAttribute('@insights-range-mobile-custom', 'data-disabled', '')+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php b/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.phpindex 2e59677fa..ab0e6f02a 100644--- a/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php+++ b/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php@@ -127,6 +127,7 @@ test('workspace report keeps accounts separate and aggregates only latest normal->and($report['summary']['engagement_rate']['previous'])->toBe(10.0)->and($report['bounds'])->toBe(['min' => '2026-08-25', 'max' => '2026-09-10'])->and($report['posts']['resolution'])->toBe('daily')+ ->and($report['posts']['total'])->toBe(3)->and(count($report['posts']['buckets']))->toBe(10)->and(array_column($report['posts']['buckets'], 'total'))->toBe([0, 0, 0, 0, 1, 1, 1, 0, 0, 0])->and(array_key_exists('label', $report['posts']['buckets'][0]))->toBeFalse()@@ -135,7 +136,8 @@ test('workspace report keeps accounts separate and aggregates only latest normal->and($report['followers']['total'])->toBe(170)->and($report['top_posts']['reactions'][0]['social_account_key'])->toBe($instagramA->id)->and($report['top_posts']['reactions'][0]['post_id'])->toBeNull()- ->and($report['top_posts']['reactions'][0]['reactions'])->toBe(10);+ ->and($report['top_posts']['reactions'][0]['reactions'])->toBe(10)+ ->and(array_column($report['top_posts']['reactions'], 'rank'))->toBe(range(1, count($report['top_posts']['reactions'])));$performanceKeys = array_column($report['performance'], 'social_account_key');expect($performanceKeys)->toContain($instagramA->id, $instagramB->id, $x->id);diff --git a/tests/Feature/Services/Social/DisplayLengthParityTest.php b/tests/Feature/Services/Social/DisplayLengthParityTest.phpindex 4d206ef66..5c9014a23 100644--- a/tests/Feature/Services/Social/DisplayLengthParityTest.php+++ b/tests/Feature/Services/Social/DisplayLengthParityTest.php@@ -15,7 +15,7 @@ test('the composer counts plain text the way the server measures it on every net$process = new Process(['node',- base_path('tests/fixtures/display-length-harness.js'),+ base_path('tests/fixtures/display-length-harness.ts'),resource_path('js'),$corpusPath,$platformsPath,diff --git a/tests/Feature/Services/Social/HashtagParityTest.php b/tests/Feature/Services/Social/HashtagParityTest.phpindex 19311ead4..3272b863c 100644--- a/tests/Feature/Services/Social/HashtagParityTest.php+++ b/tests/Feature/Services/Social/HashtagParityTest.php@@ -11,7 +11,7 @@ test('the typescript hashtag counter agrees with the php one on every corpus ent$process = new Process(['node',- base_path('tests/fixtures/hashtag-harness.js'),+ base_path('tests/fixtures/hashtag-harness.ts'),resource_path('js/lib/hashtags.ts'),$corpusPath,]);diff --git a/tests/Feature/Services/Social/XLinkDefusingParityTest.php b/tests/Feature/Services/Social/XLinkDefusingParityTest.phpindex 3258962cd..2a6426509 100644--- a/tests/Feature/Services/Social/XLinkDefusingParityTest.php+++ b/tests/Feature/Services/Social/XLinkDefusingParityTest.php@@ -22,7 +22,7 @@ test('the typescript defuser agrees with the php one on every corpus entry', fun$process = new Process(['node',- base_path('tests/fixtures/defuse-x-links-harness.js'),+ base_path('tests/fixtures/defuse-x-links-harness.ts'),$tldsPath,resource_path('js/lib/defuseXLinks.ts'),$corpusPath,diff --git a/tests/Pest.php b/tests/Pest.phpindex 4aaf7f816..b19e96021 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -733,6 +733,28 @@ function waitForCondition(mixed $page, string $condition): voidJS);}+/**+ * Wait until a condition the test reads on the server (a row in the database)+ * holds, letting the page's own requests land between tries.+ */+function waitForDatabase(mixed $page, Closure $condition): void+{+ for ($attempt = 0; $attempt < 50 && ! $condition(); $attempt++) {+ $page->script('new Promise((resolve) => setTimeout(resolve, 100))');+ }+}++/**+ * Wait until the page's URL carries this query parameter value.+ */+function waitForQueryParameter(mixed $page, string $name, string $value): void+{+ $name = json_encode($name);+ $value = json_encode($value);++ waitForCondition($page, "new URLSearchParams(location.search).get({$name}) === {$value}");+}+/*** The selector as a JavaScript string, with `@name` standing for* `[data-testid="name"]` as in `$page->click('@name')`, anywhere in it:@@ -805,3 +827,54 @@ function waitForPath(mixed $page, string $path): voidwaitForCondition($page, "location.pathname === {$path}");}++/**+ * Records what every canvas on the page draws from now on: each text with+ * its direction, place, width, alignment and font (`window.__drawn`), each image's address+ * (`window.__images`) and how many patterns it fills with (`window.__patterns`,+ * the share card's hatch for a previous period). A canvas cannot be read back+ * as text, so a test of a painted card reads these instead.+ */+function recordCanvasDrawing(mixed $page): void+{+ $page->script(<<<'JS'+ (() => {+ if (window.__drawn) {+ return;+ }++ window.__drawn = [];+ window.__images = [];+ window.__patterns = 0;+ window.__paths = [];+ const NativePath2D = window.Path2D;+ window.Path2D = class extends NativePath2D {+ constructor(path) {+ super(path);++ if (typeof path === 'string') {+ window.__paths.push(path);+ }+ }+ };+ const createPattern = CanvasRenderingContext2D.prototype.createPattern;+ const fillText = CanvasRenderingContext2D.prototype.fillText;+ const drawImage = CanvasRenderingContext2D.prototype.drawImage;+ CanvasRenderingContext2D.prototype.fillText = function (text, ...rest) {+ window.__drawn.push({ text: String(text), direction: this.direction, x: rest[0], y: rest[1], width: this.measureText(String(text)).width, align: this.textAlign, font: this.font });++ return fillText.call(this, text, ...rest);+ };+ CanvasRenderingContext2D.prototype.createPattern = function (...args) {+ window.__patterns += 1;++ return createPattern.apply(this, args);+ };+ CanvasRenderingContext2D.prototype.drawImage = function (image, ...rest) {+ window.__images.push(image.src ?? '');++ return drawImage.call(this, image, ...rest);+ };+ })();+ JS);+}diff --git a/tests/Unit/Enums/MediaEditorPresetsParityTest.php b/tests/Unit/Enums/MediaEditorPresetsParityTest.phpindex 9d4639b0c..b0c1cead8 100644--- a/tests/Unit/Enums/MediaEditorPresetsParityTest.php+++ b/tests/Unit/Enums/MediaEditorPresetsParityTest.php@@ -8,7 +8,7 @@ use Symfony\Component\Process\ExecutableFinder;use Symfony\Component\Process\Process;/**- * Runs `tests/fixtures/media-editor-harness.js` over the real `mediaRules()`+ * Runs `tests/fixtures/media-editor-harness.ts` over the real `mediaRules()`* payload of every content type and returns its JSON output.** @return array<string, mixed>@@ -30,7 +30,7 @@ function runMediaEditorPresetsHarness(): arraytry {$process = (new Process([$node,- base_path('tests/fixtures/media-editor-harness.js'),+ base_path('tests/fixtures/media-editor-harness.ts'),resource_path('js'),$input,]))->mustRun();diff --git a/tests/Unit/Enums/MediaTypeParityTest.php b/tests/Unit/Enums/MediaTypeParityTest.phpindex 9ae36dd4a..9fbba9e02 100644--- a/tests/Unit/Enums/MediaTypeParityTest.php+++ b/tests/Unit/Enums/MediaTypeParityTest.php@@ -26,7 +26,7 @@ test('the typescript media classifier agrees with the php enum on every corpus e// mustRun(): a broken harness or a syntax error in mediaType.ts is a failure, not a skip.$process = (new Process([$node,- base_path('tests/fixtures/media-type-harness.js'),+ base_path('tests/fixtures/media-type-harness.ts'),resource_path('js/lib/mediaType.ts'),$corpusPath,]))->mustRun();diff --git a/tests/Unit/Enums/PostPlatform/ContentTypeForMediaTest.php b/tests/Unit/Enums/PostPlatform/ContentTypeForMediaTest.phpindex a03137c6f..17150effe 100644--- a/tests/Unit/Enums/PostPlatform/ContentTypeForMediaTest.php+++ b/tests/Unit/Enums/PostPlatform/ContentTypeForMediaTest.php@@ -86,7 +86,7 @@ test('the composer picks the same type as forMedia for every network and media mtry {$process = (new Process([$node,- base_path('tests/fixtures/derived-content-type-harness.js'),+ base_path('tests/fixtures/derived-content-type-harness.ts'),resource_path('js'),$input,]))->mustRun();diff --git a/tests/Unit/ShareCardArithmeticTest.php b/tests/Unit/ShareCardArithmeticTest.phpnew file mode 100644index 000000000..35ebabfd1--- /dev/null+++ b/tests/Unit/ShareCardArithmeticTest.php@@ -0,0 +1,84 @@+<?php++declare(strict_types=1);++use Symfony\Component\Process\ExecutableFinder;+use Symfony\Component\Process\Process;++/**+ * Runs `tests/fixtures/share-card-harness.ts` over the share card's pure+ * arithmetic and returns its JSON output.+ *+ * @return array<string, mixed>+ */+function runShareCardHarness(): array+{+ $node = (new ExecutableFinder)->find('node');++ if ($node === null) {+ test()->markTestSkipped('node is unavailable');+ }++ $process = (new Process([$node, base_path('tests/fixtures/share-card-harness.ts'), resource_path('js')]))->mustRun();++ return json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);+}++test('the card picks the same value ticks as d3, which the page axes use', function () {+ expect(runShareCardHarness()['ticks'])->toEqual([+ 'days' => [0, 5, 10, 15, 20, 25],+ 'growth' => [-20, -10, 0, 10, 20, 30],+ 'closeFollowers' => [9990, 9995, 10000, 10005, 10010],+ 'fractions' => [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3],+ 'halfSteps' => [1000, 1000.5, 1001, 1001.5, 1002],+ ]);+});++test('the card dates the days the page axes date, on whole days only', function () {+ expect(runShareCardHarness()['dates'])->toEqual([+ 'combo9' => [0, 2, 4, 6, 8],+ 'combo19' => [0, 5, 10, 15],+ 'even2' => [0, 1],+ 'even30' => [0, 5, 10, 15, 20, 25],+ ]);+});++test('the stacked card labels every column that fits and skips evenly when they do not', function () {+ expect(runShareCardHarness()['columns'])->toEqual([+ 'crowded' => [0, 3, 6, 9, 12],+ 'roomy' => [0, 1, 2, 3],+ ]);+});++test('a value axis runs over the values with zero in it', function () {+ $axis = runShareCardHarness()['axis'];++ expect($axis['ticks'])->toEqual([-20, -10, 0, 10, 20, 30])+ ->and($axis['zero'])->toEqualWithDelta(26 / 56, 0.000001);+});++test('the card draws the same monotone curve as d3: flat before a spike, eased while rising, straight for two points', function () {+ expect(runShareCardHarness()['curve'])->toEqual([+ 'spike' => [+ ['M', 0, 10],+ ['C', 3.333333, 10, 6.666667, 10, 10, 10],+ ['C', 13.333333, 10, 16.666667, 10, 20, 10],+ ['C', 23.333333, 10, 26.666667, 80, 30, 80],+ ['C', 33.333333, 80, 36.666667, 50, 40, 20],+ ],+ 'rising' => [+ ['M', 0, 0],+ ['C', 3.333333, 0.166667, 6.666667, 0.333333, 10, 1],+ ['C', 13.333333, 1.666667, 16.666667, 5.166667, 20, 10],+ ['C', 23.333333, 14.833333, 26.666667, 22.416667, 30, 30],+ ],+ 'two' => [['M', 0, 0], ['L', 10, 5]],+ ]);+});++test('line end labels move apart just enough and stay inside the plot', function () {+ expect(runShareCardHarness()['labels'])->toEqual([+ 'apart' => [100, 124, 300],+ 'atTheBottom' => [364, 388],+ ]);+});diff --git a/tests/Unit/Support/FacebookLinkPreviewTest.php b/tests/Unit/Support/FacebookLinkPreviewTest.phpindex 0d5972dd3..d9ff1682e 100644--- a/tests/Unit/Support/FacebookLinkPreviewTest.php+++ b/tests/Unit/Support/FacebookLinkPreviewTest.php@@ -44,7 +44,7 @@ test('the editor picks the same facebook link as the publisher', function () {$process = new Process(['node','--experimental-strip-types',- base_path('tests/fixtures/facebook-link-preview-harness.js'),+ base_path('tests/fixtures/facebook-link-preview-harness.ts'),resource_path('js/lib/facebookLinkPreview.ts'),$corpusPath,]);diff --git a/tests/fixtures/defuse-x-links-harness.js b/tests/fixtures/defuse-x-links-harness.tssimilarity index 67%rename from tests/fixtures/defuse-x-links-harness.jsrename to tests/fixtures/defuse-x-links-harness.tsindex 321907b0e..78fb8e197 100644--- a/tests/fixtures/defuse-x-links-harness.js+++ b/tests/fixtures/defuse-x-links-harness.ts@@ -11,14 +11,14 @@ import fs from 'node:fs';const [tldsFile, defuserFile, corpusFile] = process.argv.slice(2);-const tlds = new Set(JSON.parse(fs.readFileSync(tldsFile, 'utf8')));+const tlds = new Set<string>(JSON.parse(fs.readFileSync(tldsFile, 'utf8')));const pattern = new RegExp(- fs.readFileSync(defuserFile, 'utf8').match(/const LINK_PATTERN =\s*\/(.*)\/giu;/s)[1],+ fs.readFileSync(defuserFile, 'utf8').match(/const LINK_PATTERN =\s*\/(.*)\/giu;/s)?.[1] ?? '','giu',);-const defuse = (content) =>- content.replace(pattern, (whole, boundary, prefix, host, tld, path) =>+const defuse = (content: string): string =>+ content.replace(pattern, (whole: string, boundary: string, prefix: string, host: string, tld: string, path: string) =>prefix === '' && !tlds.has(tld.toLowerCase()) ? whole : boundary + host.replaceAll('.', '(.)') + path);-console.log(JSON.stringify(JSON.parse(fs.readFileSync(corpusFile, 'utf8')).map(defuse)));+console.log(JSON.stringify((JSON.parse(fs.readFileSync(corpusFile, 'utf8')) as string[]).map(defuse)));diff --git a/tests/fixtures/derived-content-type-harness.js b/tests/fixtures/derived-content-type-harness.tssimilarity index 91%rename from tests/fixtures/derived-content-type-harness.jsrename to tests/fixtures/derived-content-type-harness.tsindex a9b1969ed..25e8a8c5a 100644--- a/tests/fixtures/derived-content-type-harness.js+++ b/tests/fixtures/derived-content-type-harness.ts@@ -29,7 +29,9 @@ const { getContentTypeOptions } = await import(pathToFileURL(path.join(path.resolve(resourcesDir), 'composables/usePlatformLogo.ts')).href);-const cases = JSON.parse(fs.readFileSync(inputFile, 'utf8'));+type Case = { platform: string; media: unknown[] };++const cases: Record<string, Case> = JSON.parse(fs.readFileSync(inputFile, 'utf8'));const results = Object.fromEntries(Object.entries(cases).map(([key, { platform, media }]) => [diff --git a/tests/fixtures/display-length-harness.js b/tests/fixtures/display-length-harness.tssimilarity index 86%rename from tests/fixtures/display-length-harness.jsrename to tests/fixtures/display-length-harness.tsindex 8713764d9..51840ab7d 100644--- a/tests/fixtures/display-length-harness.js+++ b/tests/fixtures/display-length-harness.ts@@ -18,7 +18,7 @@ registerHooks({});const { displayLength } = await import(new URL('lib/characters.ts', base).href);-const corpus = JSON.parse(fs.readFileSync(corpusFile, 'utf8'));-const platforms = JSON.parse(fs.readFileSync(platformsFile, 'utf8'));+const corpus: string[] = JSON.parse(fs.readFileSync(corpusFile, 'utf8'));+const platforms: string[] = JSON.parse(fs.readFileSync(platformsFile, 'utf8'));console.log(JSON.stringify(Object.fromEntries(platforms.map((platform) => [platform, corpus.map((text) => displayLength(text))]))));diff --git a/tests/fixtures/facebook-link-preview-harness.js b/tests/fixtures/facebook-link-preview-harness.tssimilarity index 86%rename from tests/fixtures/facebook-link-preview-harness.jsrename to tests/fixtures/facebook-link-preview-harness.tsindex 13fc8ae8e..25ef62d86 100644--- a/tests/fixtures/facebook-link-preview-harness.js+++ b/tests/fixtures/facebook-link-preview-harness.ts@@ -8,6 +8,6 @@ import { pathToFileURL } from 'node:url';const [modulePath, corpusPath] = process.argv.slice(2);const { facebookLinkPreviewUrl } = await import(pathToFileURL(modulePath).href);-const corpus = JSON.parse(fs.readFileSync(corpusPath, 'utf8'));+const corpus: string[] = JSON.parse(fs.readFileSync(corpusPath, 'utf8'));console.log(JSON.stringify(corpus.map((entry) => facebookLinkPreviewUrl(entry))));diff --git a/tests/fixtures/hashtag-harness.js b/tests/fixtures/hashtag-harness.tssimilarity index 74%rename from tests/fixtures/hashtag-harness.jsrename to tests/fixtures/hashtag-harness.tsindex 8146ff3a1..cdc897ced 100644--- a/tests/fixtures/hashtag-harness.js+++ b/tests/fixtures/hashtag-harness.ts@@ -9,8 +9,8 @@ import fs from 'node:fs';const [sourceFile, corpusFile] = process.argv.slice(2);const pattern = new RegExp(- fs.readFileSync(sourceFile, 'utf8').match(/const HASHTAG_PATTERN =\s*\/(.*)\/gu;/s)[1],+ fs.readFileSync(sourceFile, 'utf8').match(/const HASHTAG_PATTERN =\s*\/(.*)\/gu;/s)?.[1] ?? '','gu',);-console.log(JSON.stringify(JSON.parse(fs.readFileSync(corpusFile, 'utf8')).map((text) => text.match(pattern)?.length ?? 0)));+console.log(JSON.stringify((JSON.parse(fs.readFileSync(corpusFile, 'utf8')) as string[]).map((text) => text.match(pattern)?.length ?? 0)));diff --git a/tests/fixtures/media-editor-harness.js b/tests/fixtures/media-editor-harness.tssimilarity index 70%rename from tests/fixtures/media-editor-harness.jsrename to tests/fixtures/media-editor-harness.tsindex 6b3964588..b44a82a88 100644--- a/tests/fixtures/media-editor-harness.js+++ b/tests/fixtures/media-editor-harness.ts@@ -28,15 +28,19 @@ const { toMediaRules } = await import(pathToFileURL(path.join(path.resolve(resourcesDir), 'lib/contentTypeMediaRules.ts')).href);-const { rules, defaults } = JSON.parse(fs.readFileSync(inputFile, 'utf8'));+type Bounds = { aspectRatioMin: number | null; aspectRatioMax: number | null };-const boundsOf = (rule) => ({ min: rule.aspectRatioMin, max: rule.aspectRatioMax });+type Preset = { value: string; ratio: number | null };-const summarize = (presets) => presets.map((preset) => ({ value: preset.value, ratio: preset.ratio }));+const { rules, defaults }: { rules: Record<string, unknown>; defaults: unknown } = JSON.parse(fs.readFileSync(inputFile, 'utf8'));-const valuesFor = (rule) => summarize(cropPresetsFor(presetValuesFor([rule], defaults), boundsOf(rule)));+const boundsOf = (rule: Bounds) => ({ min: rule.aspectRatioMin, max: rule.aspectRatioMax });-const noChannelValuesFor = (rule) => summarize(cropPresetsFor(defaults, boundsOf(rule)));+const summarize = (presets: Preset[]) => presets.map((preset) => ({ value: preset.value, ratio: preset.ratio }));++const valuesFor = (rule: Bounds) => summarize(cropPresetsFor(presetValuesFor([rule], defaults), boundsOf(rule)));++const noChannelValuesFor = (rule: Bounds) => summarize(cropPresetsFor(defaults, boundsOf(rule)));const results = Object.fromEntries(Object.entries(rules).map(([contentType, rule]) => [contentType, valuesFor(toMediaRules(rule))]),@@ -50,6 +54,6 @@ console.log(JSON.stringify({contentTypes: results,noChannelWithinBounds: noChannelResults,- noChannel: cropPresetsFor(presetValuesFor([], defaults)).map((preset) => preset.value),+ noChannel: cropPresetsFor(presetValuesFor([], defaults)).map((preset: Preset) => preset.value),}),);diff --git a/tests/fixtures/media-type-harness.js b/tests/fixtures/media-type-harness.tssimilarity index 79%rename from tests/fixtures/media-type-harness.jsrename to tests/fixtures/media-type-harness.tsindex 8c55139a4..bc89f0e1d 100644--- a/tests/fixtures/media-type-harness.js+++ b/tests/fixtures/media-type-harness.ts@@ -3,7 +3,7 @@* `{ type, isMov, isGif }` per entry as JSON, so `MediaTypeParityTest.php` can* diff the TypeScript against `App\Enums\Media\Type`, which it mirrors.*- * Node 22 strips type annotations on import, so the source is loaded as-is —+ * Node strips type annotations, so the source is loaded as-is —* no bundler, and nothing in `mediaType.ts` may depend on the DOM.*/import fs from 'node:fs';@@ -14,7 +14,7 @@ const [mediaTypeFile, corpusFile] = process.argv.slice(2);const { classify, isMov, isGif } = await import(pathToFileURL(path.resolve(mediaTypeFile)).href);-const results = JSON.parse(fs.readFileSync(corpusFile, 'utf8')).map((item) => ({+const results = (JSON.parse(fs.readFileSync(corpusFile, 'utf8')) as Record<string, unknown>[]).map((item) => ({type: classify(item),isMov: isMov(item),isGif: isGif(item),diff --git a/tests/fixtures/share-card-harness.ts b/tests/fixtures/share-card-harness.tsnew file mode 100644index 000000000..a23deb10b--- /dev/null+++ b/tests/fixtures/share-card-harness.ts@@ -0,0 +1,80 @@+/**+ * Runs the share card's pure arithmetic (`resources/js/lib/shareCard/scale.ts`,+ * `curve.ts` and `lib/labelLayout.ts`) over fixed inputs and prints the results+ * as JSON, so `ShareCardArithmeticTest.php` can hold them to d3's own output+ * and to hand-worked layouts.+ *+ * 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);+ },+});++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 { traceMonotone } = await load('lib/shareCard/curve.ts');+const { spreadLabels } = await load('lib/labelLayout.ts');++/** A canvas context that records the path it is asked to draw. */+const recorder = () => {+ const ops: Op[] = [];+ const round = (values: number[]): number[] => values.map((value) => Number(value.toFixed(6)));++ return {+ ops,+ beginPath: () => {},+ moveTo: (...values: number[]) => ops.push(['M', ...round(values)]),+ lineTo: (...values: number[]) => ops.push(['L', ...round(values)]),+ bezierCurveTo: (...values: number[]) => ops.push(['C', ...round(values)]),+ };+};++const curve = (points: [number, number][]): Op[] => {+ const context = recorder();++ traceMonotone(context, points.map(([x, y]) => ({ x, y })));++ return context.ops;+};++const axis = valueAxis([-26, 30], 5);++console.log(+ JSON.stringify({+ ticks: {+ days: linearTicks(0, 29, 6),+ growth: linearTicks(-26, 30, 5),+ closeFollowers: linearTicks(9990, 10010, 5),+ fractions: linearTicks(0, 0.3, 5),+ halfSteps: linearTicks(1000, 1002, 5),+ },+ dates: { combo9: comboDates(9), combo19: comboDates(19), even2: evenDates(2), even30: evenDates(30) },+ columns: { crowded: fittingColumns(13, 5), roomy: fittingColumns(4, 10) },+ axis: { ticks: axis.ticks, zero: axis.zero },+ curve: {+ spike: curve([[0, 10], [10, 10], [20, 10], [30, 80], [40, 20]]),+ rising: curve([[0, 0], [10, 1], [20, 10], [30, 30]]),+ two: curve([[0, 0], [10, 5]]),+ },+ 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.phpindex a4c351d26..eea719fc4 100644--- a/tests/fixtures/single-line-copy.php+++ b/tests/fixtures/single-line-copy.php@@ -31,6 +31,10 @@ return ['analytics.channel.series.followers' => 11,'analytics.channel.series.posts' => 13,'analytics.channel.this_period' => 15,+ 'analytics.ranges.versus' => 13,+ 'analytics.share.copy' => 19,+ 'analytics.share.create_post' => 17,+ 'analytics.share.download' => 13,'auth.login.title' => 24,'auth.register.password_requirements.min' => 25,'auth.register.password_requirements.mixed_case' => 30,