Skip to content

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

Publish, import and show X polls (#463)

Paulo Castellano04bf4b32b345
diff --git a/AGENTS.md b/AGENTS.md
index 58ad37c37..e3c75f5f9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -217,6 +217,7 @@ Vue components must have a single root element.
- Every change to the guard ships with a browser test in `tests/Browser/ComposerUnsavedChangesTest.php` that fails without it, checked by removing the change and running the test. History bugs here showed up only in a real browser (Inertia's own popstate handler is part of every flow).
- **Composables are scoped by area.** A composable used by one area only lives in that area's folder, `resources/js/composables/<area>/` (e.g. `composables/composer/useComposerUnsavedChanges.ts`, `composables/echo/usePostEcho.ts`). Only composables shared across areas stay at the root of `resources/js/composables/`. When a scoped composable gains a consumer in another area, move it to the root in the same change.
- Searching a list in the UI goes through `matchesSearch` / `filterBySearch` (`resources/js/lib/search.ts`): word by word, ignoring case and accents. Never hand-roll `.toLowerCase().includes(...)` for a search box.
+- **Value checks go through `@/lib/helpers`** (owner decision November 2026), the front-end mirror of Laravel's helpers, so a check reads the same on both sides: `blank()` / `filled()` for emptiness, `isEmpty()` (Laravel's `isEmpty()` on a string or a collection) when spaces count, instead of `=== ''` or `.length === 0`, `isString()` / `isNumber()` instead of `typeof x === 'string'`, `transform(value, callback, fallback)` instead of `value ? callback(value) : fallback`, and `clamp()` (Laravel's `Number::clamp`) instead of `Math.min(Math.max(...))`. Emptiness reads `filled(reply.media)`, not `reply.media.length > 0`; `filled(limits)`, not `limits !== null`. Every helper follows its PHP twin, kept equal by `tests/Unit/HelpersParityTest.php`: null, undefined, a whitespace-only string and an empty array or plain object are blank; numbers and booleans (zero and false included) never are. `filled()` narrows the type, so after `if (filled(reply))` the value is no longer null or undefined. Keep an exact `=== undefined` where an empty object is a real value (a poll or meta that may be `{}`), since `blank({})` is true. A new helper (Laravel's `transform`, `value`, …) goes in the same file with a case in the parity test. Existing hand-written checks move to the helpers when touched, not in a sweep.
- **A translated sentence with markup (bold, italic, a link) goes through `TransSlots`** (`resources/js/components/TransSlots.vue`, owner decision October 2026), our take on vue-i18n's `<i18n-t>` component interpolation for laravel-vue-i18n's `:placeholder` syntax. The lang string holds plain text and `:placeholders` only, in all 16 locales; each placeholder is filled by a named slot, so the markup lives in the template and every value is escaped by Vue: `<TransSlots :message="$t('calendar.reschedule.custom_time.description')"><template #from><strong>{{ fromTime }}</strong></template></TransSlots>`. Never put HTML in a lang string rendered with `v-html`, never escape replacement values by hand, and never split one sentence across several keys to style part of it. The `v-html` translations that predate this rule (`LegalLinks`, `BlueskyConnect`) move to `TransSlots` when touched.
## Inertia SSR
@@ -707,7 +708,7 @@ rolls the switch back and toasts.
today's snapshot dated by the next UTC day still count).
- **Frontend zone.** `@/date`'s `getUserTimezone()` returns `auth.user.timezone`
(the `userTimezone` ref in `resources/js/preferences.ts`); "now" comes from
- `userNow()`, never the browser clock. Times shown next to display-zone cards go
+ `userNow()`, never the browser clock. `userNow()` is a wall clock in the user's zone, not an instant: to ask whether a UTC instant has passed (`date.hasPassed()`), compare instants with `dayjs()`, or a browser in another zone than the user's is off by the difference. Times shown next to display-zone cards go
through `useViewTimezone()`: the page's display zone where a picker exists
(publish list and calendar call `provideViewTimezone()`), the user zone
elsewhere.
@@ -1087,7 +1088,7 @@ an `enabled` flag or posts with several channels. Posts created together share
## Content limits
-- **Per account, not per platform.** Read the cap through `SocialAccount::maxContentLength()`. It is the platform's `Platform::maxContentLength()`, except an X account with long posts (`hasXLongPosts()`: a `Basic`, `Premium` or `PremiumPlus` subscription, or `verified_type=business`), which gets 25000. The tier lives in the account meta and is written by `SyncXSubscription`, called from `ConnectionVerifier` on connect and on the daily `social:check-connections`.
+- **Per account, not per platform.** Read the cap through `SocialAccount::maxContentLength()`. It is the platform's `Platform::maxContentLength()`, except an X account with long posts (`hasXLongPosts()`: a `Basic`, `Premium` or `PremiumPlus` subscription, or `verified_type=business`), which gets 25000. A post type may cap it lower: `ContentType::maxContentLengthFor($account, $platform, $type)` is the one cap save, publish, the preview and the writing assistant read (an X poll's question stays at 280, and so does a reply poll's through `ThreadReplies`). The tier lives in the account meta and is written by `SyncXSubscription`, called from `ConnectionVerifier` on connect and on the daily `social:check-connections`.
- `Post::CONTENT_MAX_LENGTH` (25000 characters of plain text) is the ceiling of any post, enforced by `PostContentFitsMaxLength`.
- `Platform::reservedLength()` counts what the network adds to the text: the Mastodon content warning (trimmed like `Str::trim`) counts toward the 500.
- `Platform::maxHashtags()` is 5 on Instagram (both platforms). It is a **save-time** rule (web, API, MCP), never a publish-time failure: a post stored with more still publishes. Repurpose captions are trimmed to the first 5 by `CaptionAdapter` through `Hashtags::keepFirst()`. Hashtags are counted by `App\Support\Hashtags`, mirrored by `resources/js/lib/hashtags.ts` and kept identical by `HashtagParityTest`.
@@ -1097,13 +1098,29 @@ an `enabled` flag or posts with several channels. Posts created together share
## Thread replies
- Bluesky, Mastodon and X (`App\Support\ThreadReplies`), up to 24 replies in `meta.thread_replies`. Each reply is measured against the **account's** limit (`SocialAccount::maxContentLength()`), so an X account with long posts gets 25000 per reply; pass the account to `ThreadReplies::violation()` / `PostPlatformMetaRules::requiredMetaViolation()` whenever it is known.
-- Each reply is `{text, media}` (a stored plain string is a text-only reply; `ThreadReplies::of()` normalizes both, `PostPlatformMetaRules::normalize()` stores objects). Its media belongs to that reply only, never to the root: it publishes as `ThreadReplies::replyContentType()` (X → `XPost`, Bluesky → `BlueskyPost`, Mastodon → `MastodonPost`), so it follows that type's media rules (`ThreadReplies::mediaErrors()`, at save and at publish), and a reply needs text or media. The frontend mirror is `THREAD_REPLY_CONTENT_TYPES`. Adding a network means one entry in each map plus a reply callback in its publisher.
+- Each reply is `{text, media}`, plus `poll` on an X reply that is a poll (see "X polls") (a stored plain string is a text-only reply; `ThreadReplies::of()` normalizes both, `PostPlatformMetaRules::normalize()` stores objects). Its media belongs to that reply only, never to the root: it publishes as `ThreadReplies::replyContentType()` (X → `XPost`, Bluesky → `BlueskyPost`, Mastodon → `MastodonPost`), so it follows that type's media rules (`ThreadReplies::mediaErrors()`, at save and at publish), and a reply needs text or media. The frontend mirror is `THREAD_REPLY_CONTENT_TYPES`. Adding a network means one entry in each map plus a reply callback in its publisher.
- Reply media rows are owned by the post like its root media. `SyncOwnedMedia` resolves them from the post's stored `meta.thread_replies` and writes the canonical items back, so write the target's meta **before** calling it; it never deletes a row a reply still uses. Every segment's checkpoint hash covers its media ids.
- In the composer each post of a thread shows its own media under it; the toolbar, paste, drop and the toolbar upload button add to the active post.
- X replies go through `POST /2/tweets` with `reply.in_reply_to_tweet_id` on the previous segment. X restricts API replies (February 2026) to posts whose author summoned the replier; replying to your own post is the case that stays allowed. Each reply is billed as a post.
- Each segment already live is checkpointed in `posts.error_context.thread_progress` (`App\Support\Social\ThreadProgress`), so a retry resumes instead of re-posting, and a resume keeps the root hash. `posts:retry` keeps the live segments.
- `posts.thread_reply_ids` lists the reply ids so `ImportExternalPosts` does not import TryPost's own replies as new posts.
+## X polls
+
+- A poll is its own content type, `ContentType::XPoll` (`x_poll`), with `meta.poll = {options, duration_minutes}` (owner decision November 2026). `App\Support\Social\XPoll` is the one home for its rules (constants, `limits()`, `options()` / `choices()`, `normalize()`, `violation()`, `optionsCountViolation()`, `choiceLengthViolation()`, `requiredViolation()`, `questionViolation()`, `payload()`, `result()`, `fromPublication()`); `PostPlatformMetaRules`, `PostMeta::forChannel()` / `PostMeta::merge()`, `PostCompositionValidator`, `ContentType::maxContentLengthFor()`, `ThreadReplies` and `XPublisher` call it, never a copy of the numbers or messages. X's `voting_status` values are `App\Enums\X\PollVotingStatus`.
+- 2–4 choices of 1–25 characters counted as X counts them (UTF-16 units, so an emoji like 🐧 counts two: `XPoll::choiceLength()`, mirrored by `pollChoiceLength()`; X refused a choice of 25 code points holding one), a duration of 5–10080 minutes, and a question (the post text) of at most 280 characters, even on an account with long posts. Blank choices are dropped and duplicates refused. `PostMeta::forChannel()` drops `poll` on any other type.
+- A poll carries no media. A poll with fewer than two choices, or without a question, is a draft that cannot be scheduled (the question error replaces the generic "content or media" one); `XPublisher` refuses it, and refuses stored media with `posts.errors.media_not_accepted`.
+- **Any post of a thread can be a poll, several in one thread** (owner decision November 2026: X allows a poll on a reply). The root is a poll through its content type (`x_poll`, `meta.poll`); a reply stays `XPost` and carries its poll in the reply itself: `meta.thread_replies.*` is `{text, media, poll}`, `poll` under the same rules as `meta.poll` (`PostPlatformMetaRules`), the reply text as its question (at most 280 characters even with long posts), no media (refused at every save by `ThreadReplies::pollMediaErrors()`). `ThreadReplies` holds the reply rules (`pollFormatViolation()` at every save, `violation()` before scheduling), calling `XPoll`, whose helpers read `poll.*` from a post's meta or a reply alike. Off X, `PostMeta::forChannel()` drops reply polls (`ThreadReplies::withoutPolls()`). `PublishesThreads` passes each reply's poll to the publisher and into its checkpoint hash (a reply without one keeps its old hash). In the composer the root keeps the Post | Poll picker; an active X reply turns into a poll with the toolbar's poll button (`ComposerEditorToolbar`, off with the media reason while the reply has media), and its poll editor (`XPollField` with `field-prefix` `thread_replies.{n}.` and its own test ids) shows while that reply is edited.
+- Attaching media through the API or MCP to a poll is refused by one guard, `AppendPostMedia::ensureAcceptsMedia()`: `execute()` always runs it, and the entry points that store or download a file first (`PostController::storeMedia`, `MediaAttacher::attachFromUrls`) call it before doing so.
+- **Cost rule (owner decision):** polls and their votes ride on requests X already makes. Never add a request, job or schedule for polls.
+ - Results are read by `XPublicationMetricsCollector` in the existing X metrics read (`GET /2/tweets/{id}`), on its usual schedule (about an hour after publishing, then at the ages in `SyncCadence::X_METRICS_DAYS`), into `analytics_publications.provider_metadata.poll`, without moving `updated_at`. A read without a poll leaves the stored one alone.
+ - When TryPost published reply polls, the same read becomes one `GET /2/tweets?ids={post},{replies with a poll}` (owner decision November 2026: still one request, though X bills each extra post it returns), and their results go to `provider_metadata.thread_polls`, a list of `{reply, ...result}` where `reply` is the reply's position from 0 (matched through `posts.thread_reply_ids`). Discovery excludes replies, so it never sees them; `UpsertAnalyticsPublication` merges `provider_metadata` key by key so a rediscovery keeps them.
+ - A poll made on x.com is found by `XPublicationCollector`'s existing discovery request, which writes the same `provider_metadata.poll`, and typed `PublicationContentType::Poll`, which `ContentType::fromPublication()` maps to `x_poll` for the importer and the insights type filter (a poll TryPost published is stored as `Poll` by `SyncTryPostPublication`). `provider_metadata.poll` is the one home of a poll's result; there is no column of its own.
+- Results are exposed as `publication.poll` and `publication.thread_polls` (read from `provider_metadata`) by `ReadPublicationAnalytics` (web, API, MCP) and shown by `PostPollResults.vue` in the Sent tab and post details, a reply's poll captioned with its post number (`posts.poll_results.thread_post`). The API and MCP post preview (`PostPreviewer`) shows the post's poll and each reply's. Because results are not read daily, it says "Final results" only when the stored `voting_status` is `closed`; an open poll whose end has passed says "Voting ended", and one still running says when it ends.
+- The duration defaults to 1440 minutes (one day, `XPoll::DEFAULT_DURATION`). The limits reach the composer through `Platform::publishConfig()` (`publishConfig.poll`, from `XPoll::limits()`), read from `platformConfigs[account.id]` by `XPollField.vue`, the X preview and the question cap; do not copy them into TypeScript. `resources/js/lib/xPoll.ts` keeps only pure helpers that take the limits as arguments; the poll types (`XPoll`, `XPollLimits`, `XPollDuration`) are in `resources/js/types/x.ts`. The composer's poll state, its limits, the type switch (`setGroupContentType`), Remove poll and the reply text limit live in `composables/composer/useComposerPoll.ts`; the media button's reason stays in `PostComposerDialog.vue`, and the medialess types (poll, Threads ghost post) with their reasons in `MEDIALESS_CONTENT_TYPE_REASONS` (`types/content-type.ts`, next to `CAPTIONLESS_CONTENT_TYPES`; `maxMediaCount()` is 0 for both on the server).
+- **The poll's media rules are X poll only** (owner decision November 2026): refusing media on a draft (`PostCompositionValidator`), refusing an attach (`AppendPostMedia::ensureAcceptsMedia()`), turning a card back into a post when the shared step opens (`watch(sharedStep)` in `PostComposerDialog.vue`) and leaving the type out of the repurpose picker all test `ContentType::XPoll`, never "a type that takes no media": a Threads ghost post keeps the behaviour it had before polls (its media is refused when it is scheduled or published).
+- A poll is never a repurpose destination: the repurpose requests refuse `x_poll` (`RepurposeRules`, `supportsVideo()`), and the repurpose picker (`ChannelConfigurator.vue`) leaves it out.
+
## Composer steps
- Step 1 is one shared editor. "Customize for each network" opens one card per network, in channel-list order, grouped by `platform`; each card starts as a copy of the shared text.
diff --git a/app/Actions/Ai/AssistPostContent.php b/app/Actions/Ai/AssistPostContent.php
index 3a176ec05..2418d3b94 100644
--- a/app/Actions/Ai/AssistPostContent.php
+++ b/app/Actions/Ai/AssistPostContent.php
@@ -6,6 +6,7 @@ namespace App\Actions\Ai;
use App\Ai\Agents\PostWritingAssistant;
use App\Enums\Ai\PostAssistantMode;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\SocialAccount;
use App\Models\User;
@@ -24,9 +25,10 @@ final class AssistPostContent
?string $previousContent,
?Platform $platform,
?SocialAccount $account = null,
+ ?ContentType $contentType = null,
): string {
$platform = $account->platform ?? $platform;
- $limit = $account?->maxContentLength() ?? $platform?->maxContentLength();
+ $limit = transform($platform, fn (Platform $platform): int => ContentType::maxContentLengthFor($account, $platform, $contentType));
$response = (new PostWritingAssistant($mode, $currentContent, $user->locale, $platform, $previousContent, $limit))
->prompt($mode->requiresPrompt() ? trim((string) $prompt) : 'Revise the existing caption as instructed.');
diff --git a/app/Actions/Analytics/ReadPublicationAnalytics.php b/app/Actions/Analytics/ReadPublicationAnalytics.php
index d8b85149b..594558bfa 100644
--- a/app/Actions/Analytics/ReadPublicationAnalytics.php
+++ b/app/Actions/Analytics/ReadPublicationAnalytics.php
@@ -184,6 +184,8 @@ class ReadPublicationAnalytics
'permalink' => $publication->permalink,
'excerpt' => $publication->excerpt,
'preview_metadata' => $publication->preview_metadata,
+ 'poll' => data_get($publication->provider_metadata, 'poll'),
+ 'thread_polls' => data_get($publication->provider_metadata, 'thread_polls', []),
'account_display_name' => $publication->account_display_name,
'account_username' => $publication->account_username,
'account_avatar_url' => $publication->socialAccount?->avatar_url ?? $publication->account_avatar_url,
diff --git a/app/Actions/Analytics/SyncTryPostPublication.php b/app/Actions/Analytics/SyncTryPostPublication.php
index d8d6b6aa9..840d65db0 100644
--- a/app/Actions/Analytics/SyncTryPostPublication.php
+++ b/app/Actions/Analytics/SyncTryPostPublication.php
@@ -59,6 +59,7 @@ class SyncTryPostPublication
ContentType::YouTubeShort => PublicationContentType::Short,
ContentType::TikTokVideo, ContentType::PinterestVideoPin => PublicationContentType::Video,
ContentType::TikTokPhoto, ContentType::PinterestCarousel => PublicationContentType::Carousel,
+ ContentType::XPoll => PublicationContentType::Poll,
default => null,
};
diff --git a/app/Actions/Analytics/UpsertAnalyticsPublication.php b/app/Actions/Analytics/UpsertAnalyticsPublication.php
index 06e30ea37..8323a1291 100644
--- a/app/Actions/Analytics/UpsertAnalyticsPublication.php
+++ b/app/Actions/Analytics/UpsertAnalyticsPublication.php
@@ -16,6 +16,7 @@ use App\Models\Post;
use App\Models\SocialAccount;
use DateTimeInterface;
use Illuminate\Database\UniqueConstraintViolationException;
+use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use LogicException;
@@ -23,6 +24,14 @@ class UpsertAnalyticsPublication
{
private const int EXCERPT_MAX_BYTES = 65535;
+ /**
+ * `provider_metadata` keys only the metrics read writes (the polls of X
+ * thread replies, which discovery never sees).
+ *
+ * @var list<string>
+ */
+ private const array METRICS_ONLY_PROVIDER_METADATA = ['thread_polls'];
+
public function __construct(private readonly ResolveAnalyticsAccountKey $accountKeys) {}
public function external(
@@ -125,7 +134,7 @@ class UpsertAnalyticsPublication
$current->fill([
'permalink' => $discovered->permalink ?? $current->permalink,
'preview_metadata' => $discovered->preview_metadata ?? $current->preview_metadata,
- 'provider_metadata' => $discovered->provider_metadata ?? $current->provider_metadata,
+ 'provider_metadata' => self::providerMetadataAfterDiscovery($current, $discovered->provider_metadata),
'provider_synced_at' => $discovered->provider_synced_at ?? $current->provider_synced_at,
'excerpt' => $discovered->excerpt ?? $current->excerpt,
'provider_published_at' => $discovered->provider_published_at ?? $current->provider_published_at,
@@ -297,7 +306,7 @@ class UpsertAnalyticsPublication
'permalink' => $permalink,
'excerpt' => $excerpt,
'preview_metadata' => $previewMetadata,
- 'provider_metadata' => $providerMetadata,
+ 'provider_metadata' => self::providerMetadataAfterDiscovery($publication, $providerMetadata),
'account_display_name' => $identity->accountDisplayName,
'account_username' => $identity->accountUsername,
'account_avatar_url' => $identity->accountAvatarUrl,
@@ -312,4 +321,22 @@ class UpsertAnalyticsPublication
return $publication->refresh();
});
}
+
+ /**
+ * The `provider_metadata` after a discovery reported `$discovered`: what it
+ * reports replaces what was stored, so a key it no longer reports goes, while
+ * the keys only the metrics read writes stay. A discovery that reported
+ * nothing (`null`, not an empty list) keeps it all.
+ *
+ * @param array<string, mixed>|null $discovered
+ * @return array<string, mixed>|null
+ */
+ private static function providerMetadataAfterDiscovery(AnalyticsPublication $publication, ?array $discovered): ?array
+ {
+ if (is_null($discovered)) {
+ return $publication->provider_metadata;
+ }
+
+ return [...$discovered, ...Arr::only($publication->provider_metadata ?? [], self::METRICS_ONLY_PROVIDER_METADATA)];
+ }
}
diff --git a/app/Actions/Analytics/WritePublicationDailySnapshot.php b/app/Actions/Analytics/WritePublicationDailySnapshot.php
index 3006640ab..35e8ee9c7 100644
--- a/app/Actions/Analytics/WritePublicationDailySnapshot.php
+++ b/app/Actions/Analytics/WritePublicationDailySnapshot.php
@@ -35,6 +35,9 @@ class WritePublicationDailySnapshot
bool $mayCreate,
): AnalyticsPublicationDailySnapshot {
return DB::transaction(function () use ($publication, $observation, $mayCreate): AnalyticsPublicationDailySnapshot {
+ $locked = filled($observation->providerMetadata)
+ ? AnalyticsPublication::query()->lockForUpdate()->find($publication->id)
+ : null;
$snapshot = AnalyticsPublicationDailySnapshot::query()
->where('publication_id', $publication->id)
->where('date', $observation->date->toDateString())
@@ -66,10 +69,31 @@ class WritePublicationDailySnapshot
]);
$snapshot->save();
+ if (filled($locked)) {
+ $this->mergeProviderMetadata($locked, $observation->providerMetadata);
+ }
+
return $snapshot->refresh();
});
}
+ /**
+ * Writes the keys the network reported over the publication's stored
+ * `provider_metadata`, on the row read again under the lock the transaction
+ * took first (before the snapshot, the order discovery locks in): the model
+ * was loaded before the network call, and a discovery may have written
+ * meanwhile. A key the observation does not carry is kept, and `updated_at`
+ * does not move.
+ *
+ * @param array<string, mixed> $providerMetadata
+ */
+ private function mergeProviderMetadata(AnalyticsPublication $current, array $providerMetadata): void
+ {
+ $current->withoutTimestamps(fn (): bool => $current->forceFill([
+ 'provider_metadata' => [...($current->provider_metadata ?? []), ...$providerMetadata],
+ ])->saveQuietly());
+ }
+
/**
* Same-day reads merge field by field; a lifetime count keeps its highest
* value so a partial read (one call refused) cannot undercut a fuller one.
diff --git a/app/Actions/Post/AppendPostMedia.php b/app/Actions/Post/AppendPostMedia.php
index 2b1b4f020..7ecbcf23e 100644
--- a/app/Actions/Post/AppendPostMedia.php
+++ b/app/Actions/Post/AppendPostMedia.php
@@ -22,6 +22,7 @@ class AppendPostMedia
* again from the new media. Changing an approved, scheduled post goes back
* through UpdatePost, so a member who needs approval sends it back for
* approval like any other edit, even when the approval landed just before.
+ * An X poll, which takes no media, is refused.
*
* @param list<array<string, mixed>> $items
*
@@ -30,6 +31,8 @@ class AppendPostMedia
public static function execute(Post $post, array $items, ?User $actor): void
{
PostApproval::locked($post, fn () => MediaCopyBatch::run(function (MediaCopyBatch $batch) use ($post, $items, $actor): void {
+ self::ensureAcceptsMedia($post);
+
$post->appendMedia($items, $batch);
if (PostStatusRules::blocksEditing($post)) {
@@ -45,4 +48,18 @@ class AppendPostMedia
}
}));
}
+
+ /**
+ * Refuses media on an X poll, which carries none. `execute()` always checks
+ * it; an entry point that stores or downloads a file first calls it before
+ * doing so.
+ *
+ * @throws ValidationException
+ */
+ public static function ensureAcceptsMedia(Post $post, string $field = 'media'): void
+ {
+ if ($post->content_type === ContentType::XPoll) {
+ throw ValidationException::withMessages([$field => trans('posts.errors.media_not_accepted')]);
+ }
+ }
}
diff --git a/app/Actions/Post/CreateChannelPost.php b/app/Actions/Post/CreateChannelPost.php
index 07af858a3..2e0c4990a 100644
--- a/app/Actions/Post/CreateChannelPost.php
+++ b/app/Actions/Post/CreateChannelPost.php
@@ -63,7 +63,7 @@ class CreateChannelPost
...$account->channelSnapshot(),
'content_type' => $destination['content_type'],
'publish_status' => PublishStatus::Pending,
- 'meta' => PostMeta::forChannel($account, $destination['meta'] ?? []),
+ 'meta' => PostMeta::forChannel($account, data_get($destination, 'meta') ?? [], contentType: data_get($destination, 'content_type')),
]);
SyncOwnedMedia::execute(
diff --git a/app/Actions/Post/ImportExternalPosts.php b/app/Actions/Post/ImportExternalPosts.php
index 0341309b7..18a4a337c 100644
--- a/app/Actions/Post/ImportExternalPosts.php
+++ b/app/Actions/Post/ImportExternalPosts.php
@@ -19,6 +19,7 @@ use App\Services\Social\ContentSanitizer;
use App\Support\PostHistoryRetention;
use App\Support\Social\PublishCheckpoint;
use App\Support\Social\ThreadProgress;
+use App\Support\Social\XPoll;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
@@ -326,6 +327,8 @@ class ImportExternalPosts
private static function createPost(SocialAccount $account, AnalyticsPublication $publication): Post
{
+ $contentType = ContentType::fromPublication($account->platform, $publication->content_type);
+
return Post::query()->forceCreate([
'workspace_id' => $account->workspace_id,
'post_group_id' => (string) Str::uuid7(),
@@ -338,11 +341,11 @@ class ImportExternalPosts
'social_account_id' => $account->id,
'platform' => $account->platform,
...$account->channelSnapshot(),
- 'content_type' => ContentType::fromPublication($account->platform, $publication->content_type),
+ 'content_type' => $contentType,
'publish_status' => PublishStatus::Published,
'platform_post_id' => $publication->remote_id,
'platform_url' => $publication->permalink,
- 'meta' => [],
+ 'meta' => $contentType === ContentType::XPoll ? ['poll' => XPoll::fromPublication($publication)] : [],
]);
}
}
diff --git a/app/Actions/Post/UpdatePost.php b/app/Actions/Post/UpdatePost.php
index 490b2f522..a02a82e5c 100644
--- a/app/Actions/Post/UpdatePost.php
+++ b/app/Actions/Post/UpdatePost.php
@@ -152,7 +152,7 @@ class UpdatePost
$queueSlot = $position === null && ! $keepsPending ? data_get($data, 'queue_slot') : null;
$meta = PostPlatformMetaRules::normalize(array_filter(
- array_merge($post->meta ?? [], data_get($data, 'meta') ?? []),
+ PostMeta::merge($post->meta ?? [], data_get($data, 'meta') ?? []),
fn (mixed $value): bool => $value !== null,
));
$scheduledAt = match (true) {
@@ -206,7 +206,7 @@ class UpdatePost
'schedule_mode' => $mode,
...PostApproval::transition($previousStatus, $storedStatus, $actor, $pending ? $position : null),
'content_type' => $destination['content_type'],
- 'meta' => PostMeta::forChannel($channel, $destination['meta'], $post->meta ?? []),
+ 'meta' => PostMeta::forChannel($channel, data_get($destination, 'meta'), $post->meta ?? [], data_get($destination, 'content_type')),
]);
SyncOwnedMedia::execute($post, $destination['media'], $batch);
diff --git a/app/Dto/Analytics/PublicationMetricObservation.php b/app/Dto/Analytics/PublicationMetricObservation.php
index 7975c3bc9..c120d3492 100644
--- a/app/Dto/Analytics/PublicationMetricObservation.php
+++ b/app/Dto/Analytics/PublicationMetricObservation.php
@@ -10,11 +10,13 @@ final readonly class PublicationMetricObservation
{
/**
* @param list<MetricValue> $metrics
+ * @param array<string, mixed>|null $providerMetadata Keys the network reported about the publication itself, merged into its `provider_metadata`
*/
public function __construct(
public CarbonImmutable $date,
public array $metrics,
public ?CarbonImmutable $providerObservedAt = null,
public ?CarbonImmutable $collectedAt = null,
+ public ?array $providerMetadata = null,
) {}
}
diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.php
index e68193aad..2605f844a 100644
--- a/app/Enums/PostPlatform/ContentType.php
+++ b/app/Enums/PostPlatform/ContentType.php
@@ -8,7 +8,10 @@ use App\Dto\MediaItem;
use App\Enums\Analytics\PublicationContentType;
use App\Enums\Media\Type as MediaType;
use App\Enums\SocialAccount\Platform as SocialPlatform;
+use App\Models\SocialAccount;
+use App\Support\Social\XPoll;
use App\Support\ThreadReplies;
+use Illuminate\Support\Str;
enum ContentType: string
{
@@ -38,6 +41,7 @@ enum ContentType: string
// X (Twitter)
case XPost = 'x_post';
+ case XPoll = 'x_poll';
// Threads
case ThreadsPost = 'threads_post';
@@ -92,6 +96,7 @@ enum ContentType: string
self::TikTokPhoto => 'Photo carousel',
self::YouTubeShort => 'Short',
self::XPost => 'Post',
+ self::XPoll => 'Poll',
self::ThreadsPost => 'Thread',
self::ThreadsGhostPost => 'Ghost post',
self::PinterestPin => 'Pin',
@@ -107,7 +112,12 @@ enum ContentType: string
public function description(): string
{
- return (string) trans("posts.content_types.{$this->value}.description");
+ $replacements = match ($this) {
+ self::XPoll => ['min' => XPoll::MIN_OPTIONS, 'max' => XPoll::MAX_OPTIONS],
+ default => [],
+ };
+
+ return (string) trans("posts.content_types.{$this->value}.description", $replacements);
}
public function platform(): SocialPlatform
@@ -119,7 +129,7 @@ enum ContentType: string
self::FacebookPost, self::FacebookReel, self::FacebookStory => SocialPlatform::Facebook,
self::TikTokVideo, self::TikTokPhoto => SocialPlatform::TikTok,
self::YouTubeShort => SocialPlatform::YouTube,
- self::XPost => SocialPlatform::X,
+ self::XPost, self::XPoll => SocialPlatform::X,
self::ThreadsPost, self::ThreadsGhostPost => SocialPlatform::Threads,
self::PinterestPin, self::PinterestVideoPin, self::PinterestCarousel => SocialPlatform::Pinterest,
self::BlueskyPost => SocialPlatform::Bluesky,
@@ -176,6 +186,28 @@ enum ContentType: string
};
}
+ /**
+ * The character cap of a post: the account's own limit
+ * (`SocialAccount::maxContentLength()`, an X account with long posts), else
+ * the platform's, capped by the post type when the type belongs to that
+ * platform (an X poll's question stays at the poll's cap even on an account
+ * with long posts). The one formula save, publish, preview and the AI
+ * assistant measure against.
+ */
+ public static function maxContentLengthFor(?SocialAccount $account, SocialPlatform $platform, ?self $type = null): int
+ {
+ $limit = $account?->maxContentLength() ?? $platform->maxContentLength();
+
+ if (blank($type) || ! $type->isCompatibleWith($platform)) {
+ return $limit;
+ }
+
+ return match ($type) {
+ self::XPoll => min($limit, XPoll::QUESTION_MAX_LENGTH),
+ default => $limit,
+ };
+ }
+
public function maxMediaCount(): int
{
return match ($this) {
@@ -188,6 +220,7 @@ enum ContentType: string
self::TikTokPhoto => 35,
self::YouTubeShort => 1,
self::XPost => 4,
+ self::XPoll => 0,
self::ThreadsPost => 10,
self::ThreadsGhostPost => 0,
self::PinterestPin, self::PinterestVideoPin => 1,
@@ -446,7 +479,7 @@ enum ContentType: string
self::InstagramFeed => ['3:4', '4:5', '1:1', '1.91:1'],
self::InstagramStory, self::InstagramReel, self::FacebookStory, self::FacebookReel,
self::TikTokVideo, self::YouTubeShort => ['9:16'],
- self::XPost => ['1:1', '4:3', '16:9', '2:1'],
+ self::XPost, self::XPoll => ['1:1', '4:3', '16:9', '2:1'],
self::TikTokPhoto => ['4:3', '16:9', '9:16', '1:1'],
self::FacebookPost, self::LinkedInPost, self::LinkedInPagePost => ['1:1', '1.91:1'],
self::PinterestPin, self::PinterestCarousel => ['2:3', '1:1'],
@@ -704,6 +737,7 @@ enum ContentType: string
self::TikTokPhoto => false,
self::YouTubeShort => true,
self::XPost => true,
+ self::XPoll => false,
self::ThreadsPost => true,
self::ThreadsGhostPost => false,
self::PinterestVideoPin => true,
@@ -725,6 +759,7 @@ enum ContentType: string
self::TikTokPhoto => true,
self::YouTubeShort => false,
self::ThreadsGhostPost => false,
+ self::XPoll => false,
self::PinterestVideoPin => false,
default => true,
};
@@ -777,7 +812,7 @@ enum ContentType: string
{
return match ($this) {
self::LinkedInPost, self::LinkedInPagePost => false,
- self::XPost => false,
+ self::XPost, self::XPoll => false,
self::ThreadsPost, self::ThreadsGhostPost => false,
self::BlueskyPost => false,
self::MastodonPost => false,
@@ -807,6 +842,23 @@ enum ContentType: string
};
}
+ /**
+ * How many characters `$text`, plus what the network adds to it
+ * (`$reserved`), goes over `maxContentLengthFor()`; 0 when it fits.
+ */
+ public static function overflowFor(?SocialAccount $account, SocialPlatform $platform, ?self $type, string $text, int $reserved = 0): int
+ {
+ return max(0, Str::length($text) + $reserved - self::maxContentLengthFor($account, $platform, $type));
+ }
+
+ /**
+ * Whether a post of this type can go to `$platform` (`compatiblePlatforms()`).
+ */
+ public function isCompatibleWith(SocialPlatform $platform): bool
+ {
+ return collect($this->compatiblePlatforms())->contains($platform);
+ }
+
/**
* Get all content types for a specific platform. Treats InstagramFacebook
* as an alias for Instagram so both flavors get the same content types.
@@ -884,6 +936,18 @@ enum ContentType: string
};
}
+ /**
+ * A content type given as the enum or its value; anything else is null.
+ */
+ public static function resolve(mixed $contentType): ?self
+ {
+ return match (true) {
+ $contentType instanceof self => $contentType,
+ is_string($contentType) => self::tryFrom($contentType),
+ default => null,
+ };
+ }
+
/**
* The content type an imported publication is shown as. One place for every
* platform and publication type pair.
@@ -910,6 +974,10 @@ enum ContentType: string
PublicationContentType::Carousel => self::PinterestCarousel,
default => self::PinterestPin,
},
+ SocialPlatform::X => match ($type) {
+ PublicationContentType::Poll => self::XPoll,
+ default => self::XPost,
+ },
default => self::defaultFor($platform),
};
}
diff --git a/app/Enums/SocialAccount/Platform.php b/app/Enums/SocialAccount/Platform.php
index 20e3ff754..2b08aa2ec 100644
--- a/app/Enums/SocialAccount/Platform.php
+++ b/app/Enums/SocialAccount/Platform.php
@@ -8,6 +8,7 @@ use App\Enums\Media\Type as MediaType;
use App\Enums\TikTok\PrivacyLevel;
use App\Enums\YouTube\Category;
use App\Support\Hashtags;
+use App\Support\Social\XPoll;
use Illuminate\Support\Str;
enum Platform: string
@@ -245,17 +246,6 @@ enum Platform: string
};
}
- /**
- * Number of characters by which the given content exceeds this platform's
- * hard cap. Returns 0 when it fits. Single source of truth for content-
- * length checks — used both at schedule-validation time and at publish
- * time itself so the two paths can never drift apart.
- */
- public function contentOverflow(string $content, int $reserved = 0): int
- {
- return max(0, mb_strlen($content) + $reserved - $this->maxContentLength());
- }
-
/**
* Characters a network counts against the post limit besides its text:
* Mastodon counts the content warning.
@@ -593,6 +583,9 @@ enum Platform: string
'categoryOptions' => Category::options(),
'defaultCategoryId' => Category::DEFAULT->value,
],
+ self::X => [
+ 'poll' => XPoll::limits(),
+ ],
default => [],
};
}
diff --git a/app/Enums/X/PollVotingStatus.php b/app/Enums/X/PollVotingStatus.php
new file mode 100644
index 000000000..89e5fc642
--- /dev/null
+++ b/app/Enums/X/PollVotingStatus.php
@@ -0,0 +1,14 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Enums\X;
+
+/**
+ * The poll `voting_status` values X reports; anything else is stored as unknown (null).
+ */
+enum PollVotingStatus: string
+{
+ case Open = 'open';
+ case Closed = 'closed';
+}
diff --git a/app/Http/Controllers/Api/PostController.php b/app/Http/Controllers/Api/PostController.php
index a08883cd5..f98ff4efb 100644
--- a/app/Http/Controllers/Api/PostController.php
+++ b/app/Http/Controllers/Api/PostController.php
@@ -152,6 +152,8 @@ class PostController extends Controller
{
$file = $request->file('media');
+ AppendPostMedia::ensureAcceptsMedia($post);
+
if ($violation = PostMediaRequestRules::typeViolation($post, MediaType::fromMime((string) $file->getMimeType()))) {
throw ValidationException::withMessages(['media' => $violation]);
}
diff --git a/app/Http/Controllers/App/PostAiAssistantController.php b/app/Http/Controllers/App/PostAiAssistantController.php
index dc116082a..a6b52ae37 100644
--- a/app/Http/Controllers/App/PostAiAssistantController.php
+++ b/app/Http/Controllers/App/PostAiAssistantController.php
@@ -7,6 +7,7 @@ namespace App\Http\Controllers\App;
use App\Actions\Ai\AssistPostContent;
use App\Enums\Ai\PostAssistantMode;
use App\Enums\PostHog\AiEvent;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Http\Requests\App\Ai\AssistPostContentRequest;
use App\Jobs\PostHog\CaptureAccountEvent;
@@ -42,6 +43,7 @@ class PostAiAssistantController extends Controller
prompt: $request->input('prompt'),
previousContent: $request->input('previous_content'),
platform: $request->enum('platform', Platform::class),
+ contentType: $request->enum('content_type', ContentType::class),
account: $request->filled('social_account_id')
? $workspace->socialAccounts()->find($request->input('social_account_id'))
: null,
diff --git a/app/Http/Requests/App/Ai/AssistPostContentRequest.php b/app/Http/Requests/App/Ai/AssistPostContentRequest.php
index ac22f2487..128763ee0 100644
--- a/app/Http/Requests/App/Ai/AssistPostContentRequest.php
+++ b/app/Http/Requests/App/Ai/AssistPostContentRequest.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Http\Requests\App\Ai;
use App\Enums\Ai\PostAssistantMode;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Rules\PostContentFitsMaxLength;
use App\Rules\PromptHasMinimumWords;
@@ -43,6 +44,7 @@ class AssistPostContentRequest extends FormRequest
],
'previous_content' => ['nullable', 'string', new PostContentFitsMaxLength],
'platform' => ['nullable', Rule::enum(Platform::class)],
+ 'content_type' => ['nullable', Rule::enum(ContentType::class)],
'social_account_id' => [
'nullable',
'uuid',
diff --git a/app/Http/Requests/App/Post/UpdatePostRequest.php b/app/Http/Requests/App/Post/UpdatePostRequest.php
index cf71492df..757400313 100644
--- a/app/Http/Requests/App/Post/UpdatePostRequest.php
+++ b/app/Http/Requests/App/Post/UpdatePostRequest.php
@@ -11,6 +11,7 @@ use App\Rules\ContentTypeCompatibleWithMedia;
use App\Rules\ContentTypeMatchesPostChannel;
use App\Rules\PostContentFitsMaxLength;
use App\Support\PostMediaRules;
+use App\Support\PostMeta;
use App\Support\PostPlatformMetaRules;
use App\Support\PostStatusRules;
use Illuminate\Foundation\Http\FormRequest;
@@ -120,12 +121,13 @@ class UpdatePostRequest extends FormRequest
}
/**
- * The meta the save would store: the submitted keys over the stored ones.
+ * The meta the save would store: the submitted keys over the stored ones,
+ * merged as `UpdatePost` merges them (`PostMeta::merge()`).
*
* @return array<string, mixed>
*/
private function effectiveMeta(): array
{
- return [...($this->route('post')->meta ?? []), ...(array) $this->input('meta', [])];
+ return PostMeta::merge($this->route('post')->meta ?? [], (array) $this->input('meta', []));
}
}
diff --git a/app/Models/SocialAccount.php b/app/Models/SocialAccount.php
index c6923ee8f..d5a9bca1f 100644
--- a/app/Models/SocialAccount.php
+++ b/app/Models/SocialAccount.php
@@ -131,11 +131,6 @@ class SocialAccount extends Model
return $this->hasXLongPosts() ? self::X_LONG_POST_LENGTH : $this->platform->maxContentLength();
}
- public function contentOverflow(string $content, int $reserved = 0): int
- {
- return max(0, mb_strlen($content) + $reserved - $this->maxContentLength());
- }
-
/**
* Persist a freshly authorized identity.
*
diff --git a/app/Rules/ContentFitsPlatformLimits.php b/app/Rules/ContentFitsPlatformLimits.php
index 31c4422c4..ed66583e1 100644
--- a/app/Rules/ContentFitsPlatformLimits.php
+++ b/app/Rules/ContentFitsPlatformLimits.php
@@ -18,7 +18,9 @@ use Illuminate\Translation\PotentiallyTranslatedString;
* `maxContentLength()` is exceeded by the submitted text. Pre-resolve the social
* accounts (or bare platforms) the post is bound to and pass them in; an account
* is measured against its own limit (an X account with long posts), a platform
- * against the platform's. Keeps the rule decoupled from the FormRequest payload.
+ * against the platform's, each capped by the post type
+ * (`ContentType::maxContentLengthFor()`). Keeps the rule decoupled from the
+ * FormRequest payload.
*
* Each platform is measured against its own sanitized content, matching what the
* publisher will actually send: the editor stores HTML, and per-platform rules
@@ -44,9 +46,11 @@ class ContentFitsPlatformLimits implements ValidationRule
$reported = [];
foreach ($this->targets as $targetKey => $target) {
- $platform = $target instanceof SocialAccount ? $target->platform : $target;
+ $account = $target instanceof SocialAccount ? $target : null;
+ $platform = $account?->platform ?? $target;
+ $contentType = ContentType::resolve(data_get($this->contentTypes, $targetKey));
- if (! $platform instanceof Platform || ContentType::tryFrom((string) data_get($this->contentTypes, $targetKey))?->isCaptionless()) {
+ if (! $platform instanceof Platform || $contentType?->isCaptionless()) {
continue;
}
@@ -60,8 +64,7 @@ class ContentFitsPlatformLimits implements ValidationRule
]));
}
- $measure = $target instanceof SocialAccount ? $target : $platform;
- $limit = $measure->maxContentLength();
+ $limit = ContentType::maxContentLengthFor($account, $platform, $contentType);
$reserved = $platform->reservedLength(data_get($this->meta, $targetKey));
$key = "{$platform->value}:{$limit}:{$reserved}";
@@ -69,7 +72,7 @@ class ContentFitsPlatformLimits implements ValidationRule
continue;
}
- $over = $measure->contentOverflow($display, $reserved);
+ $over = ContentType::overflowFor($account, $platform, $contentType, $display, $reserved);
if ($over === 0) {
continue;
diff --git a/app/Rules/ContentTypeCompatibleWithMedia.php b/app/Rules/ContentTypeCompatibleWithMedia.php
index 7ca74c08f..d60daaef7 100644
--- a/app/Rules/ContentTypeCompatibleWithMedia.php
+++ b/app/Rules/ContentTypeCompatibleWithMedia.php
@@ -144,6 +144,14 @@ class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRule
$media = $this->media();
+ if ($contentType === ContentType::XPoll) {
+ if ($media !== []) {
+ $fail(trans('posts.errors.media_not_accepted'));
+ }
+
+ return;
+ }
+
if ($contentType->maxMediaCount() === 0) {
if ($media !== []) {
$fail(trans('posts.form.warnings.text_only'));
diff --git a/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php
index f1708f07f..a11ade5e1 100644
--- a/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php
+++ b/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php
@@ -32,14 +32,17 @@ abstract class AbstractPublicationMetricsCollector extends AbstractApiPublicatio
return $account;
}
- /** @param list<MetricValue> $metrics */
- protected function observation(CarbonImmutable $date, array $metrics): PublicationMetricObservation
+ /**
+ * @param list<MetricValue> $metrics
+ * @param array<string, mixed>|null $providerMetadata
+ */
+ protected function observation(CarbonImmutable $date, array $metrics, ?array $providerMetadata = null): PublicationMetricObservation
{
if ($metrics === []) {
throw AnalyticsCollectionException::malformed('Publication metrics response contained no supported measurements.');
}
- return new PublicationMetricObservation($date, $metrics, collectedAt: CarbonImmutable::now('UTC'));
+ return new PublicationMetricObservation($date, $metrics, collectedAt: CarbonImmutable::now('UTC'), providerMetadata: $providerMetadata);
}
protected function count(
diff --git a/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php
index 974c5d373..f0822ec6d 100644
--- a/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php
+++ b/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php
@@ -8,7 +8,11 @@ use App\Dto\Analytics\PublicationMetricObservation;
use App\Enums\Analytics\MetricKey;
use App\Exceptions\Analytics\AnalyticsCollectionException;
use App\Models\AnalyticsPublication;
+use App\Models\SocialAccount;
+use App\Support\Social\XPoll;
+use App\Support\ThreadReplies;
use Carbon\CarbonImmutable;
+use Illuminate\Support\Arr;
class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector
{
@@ -22,11 +26,7 @@ class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector
$fields[] = 'non_public_metrics';
}
- $response = $this->get($account,
- rtrim((string) config('trypost.platforms.x.api'), '/')."/tweets/{$publication->remote_id}",
- ['tweet.fields' => implode(',', $fields)],
- );
- $tweet = $response->json('data');
+ [$tweet, $poll, $threadPolls] = $this->read($account, $publication, $fields);
if (! is_array($tweet)) {
throw AnalyticsCollectionException::malformed('X post response lacks data.');
@@ -43,6 +43,103 @@ class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector
$this->count(MetricKey::Quotes, $public, 'quote_count'),
$this->count(MetricKey::Bookmarks, $public, 'bookmark_count'),
$this->count(MetricKey::LinkClicks, $private, 'url_link_clicks'),
- ])));
+ ])), Arr::whereNotNull([
+ 'poll' => transform($poll, XPoll::result(...)),
+ 'thread_polls' => filled($threadPolls) ? $threadPolls : null,
+ ]) ?: null);
+ }
+
+ /**
+ * The post's tweet, its poll and its reply polls: a post whose thread has
+ * no poll is read alone, otherwise with its reply polls in one lookup.
+ *
+ * @param list<string> $fields
+ * @return array{0: mixed, 1: mixed, 2: list<array<string, mixed>>}
+ */
+ private function read(SocialAccount $account, AnalyticsPublication $publication, array $fields): array
+ {
+ $replyPolls = $this->replyPollTweetIds($publication);
+
+ if (blank($replyPolls)) {
+ return $this->readPost($account, $publication->remote_id, $fields);
+ }
+
+ return $this->readThread($account, $publication->remote_id, $replyPolls, $fields);
+ }
+
+ /**
+ * One post: its tweet and its poll.
+ *
+ * @param list<string> $fields
+ * @return array{0: mixed, 1: mixed, 2: list<array<string, mixed>>}
+ */
+ private function readPost(SocialAccount $account, string $id, array $fields): array
+ {
+ $response = $this->get($account, config('trypost.platforms.x.api')."/tweets/{$id}", $this->lookupParameters($fields));
+
+ return [$response->json('data'), $response->json('includes.polls.0'), []];
+ }
+
+ /**
+ * The post and its reply polls in one lookup: the post's tweet and poll,
+ * and each reply poll's result with its reply position.
+ *
+ * @param array<int, string> $replyPolls tweet ids keyed by reply position
+ * @param list<string> $fields
+ * @return array{0: mixed, 1: mixed, 2: list<array<string, mixed>>}
+ */
+ private function readThread(SocialAccount $account, string $id, array $replyPolls, array $fields): array
+ {
+ $response = $this->get($account, config('trypost.platforms.x.api').'/tweets', [
+ ...$this->lookupParameters([...$fields, 'attachments']),
+ 'ids' => Arr::join([$id, ...$replyPolls], ','),
+ ]);
+ $tweets = $response->collect('data')->keyBy('id');
+ $polls = $response->collect('includes.polls')->keyBy('id');
+ $pollOf = fn (mixed $tweet): mixed => $polls->get((string) data_get($tweet, 'attachments.poll_ids.0'));
+ $threadPolls = collect($replyPolls)
+ ->map(fn (string $replyId, int $reply): ?array => transform(
+ $pollOf($tweets->get($replyId)),
+ fn (array $poll): array => ['reply' => $reply, ...XPoll::result($poll)],
+ ))
+ ->filter()
+ ->values()
+ ->all();
+
+ return [$tweets->get($id), $pollOf($tweets->get($id)), $threadPolls];
+ }
+
+ /**
+ * @param list<string> $fields
+ * @return array<string, string>
+ */
+ private function lookupParameters(array $fields): array
+ {
+ return [
+ 'tweet.fields' => Arr::join($fields, ','),
+ 'expansions' => 'attachments.poll_ids',
+ 'poll.fields' => XPoll::LOOKUP_FIELDS,
+ ];
+ }
+
+ /**
+ * The tweet ids of the thread replies TryPost published with a poll, keyed by
+ * reply position, so their votes come in the same lookup as the post's.
+ *
+ * @return array<int, string>
+ */
+ private function replyPollTweetIds(AnalyticsPublication $publication): array
+ {
+ if (blank($publication->post_id)) {
+ return [];
+ }
+
+ $post = $publication->post()->first(['id', 'meta', 'thread_reply_ids']);
+ $replyIds = (array) $post?->thread_reply_ids;
+
+ return collect(ThreadReplies::of($post?->meta))
+ ->filter(fn (array $reply, int $index): bool => ThreadReplies::hasPoll($reply) && is_string(data_get($replyIds, $index)))
+ ->map(fn (array $reply, int $index): string => (string) data_get($replyIds, $index))
+ ->all();
}
}
diff --git a/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php
index 186f131b3..b3d4c898a 100644
--- a/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php
+++ b/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php
@@ -8,7 +8,10 @@ use App\Dto\Analytics\DiscoveredPublication;
use App\Dto\Analytics\PublicationPage;
use App\Enums\Analytics\PublicationContentType;
use App\Models\SocialAccount;
+use App\Support\Social\XPoll;
use Carbon\CarbonImmutable;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Collection;
class XPublicationCollector extends AbstractPublicationHistoryCollector
{
@@ -29,10 +32,12 @@ class XPublicationCollector extends AbstractPublicationHistoryCollector
'pagination_token' => $cursor,
'exclude' => 'retweets,replies',
'tweet.fields' => 'created_at,attachments,note_tweet,referenced_tweets',
- 'expansions' => 'attachments.media_keys',
+ 'expansions' => 'attachments.media_keys,attachments.poll_ids',
'media.fields' => 'media_key,type,preview_image_url,url,variants',
+ 'poll.fields' => XPoll::LOOKUP_FIELDS,
],
);
+ $polls = $response->collect('includes.polls')->keyBy('id');
$media = collect((array) $response->json('includes.media', []))->keyBy('media_key');
$publications = [];
$crossedCutoff = false;
@@ -70,23 +75,19 @@ class XPublicationCollector extends AbstractPublicationHistoryCollector
fn (array $item): bool => filled(data_get($item, 'preview_image_url')) || filled(data_get($item, 'url')),
);
+ $poll = transform($polls->get((string) data_get($row, 'attachments.poll_ids.0')), XPoll::result(...));
+
$publications[] = new DiscoveredPublication(
providerPostId: $postId,
publishedAt: $publishedAt,
- contentType: $this->contentType($types->all(), $attachedMedia->count()),
+ contentType: $this->contentType($types->all(), $attachedMedia->count(), filled($poll)),
providerContentType: $types->implode(','),
permalink: filled($account->username) ? "https://x.com/{$account->username}/status/{$postId}" : null,
excerpt: data_get($row, 'note_tweet.text') ?: data_get($row, 'text'),
previewMetadata: is_array($preview)
? ['thumbnail_url' => data_get($preview, 'preview_image_url') ?: data_get($preview, 'url')]
: null,
- providerMetadata: $attachedMedia->isEmpty() ? null : ['media' => $attachedMedia
- ->map(fn (array $item): array => array_filter([
- 'type' => data_get($item, 'type'),
- 'url' => data_get($item, 'url'),
- 'variants' => data_get($item, 'variants'),
- ], fn (mixed $value): bool => $value !== null))
- ->all()],
+ providerMetadata: $this->providerMetadata($attachedMedia, $poll),
);
}
@@ -102,9 +103,30 @@ class XPublicationCollector extends AbstractPublicationHistoryCollector
);
}
+ /**
+ * What discovery keeps of a post: its media and its poll's result.
+ *
+ * @param Collection<int, array<string, mixed>> $media
+ * @param array<string, mixed>|null $poll
+ * @return array<string, mixed>|null
+ */
+ private function providerMetadata(Collection $media, ?array $poll): ?array
+ {
+ $metadata = collect([
+ 'media' => $media->map(fn (array $item): array => Arr::whereNotNull(Arr::only($item, ['type', 'url', 'variants'])))->all(),
+ 'poll' => $poll,
+ ])->filter(fn (mixed $value): bool => filled($value));
+
+ return $metadata->isNotEmpty() ? $metadata->all() : null;
+ }
+
/** @param list<mixed> $types */
- private function contentType(array $types, int $mediaCount): PublicationContentType
+ private function contentType(array $types, int $mediaCount, bool $hasPoll): PublicationContentType
{
+ if ($hasPoll) {
+ return PublicationContentType::Poll;
+ }
+
if (in_array('video', $types, true) || in_array('animated_gif', $types, true)) {
return PublicationContentType::Video;
}
diff --git a/app/Services/Post/MediaAttacher.php b/app/Services/Post/MediaAttacher.php
index f9d4eb772..1b8d79e6e 100644
--- a/app/Services/Post/MediaAttacher.php
+++ b/app/Services/Post/MediaAttacher.php
@@ -14,6 +14,7 @@ use App\Models\Post;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Media\RemoteMediaImporter;
+use Illuminate\Validation\ValidationException;
/**
* Downloads public URLs as temporary uploads and attaches them as media the
@@ -36,9 +37,13 @@ class MediaAttacher
/**
* @param array<int, array{url: string, alt?: ?string, meta?: ?array<string, mixed>}> $urls
* @return array{attached: array<int, array<string, mixed>>, failed: array<int, string>, failures: array<int, array{url: string, reason: string, message: string}>}
+ *
+ * @throws ValidationException
*/
public function attachFromUrls(Post $post, array $urls, ?User $actor = null): array
{
+ AppendPostMedia::ensureAcceptsMedia($post, 'urls');
+
$attached = [];
$failed = [];
$failures = [];
diff --git a/app/Services/Post/PostPreviewer.php b/app/Services/Post/PostPreviewer.php
index 82455a45f..4f57bdc87 100644
--- a/app/Services/Post/PostPreviewer.php
+++ b/app/Services/Post/PostPreviewer.php
@@ -4,9 +4,11 @@ declare(strict_types=1);
namespace App\Services\Post;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
use App\Services\Social\ContentSanitizer;
+use App\Support\Social\XPoll;
use App\Support\ThreadReplies;
use App\Support\YouTubeDescription;
use App\Support\YouTubeMetadata;
@@ -37,7 +39,8 @@ class PostPreviewer
* title?: string,
* description?: string,
* description_length_bytes?: int,
- * thread_replies?: list<array{text: string, media: list<array<string, mixed>>}>
+ * poll?: array{options: list<string>, duration_minutes: int},
+ * thread_replies?: list<array{text: string, media: list<array<string, mixed>>, poll?: array{options: list<string>, duration_minutes: int}}>
* }
*/
public function forPost(Post $post): array
@@ -70,7 +73,7 @@ class PostPreviewer
'content_type' => $post->content_type?->value,
'sanitized_content' => $sanitized,
'sanitized_length' => mb_strlen($sanitized),
- 'max_content_length' => $post->socialAccount?->maxContentLength() ?? $platform->maxContentLength(),
+ 'max_content_length' => ContentType::maxContentLengthFor($post->socialAccount, $platform, $post->content_type),
'truncated' => mb_strlen($sanitized) < mb_strlen($original),
];
@@ -83,10 +86,15 @@ class PostPreviewer
$replies = ThreadReplies::supports($platform) ? ThreadReplies::of($post->meta) : [];
+ if ($post->content_type === ContentType::XPoll) {
+ $preview['poll'] = XPoll::payload($post->meta);
+ }
+
if ($replies !== []) {
$preview['thread_replies'] = array_map(fn (array $reply): array => [
'text' => $this->sanitizer->sanitize($reply['text'], $platform),
'media' => $reply['media'],
+ ...(ThreadReplies::hasPoll($reply) ? ['poll' => XPoll::payload($reply)] : []),
], $replies);
}
diff --git a/app/Services/Social/Concerns/HasSocialHttpClient.php b/app/Services/Social/Concerns/HasSocialHttpClient.php
index 0f079a672..a933f8dbf 100644
--- a/app/Services/Social/Concerns/HasSocialHttpClient.php
+++ b/app/Services/Social/Concerns/HasSocialHttpClient.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Services\Social\Concerns;
+use App\Enums\PostPlatform\ContentType;
use App\Exceptions\Social\ContentLimitException;
use App\Models\Post;
use App\Services\Social\ContentSanitizer;
@@ -11,6 +12,7 @@ use App\Services\Social\TokenRedactor;
use App\Support\ThreadReplies;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Str;
trait HasSocialHttpClient
{
@@ -39,17 +41,13 @@ trait HasSocialHttpClient
throw new ContentLimitException($post->platform, $threadViolation[1]);
}
- $reserved = $post->platform->reservedLength($post->meta);
- $overflow = $post->socialAccount?->contentOverflow($content, $reserved) ?? $post->platform->contentOverflow($content, $reserved);
+ $maxLength = ContentType::maxContentLengthFor($post->socialAccount, $post->platform, $post->content_type);
+ $contentLength = Str::length($content) + $post->platform->reservedLength($post->meta);
- if ($overflow === 0) {
+ if ($contentLength <= $maxLength) {
return;
}
- $maxLength = $post->socialAccount?->maxContentLength() ?? $post->platform->maxContentLength();
-
- $contentLength = mb_strlen($content) + $reserved;
-
throw ContentLimitException::exceeds($post->platform, $maxLength, $contentLength);
}
diff --git a/app/Services/Social/Concerns/PublishesThreads.php b/app/Services/Social/Concerns/PublishesThreads.php
index f8812cb2e..c2d3d70da 100644
--- a/app/Services/Social/Concerns/PublishesThreads.php
+++ b/app/Services/Social/Concerns/PublishesThreads.php
@@ -21,7 +21,7 @@ trait PublishesThreads
* part (ThreadProgress::failureMessage()).
*
* @param callable(): array{id: string, url?: ?string, uri?: string, cid?: string} $postRoot
- * @param callable(string, Collection<int, MediaItem>, array<string, mixed>, array<string, mixed>): array{id: string, url?: ?string, uri?: string, cid?: string} $postReply
+ * @param callable(string, Collection<int, MediaItem>, array<string, mixed>, array<string, mixed>, ?array<string, mixed>): array{id: string, url?: ?string, uri?: string, cid?: string} $postReply the last argument is the reply's poll (X only)
* @param (callable(array<string, mixed>): void)|null $afterThread
* @return array{id: string, url: ?string, thread_reply_ids?: list<string>}
*/
@@ -31,12 +31,13 @@ trait PublishesThreads
fn (array $reply): array => [
'text' => app(ContentSanitizer::class)->sanitize($reply['text'], $post->platform),
'media' => ThreadReplies::mediaItems($reply),
+ 'poll' => data_get($reply, 'poll'),
],
ThreadReplies::supports($post->platform) ? ThreadReplies::of($post->meta) : [],
);
$hashes = [
ThreadProgress::rootHash($post->error_context) ?? $rootHash,
- ...array_map(fn (array $reply): string => ThreadProgress::hash($reply['text'], $reply['media']->map(fn (MediaItem $item): string => $item->id)->all()), $replies),
+ ...array_map(fn (array $reply): string => ThreadProgress::hash($reply['text'], $reply['media']->map(fn (MediaItem $item): string => $item->id)->all(), $reply['poll']), $replies),
];
$posted = ThreadProgress::resumable($post->error_context, $hashes);
@@ -55,7 +56,7 @@ trait PublishesThreads
continue;
}
- $posted[] = self::threadSegment($hashes[$position], $postReply($reply['text'], $reply['media'], $posted[$position - 1], $posted[0]));
+ $posted[] = self::threadSegment($hashes[$position], $postReply($reply['text'], $reply['media'], $posted[$position - 1], $posted[0], $reply['poll']));
ThreadProgress::remember($post, $posted);
}
diff --git a/app/Services/Social/XPublisher.php b/app/Services/Social/XPublisher.php
index a2d5d4d60..5a0b0c80b 100644
--- a/app/Services/Social/XPublisher.php
+++ b/app/Services/Social/XPublisher.php
@@ -6,6 +6,7 @@ namespace App\Services\Social;
use App\Dto\MediaItem;
use App\Enums\Media\Type as MediaType;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\X\MediaProcessingState;
use App\Exceptions\PlatformUnavailableException;
@@ -17,6 +18,7 @@ use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\Concerns\PublishesThreads;
use App\Support\Social\PublishCheckpoint;
use App\Support\Social\ThreadProgress;
+use App\Support\Social\XPoll;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
@@ -78,11 +80,7 @@ class XPublisher
$post,
$rootHash,
fn (): array => $this->publishRoot($post, $content),
- fn (string $text, Collection $media, array $parent): array => $this->createTweet([
- ...($text !== '' ? ['text' => $text] : []),
- ...$this->mediaPayload($media),
- 'reply' => ['in_reply_to_tweet_id' => (string) $parent['id']],
- ], $account->username),
+ fn (string $text, Collection $media, array $parent, array $root, ?array $poll): array => $this->publishReply($text, $media, $parent, $poll, $account->username),
);
}
@@ -91,19 +89,14 @@ class XPublisher
*/
private function publishRoot(Post $post, ?string $content): array
{
- $data = [];
-
- if (! empty($content)) {
- $data['text'] = $content;
- }
-
- $data = [...$data, ...$this->mediaPayload($post->mediaItems)];
+ $isPoll = $post->content_type === ContentType::XPoll;
+ $data = $this->withText($content, $this->attachments($content, $post->mediaItems, $isPoll, $post->meta));
if (data_get($post->meta, 'is_ai_generated') === true) {
$data['made_with_ai'] = true;
}
- if (empty($content) && ! isset($data['media'])) {
+ if (blank($content) && ! isset($data['media'])) {
throw new XPublishException(
userMessage: 'X posts require either text or media. Please add content to your post.',
category: ErrorCategory::MediaFormat,
@@ -113,6 +106,96 @@ class XPublisher
return $this->createTweet($data, $post->socialAccount->username);
}
+ /**
+ * A reply of the thread, under the post before it.
+ *
+ * @param Collection<int, MediaItem> $media
+ * @param array<string, mixed> $parent
+ * @param array<string, mixed>|null $poll
+ * @return array{id: string, url: ?string}
+ */
+ private function publishReply(string $text, Collection $media, array $parent, ?array $poll, string $username): array
+ {
+ $data = $this->withText($text, [
+ ...$this->attachments($text, $media, filled($poll), ['poll' => $poll]),
+ 'reply' => ['in_reply_to_tweet_id' => (string) data_get($parent, 'id')],
+ ]);
+
+ return $this->createTweet($data, $username);
+ }
+
+ /**
+ * The tweet's fields, led by its text when it has any.
+ *
+ * @param array<string, mixed> $fields
+ * @return array<string, mixed>
+ */
+ private function withText(?string $text, array $fields): array
+ {
+ if (blank($text)) {
+ return $fields;
+ }
+
+ return ['text' => $text, ...$fields];
+ }
+
+ /**
+ * What a post of the thread attaches: its poll, or its media.
+ *
+ * @param Collection<int, MediaItem> $media
+ * @return array<string, mixed>
+ */
+ private function attachments(?string $text, Collection $media, bool $isPoll, mixed $meta): array
+ {
+ if ($isPoll) {
+ return ['poll' => $this->pollPayload($text, $media, $meta)];
+ }
+
+ return $this->mediaPayload($media);
+ }
+
+ /**
+ * A poll, on the post or on a reply, needs its question (that post's text),
+ * distinct choices and a length, and cannot carry media. `$meta` holds the
+ * poll under `poll`: the post's meta, or the reply itself.
+ *
+ * @param Collection<int, MediaItem> $media
+ * @return array{options: list<string>, duration_minutes: int}
+ */
+ private function pollPayload(?string $question, Collection $media, mixed $meta): array
+ {
+ $violation = $this->pollViolation($question, $media, $meta);
+
+ if (filled($violation)) {
+ throw new XPublishException(userMessage: $violation, category: ErrorCategory::ContentPolicy);
+ }
+
+ return XPoll::payload($meta);
+ }
+
+ /**
+ * Why X would refuse the poll: no question, media on it, or choices and a
+ * length that break X's rules. Null when the poll can go.
+ *
+ * @param Collection<int, MediaItem> $media
+ */
+ private function pollViolation(?string $question, Collection $media, mixed $meta): ?string
+ {
+ $questionViolation = XPoll::questionViolation($question);
+
+ if (filled($questionViolation)) {
+ return $questionViolation;
+ }
+
+ if ($media->isNotEmpty()) {
+ return trans('posts.errors.media_not_accepted');
+ }
+
+ $pollViolation = XPoll::violation($meta) ?? XPoll::requiredViolation($meta);
+
+ return data_get($pollViolation, 1);
+ }
+
/**
* Uploads the media and returns the tweet's `media` field, empty when
* nothing uploaded.
diff --git a/app/Support/PostCompositionValidator.php b/app/Support/PostCompositionValidator.php
index 8c8fba33d..b3ac60bbb 100644
--- a/app/Support/PostCompositionValidator.php
+++ b/app/Support/PostCompositionValidator.php
@@ -15,6 +15,7 @@ use App\Models\Workspace;
use App\Rules\ContentFitsPlatformLimits;
use App\Rules\ContentTypeCompatibleWithMedia;
use App\Rules\PostContentFitsMaxLength;
+use App\Support\Social\XPoll;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
@@ -173,8 +174,8 @@ class PostCompositionValidator
$validator->errors()->add("{$key}.social_account_id", __('posts.errors.queue_requires_schedule'));
}
- $contentType = ContentType::tryFrom((string) $destination['content_type']);
- if ($contentType && ! in_array($account->platform, $contentType->compatiblePlatforms(), true)) {
+ $contentType = ContentType::resolve($destination['content_type']);
+ if (filled($contentType) && ! $contentType->isCompatibleWith($account->platform)) {
$validator->errors()->add("{$key}.content_type", trans('validation.in', ['attribute' => 'content type']));
}
@@ -197,12 +198,22 @@ class PostCompositionValidator
}
}
- $formatViolation = PostPlatformMetaRules::formatViolation($account->platform, $destination['meta'] ?? []);
+ $formatViolation = PostPlatformMetaRules::formatViolation($account->platform, data_get($destination, 'meta', []), $contentType);
if ($formatViolation !== null) {
[$field, $message] = $formatViolation;
$validator->errors()->add("{$key}.meta.{$field}", $message);
}
+ $pollWithMedia = $contentType === ContentType::XPoll && filled(data_get($destination, 'media'));
+
+ if ($pollWithMedia) {
+ $validator->errors()->add("{$key}.media", trans('posts.errors.media_not_accepted'));
+ }
+
+ foreach (ThreadReplies::pollMediaErrors($account->platform, data_get($destination, 'meta', [])) as $field => $message) {
+ $validator->errors()->add("{$key}.meta.{$field}", $message);
+ }
+
if ($composition['status'] === 'draft') {
continue;
}
@@ -215,7 +226,10 @@ class PostCompositionValidator
$validator->errors()->add("{$key}.content", $contentValidator->errors()->first('content'));
}
- if (blank($destination['content']) && $destination['media'] === []) {
+ $questionViolation = $contentType === ContentType::XPoll ? XPoll::questionViolation(data_get($destination, 'content')) : null;
+ if (filled($questionViolation)) {
+ $validator->errors()->add("{$key}.content", $questionViolation);
+ } elseif (blank(data_get($destination, 'content')) && blank(data_get($destination, 'media'))) {
$validator->errors()->add("{$key}.content", trans('posts.edit.compliance.requires_content_or_media'));
}
@@ -226,11 +240,13 @@ class PostCompositionValidator
$validator->errors()->add("{$key}.meta.{$field}", $message);
}
- foreach (ContentTypeCompatibleWithMedia::errorsFor([[
- 'key' => "{$key}.content_type",
- 'content_type' => $destination['content_type'],
- ]], $destination['media'], $workspace) as $field => $message) {
- $validator->errors()->add($field, $message);
+ if (! $pollWithMedia) {
+ foreach (ContentTypeCompatibleWithMedia::errorsFor([[
+ 'key' => "{$key}.content_type",
+ 'content_type' => $destination['content_type'],
+ ]], $destination['media'], $workspace) as $field => $message) {
+ $validator->errors()->add($field, $message);
+ }
}
foreach (ThreadReplies::mediaErrors($account->platform, $destination['meta'] ?? [], $workspace) as $field => $message) {
diff --git a/app/Support/PostMeta.php b/app/Support/PostMeta.php
index ea0525849..d911488a7 100644
--- a/app/Support/PostMeta.php
+++ b/app/Support/PostMeta.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Support;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\SocialAccount;
use App\Services\Social\Discord\DiscordClient;
@@ -26,19 +27,50 @@ class PostMeta
* @param array<string, mixed> $stored the meta the post had before this save
* @return array<string, mixed>
*/
- public static function forChannel(SocialAccount $account, array $meta, array $stored = []): array
+ public static function forChannel(SocialAccount $account, array $meta, array $stored = [], ContentType|string|null $contentType = null): array
{
$meta = [
...PostPlatformMetaRules::normalize($meta),
...Arr::only($stored, PostPlatformMetaRules::SYSTEM_KEYS),
];
+ if (ContentType::resolve($contentType) !== ContentType::XPoll) {
+ $meta = Arr::except($meta, 'poll');
+ }
+
+ if ($account->platform !== Platform::X) {
+ $meta = ThreadReplies::withoutPolls($meta);
+ }
+
return match ($account->platform) {
Platform::Discord => self::withDiscordChannelName($account, $meta),
default => $meta,
};
}
+ /**
+ * The meta an update starts from: the stored meta with the sent keys on top.
+ * A sent poll is merged into the stored one key by key, so sending only its
+ * choices keeps its length (and the reverse); `options` is replaced as a
+ * whole list.
+ *
+ * @param array<string, mixed> $stored
+ * @param array<string, mixed> $incoming
+ * @return array<string, mixed>
+ */
+ public static function merge(array $stored, array $incoming): array
+ {
+ $merged = [...$stored, ...$incoming];
+ $storedPoll = data_get($stored, 'poll');
+ $incomingPoll = data_get($incoming, 'poll');
+
+ if (is_array($storedPoll) && is_array($incomingPoll)) {
+ $merged['poll'] = [...$storedPoll, ...$incomingPoll];
+ }
+
+ return $merged;
+ }
+
/**
* The Discord channel name the preview shows. It is never taken from the
* request: only `channel_id` is, and the name is read from the server's
diff --git a/app/Support/PostPlatformMetaRules.php b/app/Support/PostPlatformMetaRules.php
index 63ebdb0a2..31bb6c01a 100644
--- a/app/Support/PostPlatformMetaRules.php
+++ b/app/Support/PostPlatformMetaRules.php
@@ -17,6 +17,7 @@ use App\Models\Post;
use App\Models\SocialAccount;
use App\Rules\ValidYouTubeDescription;
use App\Services\Social\ContentSanitizer;
+use App\Support\Social\XPoll;
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
@@ -72,6 +73,11 @@ class PostPlatformMetaRules
"{$prefix}.audio.audio_volume" => ['sometimes', 'nullable', 'integer', 'between:0,100'],
"{$prefix}.audio.video_volume" => ['sometimes', 'nullable', 'integer', 'between:0,100'],
+ "{$prefix}.poll" => ['sometimes', 'nullable', 'array'],
+ "{$prefix}.poll.options" => ['sometimes', 'nullable', 'array', self::pollOptionsCount(...)],
+ "{$prefix}.poll.options.*" => ['nullable', 'string', self::pollChoiceLength(...)],
+ "{$prefix}.poll.duration_minutes" => ['sometimes', 'nullable', 'integer', 'between:'.XPoll::MIN_DURATION.','.XPoll::MAX_DURATION],
+
"{$prefix}.spoiler_text" => ['sometimes', 'nullable', 'string', 'max:500'],
"{$prefix}.thread_replies" => ['sometimes', 'nullable', 'array', 'max:'.ThreadReplies::MAX_REPLIES],
@@ -90,6 +96,10 @@ class PostPlatformMetaRules
"{$prefix}.thread_replies.*.media.*.id" => ['sometimes', 'nullable', 'string'],
"{$prefix}.thread_replies.*.media.*.upload_token" => ['sometimes', 'nullable', 'string'],
"{$prefix}.thread_replies.*.media.*.url" => ['sometimes', 'nullable', 'string'],
+ "{$prefix}.thread_replies.*.poll" => ['sometimes', 'nullable', 'array'],
+ "{$prefix}.thread_replies.*.poll.options" => ['sometimes', 'nullable', 'array', self::pollOptionsCount(...)],
+ "{$prefix}.thread_replies.*.poll.options.*" => ['nullable', 'string', self::pollChoiceLength(...)],
+ "{$prefix}.thread_replies.*.poll.duration_minutes" => ['sometimes', 'nullable', 'integer', 'between:'.XPoll::MIN_DURATION.','.XPoll::MAX_DURATION],
"{$prefix}.document_title" => ['sometimes', 'nullable', 'string', 'max:300'],
@@ -185,9 +195,35 @@ class PostPlatformMetaRules
"{$prefix}.collaborators.*.regex" => __('posts.form.instagram.collaborators.invalid'),
"{$prefix}.event.end_date.after_or_equal" => __('posts.form.google_business.event_end_date_before_start'),
"{$prefix}.event.title.max" => __('posts.form.google_business.title_max'),
+ "{$prefix}.poll.array" => __('posts.form.x.poll.poll_object'),
+ "{$prefix}.poll.options.array" => __('posts.form.x.poll.options_list'),
+ "{$prefix}.poll.options.*.string" => __('posts.form.x.poll.choice_text'),
+ "{$prefix}.poll.duration_minutes.integer" => XPoll::durationRangeMessage(),
+ "{$prefix}.poll.duration_minutes.between" => XPoll::durationRangeMessage(),
+ "{$prefix}.thread_replies.*.poll.array" => __('posts.form.x.poll.poll_object'),
+ "{$prefix}.thread_replies.*.poll.options.array" => __('posts.form.x.poll.options_list'),
+ "{$prefix}.thread_replies.*.poll.options.*.string" => __('posts.form.x.poll.choice_text'),
+ "{$prefix}.thread_replies.*.poll.duration_minutes.integer" => XPoll::durationRangeMessage(),
+ "{$prefix}.thread_replies.*.poll.duration_minutes.between" => XPoll::durationRangeMessage(),
];
}
+ /**
+ * A poll's choices, checked by `XPoll` (the post's poll and each reply's).
+ */
+ private static function pollOptionsCount(string $attribute, mixed $value, Closure $fail): void
+ {
+ transform(XPoll::optionsCountViolation($value), $fail);
+ }
+
+ /**
+ * One poll choice, checked by `XPoll`.
+ */
+ private static function pollChoiceLength(string $attribute, mixed $value, Closure $fail): void
+ {
+ transform(XPoll::choiceLengthViolation($value), $fail);
+ }
+
/**
* Friendly attribute names so default messages never expose raw meta keys.
*
@@ -218,13 +254,13 @@ class PostPlatformMetaRules
'Discord: channel_id (required to publish — call list-discord-channels-tool first), mentions ([{token,label}], e.g. {token: "@everyone"} or {token: "<@&roleId>"}), embeds (up to 10 [{title ≤256, description ≤4096, url, image (URL), color (#RRGGBB)}]).',
'YouTube Shorts: title (≤100, no < or >; omitted, it is derived from the first non-empty line of the content with < and > removed, cut to 100 characters), description (plain text, at most 5000 bytes; omit or null to use the content), category_id (YouTube category id: '.collect(Category::cases())->map(fn (Category $category): string => "{$category->value}=".__($category->labelKey(), [], 'en'))->implode(', ').'; default '.Category::DEFAULT->value.'), privacy_status (public|unlisted|private, default public), license (youtube|creativeCommon), notify_subscribers (default true), embeddable (default true), made_for_kids (default false), is_ai_generated (discloses altered or synthetic content).',
'Instagram: is_ai_generated (feed, reels, stories, carousels), share_to_feed (instagram_reel only, default true), collaborators (up to '.self::INSTAGRAM_MAX_COLLABORATORS.' Instagram usernames invited as co-authors; feed, reels and carousels, not stories; the post shows on a collaborator\'s profile only after they accept the invite in the Instagram app, and a username that does not exist is only refused when the post publishes, so confirm the usernames first), trial_graduation (instagram_reel only: MANUAL|SS_PERFORMANCE publishes a trial reel shown only to non-followers, graduated by hand in the app or by Instagram when it performs well; not with collaborators, and only on accounts where Instagram offers trial reels), audio (instagram_reel only, Instagram connected through Facebook, platform instagram-facebook: {id} of an Instagram audio track from search-instagram-audio-tool, with optional title, artist, cover_url and preview_url copied from that result so the app can show the track, and audio_volume and video_volume from 0 to 100, default 100). An instagram_feed post with a single video publishes as a Reel. People tags are the media item meta.user_tags and a video cover frame is meta.cover_offset_ms.',
- 'X: is_ai_generated (sent as made_with_ai, discloses AI-generated media on the post).',
+ 'X: is_ai_generated (sent as made_with_ai, discloses AI-generated media on the post). poll (content_type x_poll only, no media; the post content is the question; a reply of the thread can be a poll too, see thread_replies, up to '.XPoll::QUESTION_MAX_LENGTH.' characters): {options (list of '.XPoll::MIN_OPTIONS.' to '.XPoll::MAX_OPTIONS.' choices of 1 to '.XPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped), duration_minutes ('.XPoll::MIN_DURATION.' to '.XPoll::MAX_DURATION.', how long voting stays open)}, both required to schedule or publish.',
'Threads: topic_tag (1-50 characters after a leading # is dropped, no . or &). Use content_type threads_ghost_post for a text-only post archived after 24 hours (no media, no topic).',
'Facebook, Bluesky, LinkedIn: link_preview (default true; false publishes a text post with a link without its preview card).',
'LinkedIn (profile and page): document_title (≤300, the title shown on a PDF document post; defaults to the file name).',
'Google Business Profile: topic_type STANDARD (default)|EVENT|OFFER; call_to_action {action_type: '.implode('|', array_column(CtaAction::cases(), 'value')).', url} (not on OFFER; url required unless NONE or CALL); event {title ≤'.TopicType::TITLE_MAX_LENGTH.', start_date, end_date (YYYY-MM-DD), start_time, end_time (HH:MM)} (required on EVENT and OFFER, the title being the offer title); offer {coupon_code, redeem_online_url, terms_conditions ≤5000} (OFFER only).',
'Telegram, Facebook reels and stories: no settings. Stories (Instagram and Facebook) publish no text.',
- 'Threads of posts: thread_replies (list of up to '.ThreadReplies::MAX_REPLIES.' replies published under the post as a thread, each {text, media} where media is a list of up to 4 media items ({url}, {id} or {upload_token}, with optional meta.alt_text) for that reply alone; a plain string is a text-only reply) on Bluesky, Mastodon and X only; each reply needs text or media, its media follows the rules of a post on that network, and its text must fit the account limit (Bluesky 300, Mastodon 500 including the content warning, which every reply repeats, X 280 or 25000 for accounts with long posts).',
+ 'Threads of posts: thread_replies (list of up to '.ThreadReplies::MAX_REPLIES.' replies published under the post as a thread, each {text, media} where media is a list of up to 4 media items ({url}, {id} or {upload_token}, with optional meta.alt_text) for that reply alone; a plain string is a text-only reply) on Bluesky, Mastodon and X only; each reply needs text or media, its media follows the rules of a post on that network, and its text must fit the account limit (Bluesky 300, Mastodon 500 including the content warning, which every reply repeats, X 280 or 25000 for accounts with long posts). On X a reply may instead be a poll: {text, poll} with poll {options, duration_minutes} under the same rules as meta.poll, no media, and the reply text as its question (required, up to '.XPoll::QUESTION_MAX_LENGTH.' characters).',
]);
}
@@ -270,6 +306,12 @@ class PostPlatformMetaRules
throw ValidationException::withMessages(["meta.{$field}" => $message]);
}
+
+ $question = $post->content_type === ContentType::XPoll ? XPoll::questionViolation($post->content) : null;
+
+ if (filled($question)) {
+ throw ValidationException::withMessages(['content' => $question]);
+ }
}
/**
@@ -294,6 +336,10 @@ class PostPlatformMetaRules
$meta['thread_replies'] = ThreadReplies::of($meta);
}
+ if (is_array(data_get($meta, 'poll'))) {
+ $meta['poll'] = XPoll::normalize($meta['poll']);
+ }
+
if (is_array(data_get($meta, 'collaborators'))) {
$meta['collaborators'] = self::instagramCollaborators($meta['collaborators']);
}
@@ -345,9 +391,14 @@ class PostPlatformMetaRules
*
* @return array{0: string, 1: string}|null [field, message]
*/
- public static function formatViolation(?Platform $platform, mixed $meta): ?array
+ public static function formatViolation(?Platform $platform, mixed $meta, ContentType|string|null $contentType = null): ?array
{
- return $platform === Platform::YouTube ? YouTubeMetadata::violation($meta) : null;
+ if ($platform === Platform::YouTube) {
+ return YouTubeMetadata::violation($meta);
+ }
+
+ return (ContentType::resolve($contentType) === ContentType::XPoll ? XPoll::violation($meta) : null)
+ ?? ($platform === Platform::X ? ThreadReplies::pollFormatViolation($meta) : null);
}
/**
@@ -361,7 +412,7 @@ class PostPlatformMetaRules
public static function requiredMetaViolation(Platform|SocialAccount|null $target, mixed $meta, mixed $contentType = null): ?array
{
$platform = $target instanceof SocialAccount ? $target->platform : $target;
- $isInstagramReel = ($contentType instanceof ContentType ? $contentType : ContentType::tryFrom(is_string($contentType) ? $contentType : '')) === ContentType::InstagramReel;
+ $type = ContentType::resolve($contentType);
$threadViolation = ThreadReplies::violation($target, $meta);
if ($threadViolation !== null) {
@@ -375,7 +426,8 @@ class PostPlatformMetaRules
return match (true) {
$platform === Platform::YouTube => self::youtubeDescriptionViolation($meta) ?? self::formatViolation($platform, $meta),
$platform === Platform::TikTok => self::tiktokPrivacyViolation($meta),
- $isInstagramReel => self::instagramReelViolation($platform, $meta),
+ $type === ContentType::InstagramReel => self::instagramReelViolation($platform, $meta),
+ $type === ContentType::XPoll => XPoll::violation($meta) ?? XPoll::requiredViolation($meta),
$platform === Platform::Pinterest && blank(data_get($meta, 'board_id')) => ['board_id', trans('posts.form.pinterest.board_required')],
$platform === Platform::Discord && blank(data_get($meta, 'channel_id')) => ['channel_id', trans('posts.form.discord.channel_required')],
$needsGoogleBusinessEvent
diff --git a/app/Support/Requests/Post/PostRequestRules.php b/app/Support/Requests/Post/PostRequestRules.php
index 8447304cf..07d9c0d48 100644
--- a/app/Support/Requests/Post/PostRequestRules.php
+++ b/app/Support/Requests/Post/PostRequestRules.php
@@ -16,6 +16,7 @@ use App\Rules\ContentTypeMatchesPlatform;
use App\Rules\ContentTypeMatchesPostChannel;
use App\Rules\PostContentFitsMaxLength;
use App\Support\PostMediaRules;
+use App\Support\PostMeta;
use App\Support\PostPlatformMetaRules;
use App\Support\PostStatusRules;
use Illuminate\Support\Collection;
@@ -246,13 +247,14 @@ class PostRequestRules
}
/**
- * The meta the update would store: the submitted keys over the stored ones.
+ * The meta the update would store: the submitted keys over the stored ones,
+ * merged as `UpdatePost` merges them (`PostMeta::merge()`).
*
* @param array<string, mixed> $input
* @return array<string, mixed>
*/
private static function effectiveMeta(Post $post, array $input): array
{
- return [...($post->meta ?? []), ...(array) data_get($input, 'meta', [])];
+ return PostMeta::merge($post->meta ?? [], (array) data_get($input, 'meta', []));
}
}
diff --git a/app/Support/Social/ThreadProgress.php b/app/Support/Social/ThreadProgress.php
index 012dbba6f..0363add42 100644
--- a/app/Support/Social/ThreadProgress.php
+++ b/app/Support/Social/ThreadProgress.php
@@ -16,11 +16,15 @@ final class ThreadProgress
public const string KEY = 'thread_progress';
/**
+ * A reply poll is part of the segment, so changing it is a new segment;
+ * a segment without one keeps the hash it always had.
+ *
* @param list<string> $mediaIds
+ * @param array<string, mixed>|null $poll
*/
- public static function hash(string $text, array $mediaIds = []): string
+ public static function hash(string $text, array $mediaIds = [], ?array $poll = null): string
{
- return sha1((string) json_encode([$text, $mediaIds]));
+ return sha1((string) json_encode(blank($poll) ? [$text, $mediaIds] : [$text, $mediaIds, $poll]));
}
/**
diff --git a/app/Support/Social/XPoll.php b/app/Support/Social/XPoll.php
new file mode 100644
index 000000000..d142653c5
--- /dev/null
+++ b/app/Support/Social/XPoll.php
@@ -0,0 +1,246 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Support\Social;
+
+use App\Enums\SocialAccount\Platform;
+use App\Enums\X\PollVotingStatus;
+use App\Models\AnalyticsPublication;
+use App\Services\Social\ContentSanitizer;
+use Carbon\CarbonInterface;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Str;
+
+/**
+ * The poll an X post may carry (`meta.poll`, content type `x_poll`): two to
+ * four short choices and how long voting stays open. Blank choices are dropped
+ * when the meta is normalized, so the rules below read the cleaned list.
+ */
+final class XPoll
+{
+ public const int MIN_OPTIONS = 2;
+
+ public const int MAX_OPTIONS = 4;
+
+ public const int OPTION_MAX_LENGTH = 25;
+
+ public const int MIN_DURATION = 5;
+
+ public const int MAX_DURATION = 10080;
+
+ public const int DEFAULT_DURATION = 1440;
+
+ public const int QUESTION_MAX_LENGTH = 280;
+
+ /**
+ * The `poll.fields` every tweet lookup asks X for.
+ */
+ public const string LOOKUP_FIELDS = 'options,duration_minutes,end_datetime,voting_status';
+
+ /**
+ * The limits the composer reads from `Platform::publishConfig()`, so they are never copied into TypeScript.
+ *
+ * @return array{minOptions: int, maxOptions: int, optionMaxLength: int, minDuration: int, maxDuration: int, defaultDuration: int, questionMaxLength: int}
+ */
+ public static function limits(): array
+ {
+ return [
+ 'minOptions' => self::MIN_OPTIONS,
+ 'maxOptions' => self::MAX_OPTIONS,
+ 'optionMaxLength' => self::OPTION_MAX_LENGTH,
+ 'minDuration' => self::MIN_DURATION,
+ 'maxDuration' => self::MAX_DURATION,
+ 'defaultDuration' => self::DEFAULT_DURATION,
+ 'questionMaxLength' => self::QUESTION_MAX_LENGTH,
+ ];
+ }
+
+ /**
+ * The poll's choices, trimmed, without blanks.
+ *
+ * @return list<string>
+ */
+ public static function options(mixed $meta): array
+ {
+ return self::choices(data_get($meta, 'poll.options'));
+ }
+
+ /**
+ * A list of choices, trimmed, without blanks.
+ *
+ * @return list<string>
+ */
+ public static function choices(mixed $options): array
+ {
+ return Collection::wrap($options)
+ ->filter(fn (mixed $option): bool => is_string($option))
+ ->map(fn (string $option): string => Str::trim($option))
+ ->filter(fn (string $option): bool => filled($option))
+ ->values()
+ ->all();
+ }
+
+ /**
+ * @param array<string, mixed> $poll
+ * @return array{options: list<string>, duration_minutes?: int}
+ */
+ public static function normalize(array $poll): array
+ {
+ return Arr::whereNotNull([
+ 'options' => self::choices(data_get($poll, 'options')),
+ 'duration_minutes' => self::minutes(data_get($poll, 'duration_minutes')),
+ ]);
+ }
+
+ /**
+ * @return array{0: string, 1: string}|null [field, message]
+ */
+ public static function violation(mixed $meta): ?array
+ {
+ $duplicates = collect(self::options($meta))->map(fn (string $option): string => Str::lower($option))->duplicatesStrict();
+
+ if ($duplicates->isNotEmpty()) {
+ return ['poll.options', trans('posts.form.x.poll.options_distinct')];
+ }
+
+ return null;
+ }
+
+ /**
+ * Too many choices once blanks are dropped, refused at every save.
+ */
+ public static function optionsCountViolation(mixed $options): ?string
+ {
+ return when(
+ count(self::choices($options)) > self::MAX_OPTIONS,
+ fn (): string => trans('posts.form.x.poll.options_max', ['max' => self::MAX_OPTIONS]),
+ );
+ }
+
+ /**
+ * A choice's length as X counts it, without the spaces around it: in
+ * UTF-16 units, so an emoji outside the basic plane (🐧) counts two. X
+ * refused a 25-character choice holding one with "is not 1 to 25
+ * characters long".
+ */
+ public static function choiceLength(string $choice): int
+ {
+ return intdiv(strlen(mb_convert_encoding(Str::trim($choice), 'UTF-16LE', 'UTF-8')), 2);
+ }
+
+ /**
+ * A choice longer than X allows once trimmed, refused at every save.
+ */
+ public static function choiceLengthViolation(mixed $choice): ?string
+ {
+ $tooLong = is_string($choice) && self::choiceLength($choice) > self::OPTION_MAX_LENGTH;
+
+ return when($tooLong, fn (): string => trans('posts.form.x.poll.choice_max', ['max' => self::OPTION_MAX_LENGTH]));
+ }
+
+ /**
+ * "Add at least 2 choices", with the minimum from X's rules.
+ */
+ public static function optionsRequiredMessage(): string
+ {
+ return trans('posts.form.x.poll.options_required', ['min' => self::MIN_OPTIONS]);
+ }
+
+ /**
+ * "From 5 minutes to 7 days", with the range from X's rules.
+ */
+ public static function durationRangeMessage(): string
+ {
+ $maxDays = intdiv(self::MAX_DURATION, CarbonInterface::MINUTES_PER_HOUR * CarbonInterface::HOURS_PER_DAY);
+
+ return trans('posts.form.x.poll.duration_range', ['min' => self::MIN_DURATION, 'max' => $maxDays]);
+ }
+
+ /**
+ * What a poll needs before its post is scheduled or published.
+ *
+ * @return array{0: string, 1: string}|null [field, message]
+ */
+ public static function requiredViolation(mixed $meta): ?array
+ {
+ if (count(self::options($meta)) < self::MIN_OPTIONS) {
+ return ['poll.options', self::optionsRequiredMessage()];
+ }
+
+ if (blank(data_get($meta, 'poll.duration_minutes'))) {
+ return ['poll.duration_minutes', trans('posts.form.x.poll.duration_required')];
+ }
+
+ return null;
+ }
+
+ /**
+ * A poll's question is the post text: it cannot be scheduled or published
+ * without one. It is measured as X receives it, so editor markup with no
+ * words (`<p></p>`) counts as no question.
+ */
+ public static function questionViolation(?string $content): ?string
+ {
+ $question = app(ContentSanitizer::class)->displayText((string) $content, Platform::X);
+
+ return when(blank($question), fn (): string => trans('posts.form.x.poll.question_required'));
+ }
+
+ /**
+ * One X poll object as the tweet lookup returns it, reduced to what is stored.
+ *
+ * @param array<string, mixed> $poll
+ * @return array{options: list<array{label: string, votes: int}>, voting_status: ?string, end_datetime: ?string, duration_minutes: ?int}
+ */
+ public static function result(array $poll): array
+ {
+ return [
+ 'options' => Collection::wrap(data_get($poll, 'options'))
+ ->sortBy(fn (mixed $option): int => (int) data_get($option, 'position', 0))
+ ->map(fn (mixed $option): array => [
+ 'label' => (string) data_get($option, 'label', ''),
+ 'votes' => (int) data_get($option, 'votes', 0),
+ ])
+ ->values()
+ ->all(),
+ 'voting_status' => PollVotingStatus::tryFrom((string) data_get($poll, 'voting_status'))?->value,
+ 'end_datetime' => data_get($poll, 'end_datetime'),
+ 'duration_minutes' => self::minutes(data_get($poll, 'duration_minutes')),
+ ];
+ }
+
+ /**
+ * The poll meta of an X poll found on the network, read from what discovery stored.
+ *
+ * @return array{options: list<string>, duration_minutes: int}
+ */
+ public static function fromPublication(AnalyticsPublication $publication): array
+ {
+ $poll = data_get($publication->provider_metadata, 'poll');
+
+ return [
+ 'options' => Collection::wrap(data_get($poll, 'options'))->pluck('label')->all(),
+ 'duration_minutes' => self::minutes(data_get($poll, 'duration_minutes'), self::DEFAULT_DURATION),
+ ];
+ }
+
+ /**
+ * The `poll` field of the create-post request.
+ *
+ * @return array{options: list<string>, duration_minutes: int}
+ */
+ public static function payload(mixed $meta): array
+ {
+ return [
+ 'options' => self::options($meta),
+ 'duration_minutes' => self::minutes(data_get($meta, 'poll.duration_minutes'), self::DEFAULT_DURATION),
+ ];
+ }
+
+ private static function minutes(mixed $value, ?int $default = null): ?int
+ {
+ return transform($value, fn (mixed $minutes): int => (int) $minutes, $default);
+ }
+}
diff --git a/app/Support/ThreadReplies.php b/app/Support/ThreadReplies.php
index 2d53edec0..64d65081a 100644
--- a/app/Support/ThreadReplies.php
+++ b/app/Support/ThreadReplies.php
@@ -12,6 +12,8 @@ use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Rules\ContentTypeCompatibleWithMedia;
use App\Services\Social\ContentSanitizer;
+use App\Support\Social\XPoll;
+use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
@@ -20,7 +22,9 @@ use Illuminate\Support\Str;
* networks that let an app reply to its own post with the scopes we hold.
* Each reply is `{text, media}`; its media belongs to that reply and follows
* the rules of the network's reply content type. A reply stored as a bare
- * string is a text-only reply.
+ * string is a text-only reply. On X a reply may carry a poll instead of media
+ * (`{text, media, poll}`), following `XPoll`'s rules with the reply text as
+ * its question.
*/
class ThreadReplies
{
@@ -46,7 +50,7 @@ class ThreadReplies
}
/**
- * @return list<array{text: string, media: list<array<string, mixed>>}>
+ * @return list<array{text: string, media: list<array<string, mixed>>, poll?: array{options: list<string>, duration_minutes?: int}}>
*/
public static function of(mixed $meta): array
{
@@ -57,7 +61,7 @@ class ThreadReplies
}
/**
- * @return array{text: string, media: list<array<string, mixed>>}
+ * @return array{text: string, media: list<array<string, mixed>>, poll?: array{options: list<string>, duration_minutes?: int}}
*/
public static function reply(mixed $reply): array
{
@@ -66,11 +70,81 @@ class ThreadReplies
}
$text = data_get($reply, 'text');
+ $poll = data_get($reply, 'poll');
- return [
+ $normalized = [
'text' => is_string($text) ? $text : '',
'media' => array_values(array_filter((array) data_get($reply, 'media', []), is_array(...))),
];
+
+ if (is_array($poll) && filled($poll)) {
+ $normalized['poll'] = XPoll::normalize($poll);
+ }
+
+ return $normalized;
+ }
+
+ /**
+ * Whether a reply is a poll (an X reply only; `of()` drops an empty one).
+ *
+ * @param array<string, mixed> $reply
+ */
+ public static function hasPoll(array $reply): bool
+ {
+ return filled(data_get($reply, 'poll'));
+ }
+
+ /**
+ * Replies without their polls, for a network other than X.
+ *
+ * @param array<string, mixed> $meta
+ * @return array<string, mixed>
+ */
+ public static function withoutPolls(array $meta): array
+ {
+ if (blank(data_get($meta, 'thread_replies'))) {
+ return $meta;
+ }
+
+ $meta['thread_replies'] = collect(self::of($meta))->map(fn (array $reply): array => Arr::except($reply, 'poll'))->all();
+
+ return $meta;
+ }
+
+ /**
+ * A reply poll no post may store, even as a draft: repeated choices.
+ *
+ * @return array{0: string, 1: string}|null [field, message]
+ */
+ public static function pollFormatViolation(mixed $meta): ?array
+ {
+ foreach (self::of($meta) as $index => $reply) {
+ $violation = self::hasPoll($reply) ? XPoll::violation($reply) : null;
+
+ if (filled($violation)) {
+ return ["thread_replies.{$index}.{$violation[0]}", $violation[1]];
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * A reply poll carries no media, drafts included. Only X has reply polls;
+ * any other network drops them on save.
+ *
+ * @return array<string, string>
+ */
+ public static function pollMediaErrors(?Platform $platform, mixed $meta): array
+ {
+ if ($platform !== Platform::X) {
+ return [];
+ }
+
+ return collect(self::of($meta))
+ ->filter(fn (array $reply): bool => self::hasPoll($reply) && filled($reply['media']))
+ ->mapWithKeys(fn (array $reply, int $index): array => ["thread_replies.{$index}.media" => __('posts.errors.media_not_accepted')])
+ ->all();
}
/**
@@ -104,25 +178,98 @@ class ThreadReplies
}
$reserved = $platform->reservedLength(is_array($meta) ? $meta : null);
- $limit = $target instanceof SocialAccount ? $target->maxContentLength() : $platform->maxContentLength();
+ $account = $target instanceof SocialAccount ? $target : null;
foreach ($replies as $index => $reply) {
- $blank = blank(Str::trim($reply['text']));
+ $violation = self::replyViolation($reply, $platform, $account, $reserved);
- if ($blank && $reply['media'] === []) {
- return ["thread_replies.{$index}", __('posts.form.thread.reply_empty')];
+ if (filled($violation)) {
+ [$field, $message] = $violation;
+
+ return [self::replyKey($index, $field), $message];
}
+ }
- $over = $blank ? 0 : max(0, mb_strlen(app(ContentSanitizer::class)->displayText($reply['text'], $platform)) + $reserved - $limit);
+ return null;
+ }
- if ($over > 0) {
- return ["thread_replies.{$index}", __('posts.form.thread.reply_too_long', ['limit' => $limit - $reserved, 'over' => $over])];
- }
+ /**
+ * The validation key of a reply (`thread_replies.0`), or of one of its
+ * fields (`thread_replies.0.poll.options`).
+ */
+ private static function replyKey(int $index, ?string $field): string
+ {
+ if (blank($field)) {
+ return "thread_replies.{$index}";
+ }
+
+ return "thread_replies.{$index}.{$field}";
+ }
+
+ /**
+ * Why one reply cannot go: a poll is checked as a poll, any other reply
+ * needs text or media and must fit the account's limit. The field is
+ * relative to the reply (null for the reply itself).
+ *
+ * @param array{text: string, media: list<array<string, mixed>>, poll?: array<string, mixed>} $reply
+ * @return array{0: string|null, 1: string}|null
+ */
+ private static function replyViolation(array $reply, Platform $platform, ?SocialAccount $account, int $reserved): ?array
+ {
+ if ($platform === Platform::X && self::hasPoll($reply)) {
+ return self::pollReplyViolation($reply, $account, $reserved);
+ }
+
+ if (filled(Str::trim($reply['text']))) {
+ return self::lengthViolation($reply['text'], $platform, $account, self::replyContentType($platform), $reserved);
+ }
+
+ if (blank($reply['media'])) {
+ return [null, __('posts.form.thread.reply_empty')];
}
return null;
}
+ /**
+ * A reply poll needs its question (the reply's text) within the poll's cap,
+ * and choices and a length X accepts.
+ *
+ * @param array{text: string, media: list<array<string, mixed>>, poll?: array<string, mixed>} $reply
+ * @return array{0: string|null, 1: string}|null
+ */
+ private static function pollReplyViolation(array $reply, ?SocialAccount $account, int $reserved): ?array
+ {
+ $questionViolation = XPoll::questionViolation($reply['text']);
+
+ if (filled($questionViolation)) {
+ return [null, $questionViolation];
+ }
+
+ return self::lengthViolation($reply['text'], Platform::X, $account, ContentType::XPoll, $reserved)
+ ?? XPoll::violation($reply)
+ ?? XPoll::requiredViolation($reply);
+ }
+
+ /**
+ * A reply's text over its limit, measured as the network counts it.
+ *
+ * @return array{0: null, 1: string}|null
+ */
+ private static function lengthViolation(string $text, Platform $platform, ?SocialAccount $account, ?ContentType $type, int $reserved): ?array
+ {
+ $display = app(ContentSanitizer::class)->displayText($text, $platform);
+ $over = ContentType::overflowFor($account, $platform, $type, $display, $reserved);
+
+ if ($over === 0) {
+ return null;
+ }
+
+ $limit = ContentType::maxContentLengthFor($account, $platform, $type) - $reserved;
+
+ return [null, __('posts.form.thread.reply_too_long', ['limit' => $limit, 'over' => $over])];
+ }
+
/**
* Each reply's media against the reply content type, keyed
* `thread_replies.{n}.media`.
diff --git a/database/factories/AnalyticsPublicationFactory.php b/database/factories/AnalyticsPublicationFactory.php
index bb9536075..e8c9ddd44 100644
--- a/database/factories/AnalyticsPublicationFactory.php
+++ b/database/factories/AnalyticsPublicationFactory.php
@@ -50,4 +50,10 @@ class AnalyticsPublicationFactory extends Factory
'provider_metadata' => null,
];
}
+
+ /** @param array<string, mixed> $poll */
+ public function withPoll(array $poll): static
+ {
+ return $this->state(fn (): array => ['provider_metadata' => ['poll' => $poll]]);
+ }
}
diff --git a/lang/ar/posts.php b/lang/ar/posts.php
index 0c015dfe7..cb66b4509 100644
--- a/lang/ar/posts.php
+++ b/lang/ar/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'حفظ',
'photo' => 'صورة',
'ghost_expires' => 'متبقٍ 24 ساعة',
+ 'poll_summary' => '0 أصوات · الوقت المتبقي: :time',
],
'preview_empty' => 'معاينة منشورك ستظهر هنا',
'select_all' => 'تحديد الكل',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'يجب أن يتكون الموضوع من 1 إلى 50 حرفًا، بدون . أو &.',
'ghost_post_attachments' => 'لا تدعم المنشورات الشبحية المرفقات',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'أضف خيارين على الأقل إلى استطلاعك.',
+ 'options_distinct' => 'يجب أن يكون كل خيار في الاستطلاع مختلفًا. غيّر الخيار المكرر.',
+ 'duration_required' => 'اختر المدة التي يبقى فيها استطلاعك مفتوحًا.',
+ 'question_required' => 'اكتب سؤال الاستطلاع في نص المنشور.',
+ 'options_max' => 'يمكن أن يحتوي الاستطلاع على :max خيارات كحد أقصى. احذف الخيارات الزائدة.',
+ 'poll_object' => 'أرسل الاستطلاع مع خياراته (options) ومدته (duration_minutes).',
+ 'options_list' => 'أرسل خيارات الاستطلاع كقائمة من النصوص.',
+ 'choice_text' => 'يجب أن يكون كل خيار في الاستطلاع نصًا.',
+ 'choice_max' => 'يمكن أن يحتوي كل خيار في الاستطلاع على :max حرفًا كحد أقصى. اختصر الخيار الأطول.',
+ 'duration_range' => 'يمكن أن يبقى الاستطلاع مفتوحًا من :min دقائق إلى :max أيام. اختر مدة ضمن هذا النطاق.',
+ 'choices' => 'الخيارات',
+ 'choice' => 'الخيار :number',
+ 'choice_optional' => 'الخيار :number (اختياري)',
+ 'add_choice' => 'إضافة خيار',
+ 'remove_choice' => 'إزالة الخيار :number',
+ 'length' => 'المدة',
+ 'days' => 'الأيام',
+ 'hours' => 'الساعات',
+ 'minutes' => 'الدقائق',
+ 'remove' => 'إزالة الاستطلاع',
+ 'attachments' => 'الاستطلاعات لا تدعم الوسائط',
+ 'add' => 'إضافة استطلاع',
+ ],
+ ],
'linkedin' => [
'document_title' => 'عنوان المستند',
'document_title_placeholder' => 'يظهر على منشور مستند PDF الخاص بك',
@@ -786,6 +813,10 @@ return [
'label' => 'منشور',
'description' => 'تغريدة بنص ووسائط',
],
+ 'x_poll' => [
+ 'label' => 'استطلاع',
+ 'description' => 'سؤال بـ :min إلى :max خيارات',
+ ],
'threads_post' => [
'label' => 'سلسلة',
'description' => 'منشور نصي مع وسائط اختيارية',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'يحتاج كل عنصر وسائط إلى واحد فقط من upload_token أو url أو id.',
'media_url_unreachable' => 'تعذر جلب الوسائط من :url.',
'media_type_unsupported' => 'نوع هذا الملف غير مدعوم من قناة المنشور.',
+ 'media_not_accepted' => 'لا يمكن أن يتضمن هذا النوع من المنشورات وسائط. غيّر نوع المنشور لإضافة وسائط.',
'media_file_unsupported' => 'نوع هذا الملف غير مدعوم.',
'media_file_too_large' => 'حجم هذا الملف يتجاوز :size ميغابايت المسموح بها لنوعه.',
'queue_requires_schedule' => 'ليس لهذه القناة أوقات نشر بعد. أضف أوقات النشر من إعدادات القناة لاستخدام قائمة الانتظار.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'خيارات الوسائط',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count صوت|[0,*] :count أصوات',
+ 'final' => 'النتائج النهائية',
+ 'ended' => 'انتهى التصويت',
+ 'ends' => 'تنتهي :time',
+ 'thread_post' => 'المنشور :number في السلسلة',
+ ],
+
'publish' => [
'title' => 'نشر',
'all_channels' => 'جميع القنوات',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'نُشر مباشرةً من :network',
'slot_aria' => 'أضف منشورًا إلى :channel على :network في :time',
'no_time' => 'بدون وقت',
+ 'pending_slot' => [
+ 'next' => 'الخانة التالية',
+ 'top' => 'في البداية',
+ ],
'new_in_slot' => 'جديد',
'add_post_in_slot' => 'إضافة منشور',
'more_times' => 'المزيد من الأوقات',
diff --git a/lang/de/posts.php b/lang/de/posts.php
index ecc896a0c..c9c689f14 100644
--- a/lang/de/posts.php
+++ b/lang/de/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Merken',
'photo' => 'Foto',
'ghost_expires' => 'Noch 24 Std.',
+ 'poll_summary' => '0 Stimmen · noch :time',
],
'preview_empty' => 'Hier erscheint deine Beitragsvorschau',
'select_all' => 'Alle auswählen',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'Das Thema muss 1 bis 50 Zeichen ohne . oder & haben.',
'ghost_post_attachments' => 'Ghost-Posts unterstützen keine Anhänge',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Füge deiner Umfrage mindestens :min Antworten hinzu.',
+ 'options_distinct' => 'Jede Antwort muss anders sein. Ändere die doppelte.',
+ 'duration_required' => 'Wähle, wie lange deine Umfrage läuft.',
+ 'question_required' => 'Schreib die Frage deiner Umfrage in den Text des Beitrags.',
+ 'options_max' => 'Eine Umfrage kann bis zu :max Antworten haben. Entferne die übrigen.',
+ 'poll_object' => 'Sende die Umfrage mit ihren Antworten (options) und ihrer Dauer (duration_minutes).',
+ 'options_list' => 'Sende die Antworten der Umfrage als Liste von Texten.',
+ 'choice_text' => 'Jede Antwort der Umfrage muss Text sein.',
+ 'choice_max' => 'Jede Antwort kann bis zu :max Zeichen haben. Kürze die längere.',
+ 'duration_range' => 'Eine Umfrage kann :min Minuten bis :max Tage laufen. Wähle eine Dauer in diesem Bereich.',
+ 'choices' => 'Antworten',
+ 'choice' => 'Antwort :number',
+ 'choice_optional' => 'Antwort :number (optional)',
+ 'add_choice' => 'Antwort hinzufügen',
+ 'remove_choice' => 'Antwort :number entfernen',
+ 'length' => 'Dauer',
+ 'days' => 'Tage',
+ 'hours' => 'Stunden',
+ 'minutes' => 'Minuten',
+ 'remove' => 'Umfrage entfernen',
+ 'attachments' => 'Umfragen können keine Medien enthalten',
+ 'add' => 'Umfrage hinzufügen',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Dokumenttitel',
'document_title_placeholder' => 'Wird bei deinem PDF-Dokument-Beitrag angezeigt',
@@ -786,6 +813,10 @@ return [
'label' => 'Beitrag',
'description' => 'Tweet mit Text und Medien',
],
+ 'x_poll' => [
+ 'label' => 'Umfrage',
+ 'description' => 'Frage mit :min bis :max Antworten',
+ ],
'threads_post' => [
'label' => 'Thread',
'description' => 'Textbeitrag mit optionalen Medien',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Jedes Medienelement braucht genau eines von upload_token, url oder id.',
'media_url_unreachable' => 'Medien konnten nicht von :url abgerufen werden.',
'media_type_unsupported' => 'Dieser Dateityp wird vom Kanal des Beitrags nicht unterstützt.',
+ 'media_not_accepted' => 'Dieser Beitragstyp kann keine Medien enthalten. Ändere den Beitragstyp, um Medien hinzuzufügen.',
'media_file_unsupported' => 'Dieser Dateityp wird nicht unterstützt.',
'media_file_too_large' => 'Diese Datei ist größer als die für ihren Typ erlaubten :size MB.',
'queue_requires_schedule' => 'Dieser Kanal hat noch keine Veröffentlichungszeiten. Füge in den Kanaleinstellungen Zeiten hinzu, um die Warteschlange zu nutzen.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Medienoptionen',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count Stimme|[0,*] :count Stimmen',
+ 'final' => 'Endergebnis',
+ 'ended' => 'Abstimmung beendet',
+ 'ends' => 'Endet :time',
+ 'thread_post' => 'Beitrag :number im Thread',
+ ],
+
'publish' => [
'title' => 'Veröffentlichen',
'all_channels' => 'Alle Kanäle',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Direkt über :network veröffentlicht',
'slot_aria' => 'Beitrag für :channel auf :network um :time hinzufügen',
'no_time' => 'Keine Uhrzeit',
+ 'pending_slot' => [
+ 'next' => 'Nächster Slot',
+ 'top' => 'Ganz vorne',
+ ],
'new_in_slot' => 'Neu',
'add_post_in_slot' => 'Post hinzufügen',
'more_times' => 'Weitere Zeiten',
diff --git a/lang/el/posts.php b/lang/el/posts.php
index e2439550f..d8bc49e5f 100644
--- a/lang/el/posts.php
+++ b/lang/el/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Αποθήκευση',
'photo' => 'Φωτογραφία',
'ghost_expires' => 'Απομένουν 24 ώ.',
+ 'poll_summary' => '0 ψήφοι · λήγει σε :time',
],
'preview_empty' => 'Η προεπισκόπηση της ανάρτησής σας θα εμφανιστεί εδώ',
'select_all' => 'Επιλογή όλων',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'Το θέμα πρέπει να έχει από 1 έως 50 χαρακτήρες, χωρίς . ή &.',
'ghost_post_attachments' => 'Οι αναρτήσεις-φαντάσματα δεν υποστηρίζουν συνημμένα',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Πρόσθεσε τουλάχιστον :min επιλογές στη δημοσκόπησή σου.',
+ 'options_distinct' => 'Κάθε επιλογή της δημοσκόπησης πρέπει να είναι διαφορετική. Άλλαξε την επαναλαμβανόμενη.',
+ 'duration_required' => 'Διάλεξε για πόσο θα μένει ανοιχτή η δημοσκόπησή σου.',
+ 'question_required' => 'Γράψε την ερώτηση της δημοσκόπησης στο κείμενο της ανάρτησης.',
+ 'options_max' => 'Μια δημοσκόπηση μπορεί να έχει έως :max επιλογές. Αφαίρεσε όσες περισσεύουν.',
+ 'poll_object' => 'Στείλε τη δημοσκόπηση με τις επιλογές της (options) και τη διάρκειά της (duration_minutes).',
+ 'options_list' => 'Στείλε τις επιλογές της δημοσκόπησης ως λίστα κειμένων.',
+ 'choice_text' => 'Κάθε επιλογή της δημοσκόπησης πρέπει να είναι κείμενο.',
+ 'choice_max' => 'Κάθε επιλογή της δημοσκόπησης μπορεί να έχει έως :max χαρακτήρες. Συντόμευσε τη μεγαλύτερη.',
+ 'duration_range' => 'Μια δημοσκόπηση μπορεί να μένει ανοιχτή από :min λεπτά έως :max ημέρες. Διάλεξε διάρκεια μέσα σε αυτό το εύρος.',
+ 'choices' => 'Επιλογές',
+ 'choice' => 'Επιλογή :number',
+ 'choice_optional' => 'Επιλογή :number (προαιρετική)',
+ 'add_choice' => 'Προσθήκη επιλογής',
+ 'remove_choice' => 'Αφαίρεση επιλογής :number',
+ 'length' => 'Διάρκεια',
+ 'days' => 'Ημέρες',
+ 'hours' => 'Ώρες',
+ 'minutes' => 'Λεπτά',
+ 'remove' => 'Αφαίρεση δημοσκόπησης',
+ 'attachments' => 'Οι δημοσκοπήσεις δεν υποστηρίζουν πολυμέσα',
+ 'add' => 'Προσθήκη δημοσκόπησης',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Τίτλος εγγράφου',
'document_title_placeholder' => 'Εμφανίζεται στη δημοσίευση εγγράφου PDF σας',
@@ -786,6 +813,10 @@ return [
'label' => 'Δημοσίευση',
'description' => 'Tweet με κείμενο και πολυμέσα',
],
+ 'x_poll' => [
+ 'label' => 'Δημοσκόπηση',
+ 'description' => 'Ερώτηση με :min έως :max επιλογές',
+ ],
'threads_post' => [
'label' => 'Νήμα',
'description' => 'Δημοσίευση κειμένου με προαιρετικά πολυμέσα',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Κάθε στοιχείο πολυμέσων χρειάζεται ακριβώς ένα από τα upload_token, url ή id.',
'media_url_unreachable' => 'Δεν ήταν δυνατή η λήψη πολυμέσων από το :url.',
'media_type_unsupported' => 'Αυτός ο τύπος αρχείου δεν υποστηρίζεται από το κανάλι της δημοσίευσης.',
+ 'media_not_accepted' => 'Αυτός ο τύπος δημοσίευσης δεν μπορεί να περιέχει πολυμέσα. Αλλάξτε τον τύπο δημοσίευσης για να προσθέσετε πολυμέσα.',
'media_file_unsupported' => 'Αυτός ο τύπος αρχείου δεν υποστηρίζεται.',
'media_file_too_large' => 'Αυτό το αρχείο υπερβαίνει τα :size MB που επιτρέπονται για τον τύπο του.',
'queue_requires_schedule' => 'Αυτό το κανάλι δεν έχει ακόμη ώρες δημοσίευσης. Προσθέστε ώρες στις ρυθμίσεις του καναλιού για να χρησιμοποιήσετε την ουρά.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Επιλογές πολυμέσων',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count ψήφος|[0,*] :count ψήφοι',
+ 'final' => 'Τελικά αποτελέσματα',
+ 'ended' => 'Η ψηφοφορία έληξε',
+ 'ends' => 'Λήγει :time',
+ 'thread_post' => 'Ανάρτηση :number του νήματος',
+ ],
+
'publish' => [
'title' => 'Δημοσίευση',
'all_channels' => 'Όλα τα κανάλια',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Δημοσιεύτηκε απευθείας από το :network',
'slot_aria' => 'Προσθήκη ανάρτησης στο :channel στο :network στις :time',
'no_time' => 'Χωρίς ώρα',
+ 'pending_slot' => [
+ 'next' => 'Επόμενη θέση',
+ 'top' => 'Στην κορυφή',
+ ],
'new_in_slot' => 'Νέο',
'add_post_in_slot' => 'Προσθήκη ανάρτησης',
'more_times' => 'Περισσότερες ώρες',
diff --git a/lang/en/posts.php b/lang/en/posts.php
index 1e5c3b5dd..341214138 100644
--- a/lang/en/posts.php
+++ b/lang/en/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Save',
'photo' => 'Photo',
'ghost_expires' => '24h left',
+ 'poll_summary' => '0 votes · :time left',
],
'preview_empty' => 'Your post preview will appear here.',
'select_all' => 'Select all',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'The topic must have 1 to 50 characters, without . or &.',
'ghost_post_attachments' => 'Ghost Posts don\'t support attachments',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Add at least :min choices to your poll.',
+ 'options_distinct' => 'Each poll choice must be different. Change the repeated one.',
+ 'duration_required' => 'Choose how long your poll stays open.',
+ 'question_required' => 'Write your poll question in the post text.',
+ 'options_max' => 'A poll can have up to :max choices. Remove the extra ones.',
+ 'poll_object' => 'Send the poll with its choices (options) and length (duration_minutes).',
+ 'options_list' => 'Send the poll choices as a list of text.',
+ 'choice_text' => 'Each poll choice must be text.',
+ 'choice_max' => 'Each poll choice can have up to :max characters. Shorten the longer one.',
+ 'duration_range' => 'A poll can stay open from :min minutes to :max days. Choose a length in that range.',
+ 'choices' => 'Choices',
+ 'choice' => 'Choice :number',
+ 'choice_optional' => 'Choice :number (optional)',
+ 'add_choice' => 'Add a choice',
+ 'remove_choice' => 'Remove choice :number',
+ 'length' => 'Length',
+ 'days' => 'Days',
+ 'hours' => 'Hours',
+ 'minutes' => 'Minutes',
+ 'remove' => 'Remove poll',
+ 'attachments' => 'Polls can\'t have media',
+ 'add' => 'Add a poll',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Document title',
'document_title_placeholder' => 'Shown on your PDF document post',
@@ -786,6 +813,10 @@ return [
'label' => 'Post',
'description' => 'Tweet with text and media',
],
+ 'x_poll' => [
+ 'label' => 'Poll',
+ 'description' => 'Question with :min to :max choices',
+ ],
'threads_post' => [
'label' => 'Thread',
'description' => 'Text post with optional media',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Each media item needs exactly one of upload_token, url or id.',
'media_url_unreachable' => 'Could not fetch media from :url.',
'media_type_unsupported' => 'This file type is not supported by the post\'s channel.',
+ 'media_not_accepted' => 'This post type can\'t include media. Change the post type to add media.',
'media_file_unsupported' => 'This file type is not supported.',
'media_file_too_large' => 'This file is larger than the :size MB allowed for its type.',
'queue_requires_schedule' => 'This channel has no posting times yet. Add posting times in the channel settings to use the queue.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Media options',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count vote|[0,*] :count votes',
+ 'final' => 'Final results',
+ 'ended' => 'Voting ended',
+ 'ends' => 'Ends :time',
+ 'thread_post' => 'Post :number of the thread',
+ ],
+
'publish' => [
'title' => 'Publish',
'all_channels' => 'All channels',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'This was published directly from :network',
'slot_aria' => 'Add a post to :channel on :network at :time',
'no_time' => 'No time',
+ 'pending_slot' => [
+ 'next' => 'Next slot',
+ 'top' => 'Top of queue',
+ ],
'new_in_slot' => 'New',
'add_post_in_slot' => 'Add a post',
'more_times' => 'More times',
diff --git a/lang/es/posts.php b/lang/es/posts.php
index 2a75c3875..90853dc58 100644
--- a/lang/es/posts.php
+++ b/lang/es/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Guardar',
'photo' => 'Foto',
'ghost_expires' => 'Quedan 24 h',
+ 'poll_summary' => '0 votos · termina en :time',
],
'preview_empty' => 'La vista previa de tu publicación aparecerá aquí',
'select_all' => 'Seleccionar todos',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'El tema debe tener entre 1 y 50 caracteres, sin . ni &.',
'ghost_post_attachments' => 'Los posts fantasma no admiten adjuntos',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Añade al menos :min opciones a tu encuesta.',
+ 'options_distinct' => 'Cada opción de la encuesta debe ser distinta. Cambia la repetida.',
+ 'duration_required' => 'Elige cuánto tiempo estará abierta tu encuesta.',
+ 'question_required' => 'Escribe la pregunta de tu encuesta en el texto de la publicación.',
+ 'options_max' => 'Una encuesta puede tener hasta :max opciones. Quita las que sobran.',
+ 'poll_object' => 'Envía la encuesta con sus opciones (options) y su duración (duration_minutes).',
+ 'options_list' => 'Envía las opciones de la encuesta como una lista de textos.',
+ 'choice_text' => 'Cada opción de la encuesta debe ser texto.',
+ 'choice_max' => 'Cada opción de la encuesta puede tener hasta :max caracteres. Acorta la más larga.',
+ 'duration_range' => 'Una encuesta puede estar abierta de :min minutos a :max días. Elige una duración dentro de ese rango.',
+ 'choices' => 'Opciones',
+ 'choice' => 'Opción :number',
+ 'choice_optional' => 'Opción :number (opcional)',
+ 'add_choice' => 'Añadir opción',
+ 'remove_choice' => 'Quitar opción :number',
+ 'length' => 'Duración',
+ 'days' => 'Días',
+ 'hours' => 'Horas',
+ 'minutes' => 'Minutos',
+ 'remove' => 'Quitar encuesta',
+ 'attachments' => 'Las encuestas no admiten contenido multimedia',
+ 'add' => 'Añadir encuesta',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Título del documento',
'document_title_placeholder' => 'Se muestra en tu publicación de documento PDF',
@@ -786,6 +813,10 @@ return [
'label' => 'Post',
'description' => 'Tweet con texto y multimedia',
],
+ 'x_poll' => [
+ 'label' => 'Encuesta',
+ 'description' => 'Pregunta con :min a :max opciones',
+ ],
'threads_post' => [
'label' => 'Hilo',
'description' => 'Post de texto con multimedia opcional',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Cada elemento multimedia necesita exactamente uno de upload_token, url o id.',
'media_url_unreachable' => 'No se pudo obtener el archivo de :url.',
'media_type_unsupported' => 'Este tipo de archivo no es compatible con el canal de la publicación.',
+ 'media_not_accepted' => 'Este tipo de publicación no admite archivos multimedia. Cambia el tipo de publicación para añadirlos.',
'media_file_unsupported' => 'Este tipo de archivo no es compatible.',
'media_file_too_large' => 'Este archivo supera los :size MB permitidos para su tipo.',
'queue_requires_schedule' => 'Este canal aún no tiene horarios de publicación. Añade horarios en los ajustes del canal para usar la cola.',
@@ -921,6 +953,14 @@ return [
'media_title' => 'Opciones de medios',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count voto|[0,*] :count votos',
+ 'final' => 'Resultados finales',
+ 'ended' => 'Votación cerrada',
+ 'ends' => 'Termina :time',
+ 'thread_post' => 'Publicación :number del hilo',
+ ],
+
'publish' => [
'title' => 'Publicar',
'all_channels' => 'Todos los canales',
@@ -954,6 +994,10 @@ return [
'published_directly_from' => 'Publicado directamente desde :network',
'slot_aria' => 'Añadir una publicación a :channel en :network a las :time',
'no_time' => 'Sin hora',
+ 'pending_slot' => [
+ 'next' => 'Próximo hueco',
+ 'top' => 'Al principio',
+ ],
'new_in_slot' => 'Nuevo',
'add_post_in_slot' => 'Añadir post',
'more_times' => 'Más horarios',
diff --git a/lang/fr/posts.php b/lang/fr/posts.php
index afcd6365f..81ec70cbc 100644
--- a/lang/fr/posts.php
+++ b/lang/fr/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Enregistrer',
'photo' => 'Photo',
'ghost_expires' => '24 h restantes',
+ 'poll_summary' => '0 vote · il reste :time',
],
'preview_empty' => 'L’aperçu de votre publication apparaîtra ici',
'select_all' => 'Tout sélectionner',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'Le sujet doit contenir de 1 à 50 caractères, sans . ni &.',
'ghost_post_attachments' => 'Les posts fantômes n\'acceptent pas les pièces jointes',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Ajoutez au moins :min choix à votre sondage.',
+ 'options_distinct' => 'Chaque choix du sondage doit être différent. Modifiez celui qui se répète.',
+ 'duration_required' => 'Choisissez la durée de votre sondage.',
+ 'question_required' => 'Écrivez la question de votre sondage dans le texte du post.',
+ 'options_max' => 'Un sondage peut avoir jusqu\'à :max choix. Retirez ceux en trop.',
+ 'poll_object' => 'Envoyez le sondage avec ses choix (options) et sa durée (duration_minutes).',
+ 'options_list' => 'Envoyez les choix du sondage sous forme de liste de textes.',
+ 'choice_text' => 'Chaque choix du sondage doit être du texte.',
+ 'choice_max' => 'Chaque choix du sondage peut contenir jusqu\'à :max caractères. Raccourcissez le plus long.',
+ 'duration_range' => 'Un sondage peut rester ouvert de :min minutes à :max jours. Choisissez une durée dans cet intervalle.',
+ 'choices' => 'Choix',
+ 'choice' => 'Choix :number',
+ 'choice_optional' => 'Choix :number (facultatif)',
+ 'add_choice' => 'Ajouter un choix',
+ 'remove_choice' => 'Retirer le choix :number',
+ 'length' => 'Durée',
+ 'days' => 'Jours',
+ 'hours' => 'Heures',
+ 'minutes' => 'Minutes',
+ 'remove' => 'Retirer le sondage',
+ 'attachments' => 'Un sondage n\'accepte pas de médias',
+ 'add' => 'Ajouter un sondage',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Titre du document',
'document_title_placeholder' => 'Affiché sur votre publication de document PDF',
@@ -786,6 +813,10 @@ return [
'label' => 'Publication',
'description' => 'Tweet avec texte et médias',
],
+ 'x_poll' => [
+ 'label' => 'Sondage',
+ 'description' => 'Question avec :min à :max choix',
+ ],
'threads_post' => [
'label' => 'Fil',
'description' => 'Publication texte avec média facultatif',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Chaque média doit avoir exactement un seul de ces champs : upload_token, url ou id.',
'media_url_unreachable' => 'Impossible de récupérer le média depuis :url.',
'media_type_unsupported' => 'Ce type de fichier n\'est pas pris en charge par le canal de la publication.',
+ 'media_not_accepted' => 'Ce type de publication n\'accepte pas de médias. Changez le type de publication pour en ajouter.',
'media_file_unsupported' => 'Ce type de fichier n\'est pas pris en charge.',
'media_file_too_large' => 'Ce fichier dépasse les :size Mo autorisés pour son type.',
'queue_requires_schedule' => 'Ce canal n\'a pas encore d\'horaires de publication. Ajoutez-en dans les paramètres du canal pour utiliser la file d\'attente.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Options de médias',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count vote|[0,*] :count votes',
+ 'final' => 'Résultats finaux',
+ 'ended' => 'Vote terminé',
+ 'ends' => 'Se termine :time',
+ 'thread_post' => 'Publication :number du fil',
+ ],
+
'publish' => [
'title' => 'Publier',
'all_channels' => 'Tous les canaux',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Publié directement depuis :network',
'slot_aria' => 'Ajouter une publication à :channel sur :network à :time',
'no_time' => 'Sans heure',
+ 'pending_slot' => [
+ 'next' => 'Créneau libre',
+ 'top' => 'En tête',
+ ],
'new_in_slot' => 'Nouveau',
'add_post_in_slot' => 'Ajouter un post',
'more_times' => 'Plus d\'horaires',
diff --git a/lang/it/posts.php b/lang/it/posts.php
index 99460e6d1..dbefb3110 100644
--- a/lang/it/posts.php
+++ b/lang/it/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Salva',
'photo' => 'Foto',
'ghost_expires' => '24 h rimaste',
+ 'poll_summary' => '0 voti · termina tra :time',
],
'preview_empty' => 'L’anteprima del post apparirà qui',
'select_all' => 'Seleziona tutti',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'L\'argomento deve avere da 1 a 50 caratteri, senza . o &.',
'ghost_post_attachments' => 'I post fantasma non supportano allegati',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Aggiungi almeno :min opzioni al sondaggio.',
+ 'options_distinct' => 'Ogni opzione del sondaggio deve essere diversa. Modifica quella ripetuta.',
+ 'duration_required' => 'Scegli per quanto tempo resta aperto il sondaggio.',
+ 'question_required' => 'Scrivi la domanda del sondaggio nel testo del post.',
+ 'options_max' => 'Un sondaggio può avere fino a :max opzioni. Rimuovi quelle in più.',
+ 'poll_object' => 'Invia il sondaggio con le sue opzioni (options) e la sua durata (duration_minutes).',
+ 'options_list' => 'Invia le opzioni del sondaggio come elenco di testi.',
+ 'choice_text' => 'Ogni opzione del sondaggio deve essere un testo.',
+ 'choice_max' => 'Ogni opzione del sondaggio può avere fino a :max caratteri. Accorcia quella più lunga.',
+ 'duration_range' => 'Un sondaggio può restare aperto da :min minuti a :max giorni. Scegli una durata in questo intervallo.',
+ 'choices' => 'Opzioni',
+ 'choice' => 'Opzione :number',
+ 'choice_optional' => 'Opzione :number (facoltativa)',
+ 'add_choice' => 'Aggiungi opzione',
+ 'remove_choice' => 'Rimuovi opzione :number',
+ 'length' => 'Durata',
+ 'days' => 'Giorni',
+ 'hours' => 'Ore',
+ 'minutes' => 'Minuti',
+ 'remove' => 'Rimuovi sondaggio',
+ 'attachments' => 'I sondaggi non supportano i media',
+ 'add' => 'Aggiungi sondaggio',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Titolo del documento',
'document_title_placeholder' => 'Mostrato sul tuo post con documento PDF',
@@ -786,6 +813,10 @@ return [
'label' => 'Post',
'description' => 'Tweet con testo e media',
],
+ 'x_poll' => [
+ 'label' => 'Sondaggio',
+ 'description' => 'Domanda con :min-:max opzioni',
+ ],
'threads_post' => [
'label' => 'Thread',
'description' => 'Post di testo con media facoltativi',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Ogni elemento multimediale richiede esattamente uno tra upload_token, url o id.',
'media_url_unreachable' => 'Impossibile recuperare il contenuto multimediale da :url.',
'media_type_unsupported' => 'Questo tipo di file non è supportato dal canale del post.',
+ 'media_not_accepted' => 'Questo tipo di post non può includere media. Cambia il tipo di post per aggiungerli.',
'media_file_unsupported' => 'Questo tipo di file non è supportato.',
'media_file_too_large' => 'Questo file supera i :size MB consentiti per il suo tipo.',
'queue_requires_schedule' => 'Questo canale non ha ancora orari di pubblicazione. Aggiungili nelle impostazioni del canale per usare la coda.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Opzioni media',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count voto|[0,*] :count voti',
+ 'final' => 'Risultati finali',
+ 'ended' => 'Votazione chiusa',
+ 'ends' => 'Termina :time',
+ 'thread_post' => 'Post :number del thread',
+ ],
+
'publish' => [
'title' => 'Pubblica',
'all_channels' => 'Tutti i canali',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Pubblicato direttamente da :network',
'slot_aria' => 'Aggiungi un post a :channel su :network alle :time',
'no_time' => 'Nessun orario',
+ 'pending_slot' => [
+ 'next' => 'Prossimo slot',
+ 'top' => 'In cima',
+ ],
'new_in_slot' => 'Nuovo',
'add_post_in_slot' => 'Aggiungi post',
'more_times' => 'Altri orari',
diff --git a/lang/ja/posts.php b/lang/ja/posts.php
index 2d166f5fe..ca2d6ee63 100644
--- a/lang/ja/posts.php
+++ b/lang/ja/posts.php
@@ -157,6 +157,7 @@ return [
'save' => '保存',
'photo' => '写真',
'ghost_expires' => '残り24時間',
+ 'poll_summary' => '0票 · 残り:time',
],
'preview_empty' => '投稿のプレビューがここに表示されます',
'select_all' => 'すべて選択',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'トピックは . と & を含まない1〜50文字にしてください。',
'ghost_post_attachments' => 'ゴースト投稿は添付ファイルに対応していません',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => '投票に選択肢を:minつ以上追加してください。',
+ 'options_distinct' => '投票の選択肢はそれぞれ異なる内容にしてください。重複しているものを変更してください。',
+ 'duration_required' => '投票を受け付ける期間を選んでください。',
+ 'question_required' => '投稿のテキストに投票の質問を書いてください。',
+ 'options_max' => '投票の選択肢は最大:max個までです。余分な選択肢を削除してください。',
+ 'poll_object' => '投票は選択肢(options)と期間(duration_minutes)を含めて送信してください。',
+ 'options_list' => '投票の選択肢はテキストのリストで送信してください。',
+ 'choice_text' => '投票の選択肢はテキストで入力してください。',
+ 'choice_max' => '投票の選択肢はそれぞれ最大:max文字までです。長い選択肢を短くしてください。',
+ 'duration_range' => '投票の期間は:min分から:max日までです。この範囲で期間を選んでください。',
+ 'choices' => '選択肢',
+ 'choice' => '選択肢:number',
+ 'choice_optional' => '選択肢:number(任意)',
+ 'add_choice' => '選択肢を追加',
+ 'remove_choice' => '選択肢:numberを削除',
+ 'length' => '期間',
+ 'days' => '日',
+ 'hours' => '時間',
+ 'minutes' => '分',
+ 'remove' => '投票を削除',
+ 'attachments' => '投票はメディアに対応していません',
+ 'add' => '投票を追加',
+ ],
+ ],
'linkedin' => [
'document_title' => 'ドキュメントタイトル',
'document_title_placeholder' => 'PDF ドキュメント投稿に表示されます',
@@ -786,6 +813,10 @@ return [
'label' => '投稿',
'description' => 'テキストとメディア付きのツイート',
],
+ 'x_poll' => [
+ 'label' => '投票',
+ 'description' => ':min〜:max個の選択肢がある質問',
+ ],
'threads_post' => [
'label' => 'スレッド',
'description' => 'メディア(任意)付きのテキスト投稿',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => '各メディア項目には、upload_token、url、id のいずれか1つだけを指定してください。',
'media_url_unreachable' => ':url からメディアを取得できませんでした。',
'media_type_unsupported' => 'このファイル形式は、投稿のチャンネルでサポートされていません。',
+ 'media_not_accepted' => 'この投稿タイプにはメディアを含められません。メディアを追加するには投稿タイプを変更してください。',
'media_file_unsupported' => 'このファイル形式はサポートされていません。',
'media_file_too_large' => 'このファイルは、その形式で許可されている :size MB を超えています。',
'queue_requires_schedule' => 'このチャンネルにはまだ投稿時間がありません。キューを使うには、チャンネル設定で投稿時間を追加してください。',
@@ -920,6 +952,14 @@ return [
'media_title' => 'メディアオプション',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count票|[0,*] :count票',
+ 'final' => '最終結果',
+ 'ended' => '投票は終了しました',
+ 'ends' => '終了:time',
+ 'thread_post' => 'スレッドの投稿 :number',
+ ],
+
'publish' => [
'title' => '公開',
'all_channels' => '全チャンネル',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => ':network から直接公開されました',
'slot_aria' => ':network の :channel に :time の投稿を追加',
'no_time' => '時間なし',
+ 'pending_slot' => [
+ 'next' => '次の枠',
+ 'top' => '先頭',
+ ],
'new_in_slot' => '新規',
'add_post_in_slot' => '投稿を追加',
'more_times' => 'その他の時間',
diff --git a/lang/ko/posts.php b/lang/ko/posts.php
index 0d0abc5a8..f135996c0 100644
--- a/lang/ko/posts.php
+++ b/lang/ko/posts.php
@@ -157,6 +157,7 @@ return [
'save' => '저장',
'photo' => '사진',
'ghost_expires' => '24시간 남음',
+ 'poll_summary' => '0표 · :time 남음',
],
'preview_empty' => '게시물 미리보기가 여기에 표시됩니다',
'select_all' => '모두 선택',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => '주제는 . 또는 & 없이 1~50자여야 합니다.',
'ghost_post_attachments' => '고스트 게시물은 첨부 파일을 지원하지 않습니다',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => '투표에 선택지를 :min개 이상 추가하세요.',
+ 'options_distinct' => '투표 선택지는 서로 달라야 합니다. 중복된 선택지를 바꿔 주세요.',
+ 'duration_required' => '투표를 얼마나 열어 둘지 선택하세요.',
+ 'question_required' => '게시물 텍스트에 투표 질문을 작성해 주세요.',
+ 'options_max' => '투표 선택지는 최대 :max개까지 추가할 수 있습니다. 남는 선택지를 삭제하세요.',
+ 'poll_object' => '투표를 선택지(options)와 기간(duration_minutes)과 함께 보내 주세요.',
+ 'options_list' => '투표 선택지를 텍스트 목록으로 보내 주세요.',
+ 'choice_text' => '투표 선택지는 텍스트여야 합니다.',
+ 'choice_max' => '투표 선택지는 각각 최대 :max자까지 입력할 수 있습니다. 긴 선택지를 줄여 주세요.',
+ 'duration_range' => '투표는 :min분에서 :max일까지 열어 둘 수 있습니다. 이 범위 안에서 기간을 선택하세요.',
+ 'choices' => '선택지',
+ 'choice' => '선택지 :number',
+ 'choice_optional' => '선택지 :number (선택 사항)',
+ 'add_choice' => '선택지 추가',
+ 'remove_choice' => '선택지 :number 삭제',
+ 'length' => '기간',
+ 'days' => '일',
+ 'hours' => '시간',
+ 'minutes' => '분',
+ 'remove' => '투표 삭제',
+ 'attachments' => '투표는 미디어를 지원하지 않습니다',
+ 'add' => '투표 추가',
+ ],
+ ],
'linkedin' => [
'document_title' => '문서 제목',
'document_title_placeholder' => 'PDF 문서 게시물에 표시됩니다',
@@ -786,6 +813,10 @@ return [
'label' => '게시물',
'description' => '텍스트와 미디어가 있는 트윗',
],
+ 'x_poll' => [
+ 'label' => '투표',
+ 'description' => '선택지 :min~:max개가 있는 질문',
+ ],
'threads_post' => [
'label' => '스레드',
'description' => '선택적 미디어가 있는 텍스트 게시물',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => '각 미디어 항목에는 upload_token, url, id 중 정확히 하나가 필요합니다.',
'media_url_unreachable' => ':url에서 미디어를 가져올 수 없습니다.',
'media_type_unsupported' => '이 파일 형식은 게시물의 채널에서 지원되지 않습니다.',
+ 'media_not_accepted' => '이 게시물 유형에는 미디어를 포함할 수 없습니다. 미디어를 추가하려면 게시물 유형을 변경하세요.',
'media_file_unsupported' => '이 파일 형식은 지원되지 않습니다.',
'media_file_too_large' => '이 파일은 해당 형식에 허용된 :size MB를 초과합니다.',
'queue_requires_schedule' => '이 채널에는 아직 게시 시간이 없습니다. 대기열을 사용하려면 채널 설정에서 게시 시간을 추가하세요.',
@@ -920,6 +952,14 @@ return [
'media_title' => '미디어 옵션',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count표|[0,*] :count표',
+ 'final' => '최종 결과',
+ 'ended' => '투표 종료',
+ 'ends' => '종료 :time',
+ 'thread_post' => '스레드의 게시물 :number',
+ ],
+
'publish' => [
'title' => '게시',
'all_channels' => '모든 채널',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => ':network에서 직접 게시됨',
'slot_aria' => ':network의 :channel에 :time 게시물 추가',
'no_time' => '시간 없음',
+ 'pending_slot' => [
+ 'next' => '다음 슬롯',
+ 'top' => '맨 앞',
+ ],
'new_in_slot' => '신규',
'add_post_in_slot' => '게시물 추가',
'more_times' => '더 많은 시간',
diff --git a/lang/nl/posts.php b/lang/nl/posts.php
index 4d505f24e..0fee5cf0d 100644
--- a/lang/nl/posts.php
+++ b/lang/nl/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Bewaren',
'photo' => 'Foto',
'ghost_expires' => 'Nog 24 u',
+ 'poll_summary' => '0 stemmen · nog :time',
],
'preview_empty' => 'Je berichtvoorbeeld verschijnt hier',
'select_all' => 'Alles selecteren',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'Het onderwerp moet 1 tot 50 tekens hebben, zonder . of &.',
'ghost_post_attachments' => 'Ghost-posts ondersteunen geen bijlagen',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Voeg minstens :min keuzes toe aan je poll.',
+ 'options_distinct' => 'Elke keuze in de poll moet anders zijn. Pas de dubbele aan.',
+ 'duration_required' => 'Kies hoe lang je poll openstaat.',
+ 'question_required' => 'Schrijf de vraag van je poll in de tekst van het bericht.',
+ 'options_max' => 'Een poll kan maximaal :max keuzes hebben. Verwijder de overige.',
+ 'poll_object' => 'Stuur de poll met de keuzes (options) en de duur (duration_minutes).',
+ 'options_list' => 'Stuur de keuzes van de poll als een lijst met tekst.',
+ 'choice_text' => 'Elke keuze in de poll moet tekst zijn.',
+ 'choice_max' => 'Elke keuze in de poll mag maximaal :max tekens hebben. Maak de langere korter.',
+ 'duration_range' => 'Een poll kan van :min minuten tot :max dagen openstaan. Kies een duur binnen dat bereik.',
+ 'choices' => 'Keuzes',
+ 'choice' => 'Keuze :number',
+ 'choice_optional' => 'Keuze :number (optioneel)',
+ 'add_choice' => 'Keuze toevoegen',
+ 'remove_choice' => 'Keuze :number verwijderen',
+ 'length' => 'Duur',
+ 'days' => 'Dagen',
+ 'hours' => 'Uren',
+ 'minutes' => 'Minuten',
+ 'remove' => 'Poll verwijderen',
+ 'attachments' => 'Een poll ondersteunt geen media',
+ 'add' => 'Poll toevoegen',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Documenttitel',
'document_title_placeholder' => 'Getoond op je PDF-documentpost',
@@ -786,6 +813,10 @@ return [
'label' => 'Post',
'description' => 'Tweet met tekst en media',
],
+ 'x_poll' => [
+ 'label' => 'Poll',
+ 'description' => 'Vraag met :min tot :max keuzes',
+ ],
'threads_post' => [
'label' => 'Thread',
'description' => 'Tekstpost met optionele media',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Elk media-item heeft precies één van upload_token, url of id nodig.',
'media_url_unreachable' => 'Media kon niet worden opgehaald van :url.',
'media_type_unsupported' => 'Dit bestandstype wordt niet ondersteund door het kanaal van de post.',
+ 'media_not_accepted' => 'Dit type post kan geen media bevatten. Wijzig het type post om media toe te voegen.',
'media_file_unsupported' => 'Dit bestandstype wordt niet ondersteund.',
'media_file_too_large' => 'Dit bestand is groter dan de :size MB die voor dit type is toegestaan.',
'queue_requires_schedule' => 'Dit kanaal heeft nog geen publicatietijden. Voeg tijden toe in de kanaalinstellingen om de wachtrij te gebruiken.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Media-opties',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count stem|[0,*] :count stemmen',
+ 'final' => 'Eindresultaat',
+ 'ended' => 'Stemmen gesloten',
+ 'ends' => 'Eindigt :time',
+ 'thread_post' => 'Bericht :number van de thread',
+ ],
+
'publish' => [
'title' => 'Publiceren',
'all_channels' => 'Alle kanalen',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Rechtstreeks gepubliceerd vanuit :network',
'slot_aria' => 'Bericht toevoegen aan :channel op :network om :time',
'no_time' => 'Geen tijd',
+ 'pending_slot' => [
+ 'next' => 'Volgend slot',
+ 'top' => 'Bovenaan',
+ ],
'new_in_slot' => 'Nieuw',
'add_post_in_slot' => 'Post toevoegen',
'more_times' => 'Meer tijden',
diff --git a/lang/pl/posts.php b/lang/pl/posts.php
index c7bdf269a..5228d1eec 100644
--- a/lang/pl/posts.php
+++ b/lang/pl/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Zapisz',
'photo' => 'Zdjęcie',
'ghost_expires' => 'Zostało 24 h',
+ 'poll_summary' => '0 głosów · pozostało: :time',
],
'preview_empty' => 'Podgląd posta pojawi się tutaj',
'select_all' => 'Zaznacz wszystkie',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'Temat musi mieć od 1 do 50 znaków, bez . i &.',
'ghost_post_attachments' => 'Posty-duchy nie obsługują załączników',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Dodaj do ankiety co najmniej :min opcje.',
+ 'options_distinct' => 'Każda opcja ankiety musi być inna. Zmień powtórzoną.',
+ 'duration_required' => 'Wybierz, jak długo ankieta ma być otwarta.',
+ 'question_required' => 'Wpisz pytanie ankiety w treści posta.',
+ 'options_max' => 'Ankieta może mieć maksymalnie :max opcje. Usuń nadmiarowe.',
+ 'poll_object' => 'Wyślij ankietę z opcjami (options) i czasem trwania (duration_minutes).',
+ 'options_list' => 'Wyślij opcje ankiety jako listę tekstów.',
+ 'choice_text' => 'Każda opcja ankiety musi być tekstem.',
+ 'choice_max' => 'Każda opcja ankiety może mieć maksymalnie :max znaków. Skróć dłuższą.',
+ 'duration_range' => 'Ankieta może być otwarta od :min minut do :max dni. Wybierz czas trwania w tym zakresie.',
+ 'choices' => 'Opcje',
+ 'choice' => 'Opcja :number',
+ 'choice_optional' => 'Opcja :number (opcjonalna)',
+ 'add_choice' => 'Dodaj opcję',
+ 'remove_choice' => 'Usuń opcję :number',
+ 'length' => 'Czas trwania',
+ 'days' => 'Dni',
+ 'hours' => 'Godziny',
+ 'minutes' => 'Minuty',
+ 'remove' => 'Usuń ankietę',
+ 'attachments' => 'Ankieta nie obsługuje multimediów',
+ 'add' => 'Dodaj ankietę',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Tytuł dokumentu',
'document_title_placeholder' => 'Wyświetlany w Twoim poście z dokumentem PDF',
@@ -786,6 +813,10 @@ return [
'label' => 'Post',
'description' => 'Tweet z tekstem i multimediami',
],
+ 'x_poll' => [
+ 'label' => 'Ankieta',
+ 'description' => 'Pytanie z :min do :max opcjami',
+ ],
'threads_post' => [
'label' => 'Wątek',
'description' => 'Post tekstowy z opcjonalnymi multimediami',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Każdy element multimedialny wymaga dokładnie jednego z pól: upload_token, url lub id.',
'media_url_unreachable' => 'Nie udało się pobrać multimediów z :url.',
'media_type_unsupported' => 'Ten typ pliku nie jest obsługiwany przez kanał posta.',
+ 'media_not_accepted' => 'Ten typ posta nie może zawierać multimediów. Zmień typ posta, aby je dodać.',
'media_file_unsupported' => 'Ten typ pliku nie jest obsługiwany.',
'media_file_too_large' => 'Ten plik jest większy niż dozwolone dla jego typu :size MB.',
'queue_requires_schedule' => 'Ten kanał nie ma jeszcze godzin publikacji. Dodaj je w ustawieniach kanału, aby korzystać z kolejki.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Opcje multimediów',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count głos|[0,*] Głosów: :count',
+ 'final' => 'Wyniki końcowe',
+ 'ended' => 'Głosowanie zakończone',
+ 'ends' => 'Kończy się :time',
+ 'thread_post' => 'Post :number w wątku',
+ ],
+
'publish' => [
'title' => 'Publikuj',
'all_channels' => 'Wszystkie kanały',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Opublikowano bezpośrednio w :network',
'slot_aria' => 'Dodaj post do :channel w :network o :time',
'no_time' => 'Bez godziny',
+ 'pending_slot' => [
+ 'next' => 'Następny slot',
+ 'top' => 'Na początku',
+ ],
'new_in_slot' => 'Nowy',
'add_post_in_slot' => 'Dodaj post',
'more_times' => 'Więcej godzin',
diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php
index 4c2e791a8..034a63ba0 100644
--- a/lang/pt-BR/posts.php
+++ b/lang/pt-BR/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Salvar',
'photo' => 'Foto',
'ghost_expires' => '24h restantes',
+ 'poll_summary' => '0 votos · termina em :time',
],
'preview_empty' => 'A prévia da publicação aparecerá aqui',
'select_all' => 'Selecionar todos',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'O tópico deve ter de 1 a 50 caracteres, sem . ou &.',
'ghost_post_attachments' => 'Posts fantasma não aceitam anexos',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Adicione pelo menos :min opções à sua enquete.',
+ 'options_distinct' => 'Cada opção da enquete precisa ser diferente. Altere a repetida.',
+ 'duration_required' => 'Escolha por quanto tempo sua enquete fica aberta.',
+ 'question_required' => 'Escreva a pergunta da sua enquete no texto do post.',
+ 'options_max' => 'Uma enquete pode ter até :max opções. Remova as que sobram.',
+ 'poll_object' => 'Envie a enquete com as opções (options) e a duração (duration_minutes).',
+ 'options_list' => 'Envie as opções da enquete como uma lista de textos.',
+ 'choice_text' => 'Cada opção da enquete precisa ser um texto.',
+ 'choice_max' => 'Cada opção da enquete pode ter até :max caracteres. Encurte a mais longa.',
+ 'duration_range' => 'Uma enquete pode ficar aberta de :min minutos a :max dias. Escolha uma duração nesse intervalo.',
+ 'choices' => 'Opções',
+ 'choice' => 'Opção :number',
+ 'choice_optional' => 'Opção :number (opcional)',
+ 'add_choice' => 'Adicionar opção',
+ 'remove_choice' => 'Remover opção :number',
+ 'length' => 'Duração',
+ 'days' => 'Dias',
+ 'hours' => 'Horas',
+ 'minutes' => 'Minutos',
+ 'remove' => 'Remover enquete',
+ 'attachments' => 'Enquetes não aceitam mídia',
+ 'add' => 'Adicionar enquete',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Título do documento',
'document_title_placeholder' => 'Aparece no seu post de documento PDF',
@@ -786,6 +813,10 @@ return [
'label' => 'Post',
'description' => 'Tweet com texto e mídia',
],
+ 'x_poll' => [
+ 'label' => 'Enquete',
+ 'description' => 'Pergunta com :min a :max opções',
+ ],
'threads_post' => [
'label' => 'Thread',
'description' => 'Post de texto com mídia opcional',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Cada item de mídia precisa de exatamente um entre upload_token, url ou id.',
'media_url_unreachable' => 'Não foi possível buscar a mídia em :url.',
'media_type_unsupported' => 'Este tipo de arquivo não é compatível com o canal do post.',
+ 'media_not_accepted' => 'Este tipo de post não aceita mídia. Mude o tipo de post para adicionar mídia.',
'media_file_unsupported' => 'Este tipo de arquivo não é compatível.',
'media_file_too_large' => 'Este arquivo é maior que os :size MB permitidos para o tipo dele.',
'queue_requires_schedule' => 'Este canal ainda não tem horários de postagem. Adicione horários nas configurações do canal para usar a fila.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Opções de mídia',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count voto|[0,*] :count votos',
+ 'final' => 'Resultado final',
+ 'ended' => 'Votação encerrada',
+ 'ends' => 'Termina :time',
+ 'thread_post' => 'Post :number da sequência',
+ ],
+
'publish' => [
'title' => 'Publicar',
'all_channels' => 'Todos os canais',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Publicado diretamente pelo :network',
'slot_aria' => 'Adicionar um post em :channel no :network às :time',
'no_time' => 'Sem horário',
+ 'pending_slot' => [
+ 'next' => 'Próxima vaga',
+ 'top' => 'Topo da fila',
+ ],
'new_in_slot' => 'Novo',
'add_post_in_slot' => 'Adicionar post',
'more_times' => 'Mais horários',
diff --git a/lang/ru/posts.php b/lang/ru/posts.php
index 3382abe01..58998fca7 100644
--- a/lang/ru/posts.php
+++ b/lang/ru/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Сохранить',
'photo' => 'Фото',
'ghost_expires' => 'Осталось 24 ч',
+ 'poll_summary' => '0 голосов · осталось: :time',
],
'preview_empty' => 'Предпросмотр публикации появится здесь',
'select_all' => 'Выбрать все',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'Тема должна содержать от 1 до 50 символов, без . и &.',
'ghost_post_attachments' => 'Посты-призраки не поддерживают вложения',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Добавьте в опрос хотя бы :min варианта.',
+ 'options_distinct' => 'Варианты ответа должны отличаться. Измените повторяющийся.',
+ 'duration_required' => 'Выберите, как долго опрос будет открыт.',
+ 'question_required' => 'Напишите вопрос опроса в тексте поста.',
+ 'options_max' => 'В опросе может быть не больше :max вариантов. Удалите лишние.',
+ 'poll_object' => 'Отправьте опрос с вариантами (options) и длительностью (duration_minutes).',
+ 'options_list' => 'Отправьте варианты опроса списком текстов.',
+ 'choice_text' => 'Каждый вариант опроса должен быть текстом.',
+ 'choice_max' => 'Каждый вариант опроса может содержать не больше :max символов. Сократите длинный.',
+ 'duration_range' => 'Опрос может быть открыт от :min минут до :max дней. Выберите длительность в этом диапазоне.',
+ 'choices' => 'Варианты',
+ 'choice' => 'Вариант :number',
+ 'choice_optional' => 'Вариант :number (необязательно)',
+ 'add_choice' => 'Добавить вариант',
+ 'remove_choice' => 'Удалить вариант :number',
+ 'length' => 'Длительность',
+ 'days' => 'Дни',
+ 'hours' => 'Часы',
+ 'minutes' => 'Минуты',
+ 'remove' => 'Удалить опрос',
+ 'attachments' => 'Опрос не поддерживает медиа',
+ 'add' => 'Добавить опрос',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Название документа',
'document_title_placeholder' => 'Отображается в вашем посте с PDF-документом',
@@ -786,6 +813,10 @@ return [
'label' => 'Пост',
'description' => 'Твит с текстом и медиа',
],
+ 'x_poll' => [
+ 'label' => 'Опрос',
+ 'description' => 'Вопрос с :min–:max вариантами',
+ ],
'threads_post' => [
'label' => 'Тред',
'description' => 'Текстовый пост с опциональным медиа',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Каждому медиафайлу нужно ровно одно из полей: upload_token, url или id.',
'media_url_unreachable' => 'Не удалось получить медиафайл по адресу :url.',
'media_type_unsupported' => 'Этот тип файла не поддерживается каналом публикации.',
+ 'media_not_accepted' => 'Этот тип публикации не поддерживает медиафайлы. Измените тип публикации, чтобы добавить их.',
'media_file_unsupported' => 'Этот тип файла не поддерживается.',
'media_file_too_large' => 'Этот файл больше допустимых для его типа :size МБ.',
'queue_requires_schedule' => 'У этого канала пока нет времени публикации. Добавьте время в настройках канала, чтобы использовать очередь.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Параметры медиа',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count голос|[0,*] Голосов: :count',
+ 'final' => 'Итоговые результаты',
+ 'ended' => 'Голосование завершено',
+ 'ends' => 'Завершится :time',
+ 'thread_post' => 'Пост :number в цепочке',
+ ],
+
'publish' => [
'title' => 'Публикация',
'all_channels' => 'Все каналы',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Опубликовано напрямую из :network',
'slot_aria' => 'Добавить пост в :channel в :network на :time',
'no_time' => 'Без времени',
+ 'pending_slot' => [
+ 'next' => 'Первый слот',
+ 'top' => 'В начале',
+ ],
'new_in_slot' => 'Новый',
'add_post_in_slot' => 'Добавить пост',
'more_times' => 'Другое время',
diff --git a/lang/tr/posts.php b/lang/tr/posts.php
index 852691262..b44663e75 100644
--- a/lang/tr/posts.php
+++ b/lang/tr/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Kaydet',
'photo' => 'Fotoğraf',
'ghost_expires' => '24 sa kaldı',
+ 'poll_summary' => '0 oy · :time kaldı',
],
'preview_empty' => 'Gönderi önizlemen burada görünecek',
'select_all' => 'Tümünü seç',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'Konu . veya & içermeden 1 ile 50 karakter arasında olmalıdır.',
'ghost_post_attachments' => 'Hayalet gönderiler ek desteklemez',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Anketine en az :min seçenek ekle.',
+ 'options_distinct' => 'Anket seçeneklerinin her biri farklı olmalı. Tekrar eden seçeneği değiştir.',
+ 'duration_required' => 'Anketinin ne kadar açık kalacağını seç.',
+ 'question_required' => 'Anket sorunu gönderi metnine yaz.',
+ 'options_max' => 'Bir ankette en fazla :max seçenek olabilir. Fazla olanları kaldır.',
+ 'poll_object' => 'Anketi seçenekleri (options) ve süresiyle (duration_minutes) birlikte gönder.',
+ 'options_list' => 'Anket seçeneklerini metin listesi olarak gönder.',
+ 'choice_text' => 'Her anket seçeneği metin olmalı.',
+ 'choice_max' => 'Her anket seçeneği en fazla :max karakter olabilir. Uzun olanı kısalt.',
+ 'duration_range' => 'Bir anket :min dakikadan :max güne kadar açık kalabilir. Bu aralıkta bir süre seç.',
+ 'choices' => 'Seçenekler',
+ 'choice' => 'Seçenek :number',
+ 'choice_optional' => 'Seçenek :number (isteğe bağlı)',
+ 'add_choice' => 'Seçenek ekle',
+ 'remove_choice' => ':number. seçeneği kaldır',
+ 'length' => 'Süre',
+ 'days' => 'Gün',
+ 'hours' => 'Saat',
+ 'minutes' => 'Dakika',
+ 'remove' => 'Anketi kaldır',
+ 'attachments' => 'Anketler medya desteklemiyor',
+ 'add' => 'Anket ekle',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Belge başlığı',
'document_title_placeholder' => 'PDF belge gönderinizde gösterilir',
@@ -786,6 +813,10 @@ return [
'label' => 'Gönderi',
'description' => 'Metin ve medya içeren tweet',
],
+ 'x_poll' => [
+ 'label' => 'Anket',
+ 'description' => ':min ila :max seçenekli soru',
+ ],
'threads_post' => [
'label' => 'Flood',
'description' => 'İsteğe bağlı medya içeren metin gönderisi',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Her medya öğesi upload_token, url veya id alanlarından tam olarak birini içermelidir.',
'media_url_unreachable' => 'Medya :url adresinden alınamadı.',
'media_type_unsupported' => 'Bu dosya türü, gönderinin kanalı tarafından desteklenmiyor.',
+ 'media_not_accepted' => 'Bu gönderi türü medya içeremez. Medya eklemek için gönderi türünü değiştirin.',
'media_file_unsupported' => 'Bu dosya türü desteklenmiyor.',
'media_file_too_large' => 'Bu dosya, türü için izin verilen :size MB sınırını aşıyor.',
'queue_requires_schedule' => 'Bu kanalın henüz paylaşım saati yok. Kuyruğu kullanmak için kanal ayarlarından paylaşım saatleri ekleyin.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Medya seçenekleri',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count oy|[0,*] :count oy',
+ 'final' => 'Nihai sonuçlar',
+ 'ended' => 'Oylama sona erdi',
+ 'ends' => 'Bitiş: :time',
+ 'thread_post' => 'Zincirin :number. gönderisi',
+ ],
+
'publish' => [
'title' => 'Yayınla',
'all_channels' => 'Tüm kanallar',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Doğrudan :network üzerinden yayınlandı',
'slot_aria' => ':network üzerindeki :channel için :time saatine gönderi ekle',
'no_time' => 'Saat yok',
+ 'pending_slot' => [
+ 'next' => 'Sonraki slot',
+ 'top' => 'En başta',
+ ],
'new_in_slot' => 'Yeni',
'add_post_in_slot' => 'Gönderi ekle',
'more_times' => 'Daha fazla saat',
diff --git a/lang/uk/posts.php b/lang/uk/posts.php
index 86ebcc6f3..152713511 100644
--- a/lang/uk/posts.php
+++ b/lang/uk/posts.php
@@ -157,6 +157,7 @@ return [
'save' => 'Зберегти',
'photo' => 'Фото',
'ghost_expires' => 'Залишилось 24 год',
+ 'poll_summary' => '0 голосів · залишилося: :time',
],
'preview_empty' => 'Попередній перегляд допису з’явиться тут',
'select_all' => 'Вибрати всі',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => 'Тема має містити від 1 до 50 символів, без . і &.',
'ghost_post_attachments' => 'Пости-привиди не підтримують вкладення',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => 'Додайте в опитування щонайменше :min варіанти.',
+ 'options_distinct' => 'Варіанти відповіді мають відрізнятися. Змініть той, що повторюється.',
+ 'duration_required' => 'Виберіть, як довго опитування буде відкритим.',
+ 'question_required' => 'Напишіть питання опитування в тексті допису.',
+ 'options_max' => 'В опитуванні може бути не більше :max варіантів. Видаліть зайві.',
+ 'poll_object' => 'Надішліть опитування з варіантами (options) і тривалістю (duration_minutes).',
+ 'options_list' => 'Надішліть варіанти опитування списком текстів.',
+ 'choice_text' => 'Кожен варіант опитування має бути текстом.',
+ 'choice_max' => 'Кожен варіант опитування може містити не більше :max символів. Скоротіть довший.',
+ 'duration_range' => 'Опитування може бути відкритим від :min хвилин до :max днів. Виберіть тривалість у цьому діапазоні.',
+ 'choices' => 'Варіанти',
+ 'choice' => 'Варіант :number',
+ 'choice_optional' => 'Варіант :number (необов’язково)',
+ 'add_choice' => 'Додати варіант',
+ 'remove_choice' => 'Видалити варіант :number',
+ 'length' => 'Тривалість',
+ 'days' => 'Дні',
+ 'hours' => 'Години',
+ 'minutes' => 'Хвилини',
+ 'remove' => 'Видалити опитування',
+ 'attachments' => 'Опитування не підтримує медіа',
+ 'add' => 'Додати опитування',
+ ],
+ ],
'linkedin' => [
'document_title' => 'Назва документа',
'document_title_placeholder' => 'Відображається у вашому пості з PDF-документом',
@@ -786,6 +813,10 @@ return [
'label' => 'Пост',
'description' => 'Твіт із текстом та медіа',
],
+ 'x_poll' => [
+ 'label' => 'Опитування',
+ 'description' => 'Питання з :min–:max варіантами',
+ ],
'threads_post' => [
'label' => 'Тред',
'description' => 'Текстовий пост із необов’язковим медіа',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => 'Кожному медіафайлу потрібне рівно одне з полів: upload_token, url або id.',
'media_url_unreachable' => 'Не вдалося отримати медіафайл за адресою :url.',
'media_type_unsupported' => 'Цей тип файлу не підтримується каналом публікації.',
+ 'media_not_accepted' => 'Цей тип публікації не підтримує медіафайли. Змініть тип публікації, щоб додати їх.',
'media_file_unsupported' => 'Цей тип файлу не підтримується.',
'media_file_too_large' => 'Цей файл більший за дозволені для його типу :size МБ.',
'queue_requires_schedule' => 'Цей канал ще не має часу публікації. Додайте час у налаштуваннях каналу, щоб користуватися чергою.',
@@ -920,6 +952,14 @@ return [
'media_title' => 'Параметри медіа',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count голос|[0,*] Голосів: :count',
+ 'final' => 'Остаточні результати',
+ 'ended' => 'Голосування завершено',
+ 'ends' => 'Завершиться :time',
+ 'thread_post' => 'Допис :number у ланцюжку',
+ ],
+
'publish' => [
'title' => 'Публікація',
'all_channels' => 'Усі канали',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => 'Опубліковано напряму з :network',
'slot_aria' => 'Додати допис до :channel у :network на :time',
'no_time' => 'Без часу',
+ 'pending_slot' => [
+ 'next' => 'Перший слот',
+ 'top' => 'На початку',
+ ],
'new_in_slot' => 'Новий',
'add_post_in_slot' => 'Додати допис',
'more_times' => 'Інший час',
diff --git a/lang/zh/posts.php b/lang/zh/posts.php
index 7b27afc9a..d0a688868 100644
--- a/lang/zh/posts.php
+++ b/lang/zh/posts.php
@@ -157,6 +157,7 @@ return [
'save' => '保存',
'photo' => '照片',
'ghost_expires' => '剩余 24 小时',
+ 'poll_summary' => '0 票 · 剩余 :time',
],
'preview_empty' => '帖子预览将显示在这里',
'select_all' => '全选',
@@ -407,6 +408,32 @@ return [
'topic_invalid' => '话题须为 1 到 50 个字符,且不含 . 或 &。',
'ghost_post_attachments' => '幽灵帖子不支持附件',
],
+ 'x' => [
+ 'poll' => [
+ 'options_required' => '请为投票至少添加 :min 个选项。',
+ 'options_distinct' => '每个投票选项必须不同,请修改重复的选项。',
+ 'duration_required' => '请选择投票的开放时长。',
+ 'question_required' => '请在帖子正文中写下投票问题。',
+ 'options_max' => '投票最多可以有 :max 个选项。请删除多余的选项。',
+ 'poll_object' => '请发送包含选项(options)和时长(duration_minutes)的投票。',
+ 'options_list' => '请以文本列表的形式发送投票选项。',
+ 'choice_text' => '每个投票选项都必须是文本。',
+ 'choice_max' => '每个投票选项最多 :max 个字符。请缩短较长的选项。',
+ 'duration_range' => '投票可开放 :min 分钟到 :max 天。请在此范围内选择时长。',
+ 'choices' => '选项',
+ 'choice' => '选项 :number',
+ 'choice_optional' => '选项 :number(可选)',
+ 'add_choice' => '添加选项',
+ 'remove_choice' => '删除选项 :number',
+ 'length' => '时长',
+ 'days' => '天',
+ 'hours' => '小时',
+ 'minutes' => '分钟',
+ 'remove' => '删除投票',
+ 'attachments' => '投票不支持媒体',
+ 'add' => '添加投票',
+ ],
+ ],
'linkedin' => [
'document_title' => '文档标题',
'document_title_placeholder' => '显示在你的 PDF 文档帖子上',
@@ -786,6 +813,10 @@ return [
'label' => '帖子',
'description' => '带文字和媒体的推文',
],
+ 'x_poll' => [
+ 'label' => '投票',
+ 'description' => '带 :min 到 :max 个选项的问题',
+ ],
'threads_post' => [
'label' => '串文',
'description' => '可附带媒体的文字帖子',
@@ -856,6 +887,7 @@ return [
'media_item_shape' => '每个媒体项必须且只能提供 upload_token、url 或 id 中的一个。',
'media_url_unreachable' => '无法从 :url 获取媒体。',
'media_type_unsupported' => '帖子的频道不支持此文件类型。',
+ 'media_not_accepted' => '此帖子类型不能包含媒体。请更改帖子类型以添加媒体。',
'media_file_unsupported' => '不支持此文件类型。',
'media_file_too_large' => '此文件超过其类型允许的 :size MB。',
'queue_requires_schedule' => '此频道尚未设置发布时间。请在频道设置中添加发布时间以使用队列。',
@@ -920,6 +952,14 @@ return [
'media_title' => '媒体选项',
],
],
+ 'poll_results' => [
+ 'votes' => '{1} :count 票|[0,*] :count 票',
+ 'final' => '最终结果',
+ 'ended' => '投票已结束',
+ 'ends' => ':time结束',
+ 'thread_post' => '帖子串中的第 :number 条',
+ ],
+
'publish' => [
'title' => '发布',
'all_channels' => '所有频道',
@@ -953,6 +993,10 @@ return [
'published_directly_from' => '直接从 :network 发布',
'slot_aria' => '在 :time 为 :network 上的 :channel 添加帖子',
'no_time' => '无时间',
+ 'pending_slot' => [
+ 'next' => '下一个空档',
+ 'top' => '队首',
+ ],
'new_in_slot' => '新建',
'add_post_in_slot' => '添加帖子',
'more_times' => '更多时间',
diff --git a/resources/js/components/ChannelConfigurator.vue b/resources/js/components/ChannelConfigurator.vue
index 3f4750a5a..519f269df 100644
--- a/resources/js/components/ChannelConfigurator.vue
+++ b/resources/js/components/ChannelConfigurator.vue
@@ -13,10 +13,12 @@ import YouTubeSettings from '@/components/posts/editor/YouTubeSettings.vue';
import { Switch } from '@/components/ui/switch';
import { isDocumentMedia } from '@/composables/useMedia';
import {
+ type ContentTypeOption,
getContentTypeOptions,
getPlatformLabel,
} from '@/composables/usePlatformLogo';
import type { Channel } from '@/types/channel';
+import { ContentType } from '@/types/content-type';
import type { MediaItem } from '@/types/media';
import { Platform } from '@/types/platform';
@@ -60,8 +62,17 @@ const hasDocument = computed(() =>
props.media.some((item) => isDocumentMedia(item)),
);
+/** A repurpose publishes the source's media, so it never offers an X poll, which takes none. */
+const repurposeContentTypes = (platform: string): ContentTypeOption[] =>
+ getContentTypeOptions(platform).filter(
+ (option) => option.value !== ContentType.XPoll,
+ );
+
+const offersContentTypeChoice = (channel: Channel): boolean =>
+ repurposeContentTypes(channel.platform).length > 1;
+
const hasSettingsCard = (channel: Channel): boolean =>
- getContentTypeOptions(channel.platform).length > 1 ||
+ offersContentTypeChoice(channel) ||
channel.platform === Platform.Instagram ||
channel.platform === Platform.InstagramFacebook ||
SETTINGS_PLATFORMS.includes(channel.platform) ||
@@ -152,8 +163,8 @@ const settingsIndex = (channel: Channel): number =>
:data-testid="`channel-settings-${channel.id}`"
>
<ContentTypeRadioGroup
- v-if="getContentTypeOptions(channel.platform).length > 1"
- :options="getContentTypeOptions(channel.platform)"
+ v-if="offersContentTypeChoice(channel)"
+ :options="repurposeContentTypes(channel.platform)"
:model-value="channel.contentType"
:test-id-prefix="`channel-type-${channel.id}`"
:disabled="disabled"
diff --git a/resources/js/components/ai/WritingAssistantPanel.vue b/resources/js/components/ai/WritingAssistantPanel.vue
index a11dbfca0..22b7e9f9b 100644
--- a/resources/js/components/ai/WritingAssistantPanel.vue
+++ b/resources/js/components/ai/WritingAssistantPanel.vue
@@ -24,6 +24,7 @@ import { assist } from '@/routes/app/posts/ai';
export type AssistantChannel = {
accountId: string;
platform: string;
+ contentType: string | null;
label: string;
limit: number | null;
};
@@ -69,6 +70,7 @@ const http = useHttp({
previous_content: '',
platform: null as string | null,
social_account_id: null as string | null,
+ content_type: null as string | null,
});
onBeforeUnmount(() => {
@@ -107,6 +109,7 @@ const request = async (
http.previous_content = payload.previous_content ?? '';
http.platform = props.channel?.platform ?? null;
http.social_account_id = props.channel?.accountId ?? null;
+ http.content_type = props.channel?.contentType ?? null;
try {
const result = (await http.post(assist.url())) as
| { content: string }
diff --git a/resources/js/components/posts/ThreadView.vue b/resources/js/components/posts/ThreadView.vue
index d9ed4c3c1..60d5c6748 100644
--- a/resources/js/components/posts/ThreadView.vue
+++ b/resources/js/components/posts/ThreadView.vue
@@ -77,6 +77,7 @@ const openMedia = (items: MediaItem[], index: number): void => {
:test-key="`${testKey}-${index}`"
@open="openMedia(post.media, $event)"
/>
+ <slot name="post-end" :index="index" />
</div>
</li>
</ol>
diff --git a/resources/js/components/posts/composer/ComposerEditorToolbar.vue b/resources/js/components/posts/composer/ComposerEditorToolbar.vue
index fc1955258..4d5e787fd 100644
--- a/resources/js/components/posts/composer/ComposerEditorToolbar.vue
+++ b/resources/js/components/posts/composer/ComposerEditorToolbar.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { IconMoodSmile, IconSignature } from '@tabler/icons-vue';
+import { IconListDetails, IconMoodSmile, IconSignature } from '@tabler/icons-vue';
import { ref } from 'vue';
import MediaSourceMenu from '@/components/posts/composer/MediaSourceMenu.vue';
@@ -10,20 +10,38 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
withDefaults(
defineProps<{
testIdPrefix: string;
signatures: { id: string; name: string; content: string }[];
mediaDisabled?: boolean;
+ /** Why the media button is off, shown in its tooltip. */
+ mediaDisabledReasonKey?: string;
+ /** Shows the poll button: an X reply can turn into a poll. */
+ pollAvailable?: boolean;
+ /** Why the poll button is off (the reply has media), or null when it is on. */
+ pollDisabledReasonKey?: string | null;
}>(),
- { mediaDisabled: false },
+ {
+ mediaDisabled: false,
+ mediaDisabledReasonKey: 'posts.composer.media_not_supported',
+ pollAvailable: false,
+ pollDisabledReasonKey: null,
+ },
);
const emit = defineEmits<{
(event: 'import-started', payload: { importId: string; label: string }): void;
(event: 'open-unsplash'): void;
(event: 'upload'): void;
+ (event: 'add-poll'): void;
(event: 'select-emoji', emoji: string): void;
(
event: 'select-signature',
@@ -51,6 +69,10 @@ const requestUpload = (): void => {
emit('upload');
};
+const addPoll = (): void => {
+ emit('add-poll');
+};
+
const selectEmoji = (emoji: string): void => {
emit('select-emoji', emoji);
emojiOpen.value = false;
@@ -58,57 +80,105 @@ const selectEmoji = (emoji: string): void => {
</script>
<template>
- <div
- class="-me-3 -mb-2 flex flex-wrap items-center gap-y-1 pt-4"
- :data-testid="`${testIdPrefix}-toolbar`"
- >
- <MediaSourceMenu
- :test-id-prefix="testIdPrefix"
- :disabled="mediaDisabled"
- :disabled-reason="$t('posts.composer.media_not_supported')"
- @import-started="emit('import-started', $event)"
- @open-unsplash="emit('open-unsplash')"
- @upload="requestUpload"
- />
- <span class="mx-1.5 h-6 w-px bg-border" aria-hidden="true" />
- <Popover v-model:open="emojiOpen">
- <PopoverTrigger as-child>
- <button
- type="button"
- :data-testid="`${testIdPrefix}-emoji`"
- :aria-label="$t('posts.edit.emoji_picker.search')"
- :title="$t('posts.edit.emoji_picker.search')"
- class="flex size-8 items-center justify-center rounded-lg text-foreground transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
- >
- <IconMoodSmile class="size-4" />
- </button>
- </PopoverTrigger>
- <PopoverContent class="w-auto p-0" align="start">
- <EmojiPicker @select="selectEmoji" />
- </PopoverContent>
- </Popover>
- <Popover v-model:open="signaturesOpen">
- <PopoverTrigger as-child>
- <button
- type="button"
- :data-testid="`${testIdPrefix}-signature`"
- :aria-label="$t('posts.edit.signatures')"
- :title="$t('posts.edit.signatures')"
- class="flex size-8 items-center justify-center rounded-lg text-foreground transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
- >
- <IconSignature class="size-4" />
- </button>
- </PopoverTrigger>
- <PopoverContent class="w-auto p-0" align="start">
- <SignaturePicker
- :signatures="signatures"
- @select="selectSignature"
- @saved="emit('save-signature', $event)"
- />
- </PopoverContent>
- </Popover>
- <div class="ms-auto flex items-center gap-3 pe-3">
- <slot />
+ <TooltipProvider :delay-duration="200">
+ <div
+ class="-me-3 -mb-2 flex flex-wrap items-center gap-y-1 pt-4"
+ :data-testid="`${testIdPrefix}-toolbar`"
+ >
+ <MediaSourceMenu
+ :test-id-prefix="testIdPrefix"
+ :disabled="mediaDisabled"
+ :disabled-reason="$t(mediaDisabledReasonKey)"
+ @import-started="emit('import-started', $event)"
+ @open-unsplash="emit('open-unsplash')"
+ @upload="requestUpload"
+ />
+ <template v-if="pollAvailable">
+ <Tooltip v-if="pollDisabledReasonKey">
+ <TooltipTrigger as-child>
+ <span
+ class="flex size-8 cursor-not-allowed items-center justify-center text-subtle-foreground"
+ :aria-label="$t(pollDisabledReasonKey)"
+ :data-testid="`${testIdPrefix}-poll-disabled`"
+ >
+ <IconListDetails class="size-4" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{{ $t(pollDisabledReasonKey) }}</TooltipContent>
+ </Tooltip>
+ <Tooltip v-else>
+ <TooltipTrigger as-child>
+ <button
+ type="button"
+ :data-testid="`${testIdPrefix}-poll`"
+ :aria-label="$t('posts.form.x.poll.add')"
+ class="flex size-8 items-center justify-center rounded-lg text-foreground transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
+ @click="addPoll"
+ >
+ <IconListDetails class="size-4" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent :data-testid="`${testIdPrefix}-poll-tooltip`">
+ {{ $t('posts.form.x.poll.add') }}
+ </TooltipContent>
+ </Tooltip>
+ </template>
+ <span class="mx-1.5 h-6 w-px bg-border" aria-hidden="true" />
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <span class="inline-flex">
+ <Popover v-model:open="emojiOpen">
+ <PopoverTrigger as-child>
+ <button
+ type="button"
+ :data-testid="`${testIdPrefix}-emoji`"
+ :aria-label="$t('posts.edit.emoji_picker.search')"
+ class="flex size-8 items-center justify-center rounded-lg text-foreground transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
+ >
+ <IconMoodSmile class="size-4" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent class="w-auto p-0" align="start">
+ <EmojiPicker @select="selectEmoji" />
+ </PopoverContent>
+ </Popover>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent :data-testid="`${testIdPrefix}-emoji-tooltip`">
+ {{ $t('posts.edit.emoji_picker.search') }}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <span class="inline-flex">
+ <Popover v-model:open="signaturesOpen">
+ <PopoverTrigger as-child>
+ <button
+ type="button"
+ :data-testid="`${testIdPrefix}-signature`"
+ :aria-label="$t('posts.edit.signatures')"
+ class="flex size-8 items-center justify-center rounded-lg text-foreground transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
+ >
+ <IconSignature class="size-4" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent class="w-auto p-0" align="start">
+ <SignaturePicker
+ :signatures="signatures"
+ @select="selectSignature"
+ @saved="emit('save-signature', $event)"
+ />
+ </PopoverContent>
+ </Popover>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent :data-testid="`${testIdPrefix}-signature-tooltip`">
+ {{ $t('posts.edit.signatures') }}
+ </TooltipContent>
+ </Tooltip>
+ <div class="ms-auto flex items-center gap-3 pe-3">
+ <slot />
+ </div>
</div>
- </div>
+ </TooltipProvider>
</template>
diff --git a/resources/js/components/posts/composer/ComposerNetworkCard.vue b/resources/js/components/posts/composer/ComposerNetworkCard.vue
index 1153158cf..a7f3238cc 100644
--- a/resources/js/components/posts/composer/ComposerNetworkCard.vue
+++ b/resources/js/components/posts/composer/ComposerNetworkCard.vue
@@ -182,7 +182,8 @@ const showsHeader = computed(
<span
v-if="threaded && platform"
aria-hidden="true"
- class="pointer-events-none absolute -start-[25px] top-7 -bottom-3 w-0.5 rounded-full bg-border"
+ class="pointer-events-none absolute -start-[25px] -bottom-[14px] w-0.5 rounded-full bg-border"
+ :class="showsHeader ? '-top-3.5' : 'top-[26px]'"
:data-testid="`${testIdPrefix}-thread-connector`"
/>
<button
@@ -239,6 +240,12 @@ const showsHeader = computed(
</button>
</p>
</div>
+ <div
+ v-if="threaded && !captionCollapsed && $slots.attachment"
+ class="pt-2"
+ >
+ <slot name="attachment" />
+ </div>
<slot v-if="threaded" name="post-media" />
<div
v-if="threaded && !captionCollapsed"
@@ -248,6 +255,7 @@ const showsHeader = computed(
</div>
<slot name="replies" />
<div>
+ <slot v-if="!threaded" name="attachment" />
<slot v-if="showsMedia" name="media" />
<Teleport
v-if="threaded"
diff --git a/resources/js/components/posts/composer/ComposerNetworkSettings.vue b/resources/js/components/posts/composer/ComposerNetworkSettings.vue
index d9d8e2a2c..79cd5caa7 100644
--- a/resources/js/components/posts/composer/ComposerNetworkSettings.vue
+++ b/resources/js/components/posts/composer/ComposerNetworkSettings.vue
@@ -88,6 +88,7 @@ const AI_GENERATED_ROWS: Partial<
},
[ContentType.TikTokVideo]: { metaKey: 'is_aigc', testId: 'tiktok-ai-generated' },
[ContentType.XPost]: { metaKey: 'is_ai_generated', testId: 'x-ai-generated' },
+ [ContentType.XPoll]: { metaKey: 'is_ai_generated', testId: 'x-ai-generated' },
};
const aiRow = computed(
diff --git a/resources/js/components/posts/composer/MediaSourceMenu.vue b/resources/js/components/posts/composer/MediaSourceMenu.vue
index 1fbd44de9..4d5ee9b33 100644
--- a/resources/js/components/posts/composer/MediaSourceMenu.vue
+++ b/resources/js/components/posts/composer/MediaSourceMenu.vue
@@ -29,6 +29,7 @@ import {
type MediaImportPayload,
useMediaImport,
} from '@/composables/useMediaImport';
+import { filled } from '@/lib/helpers';
import { defaultCanvaPreset, openCanva } from '@/lib/mediaSources/canva';
import {
type GoogleDrivePick,
@@ -210,8 +211,8 @@ const pickCanvaPreset = (
</script>
<template>
- <TooltipProvider v-if="disabled" :delay-duration="200">
- <Tooltip>
+ <TooltipProvider :delay-duration="200">
+ <Tooltip v-if="disabled">
<TooltipTrigger as-child>
<span
class="flex size-8 cursor-not-allowed items-center justify-center text-subtle-foreground"
@@ -223,99 +224,106 @@ const pickCanvaPreset = (
</TooltipTrigger>
<TooltipContent>{{ disabledReason }}</TooltipContent>
</Tooltip>
- </TooltipProvider>
- <DropdownMenu
- v-else
- v-model:open="menuOpen"
- @update:open="onMenuOpenChange"
- >
- <DropdownMenuTrigger as-child>
- <button
- type="button"
- :data-testid="`${testIdPrefix}-media-source-menu`"
- :aria-label="$t('posts.edit.add_media')"
- :title="$t('posts.edit.add_media')"
- class="flex size-8 items-center justify-center rounded-lg text-foreground transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[state=open]:bg-accent"
- @pointerenter="preloadSources"
- @focus="preloadSources"
- >
- <IconPhotoPlus class="size-4" />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="top"
- align="start"
- :side-offset="8"
- class="min-w-48"
- :data-testid="`${testIdPrefix}-media-source-list`"
- >
- <DropdownMenuItem
- data-testid="media-source-upload"
- @select="requestUpload"
- >
- <IconUpload class="text-foreground" />
- {{ $t('posts.composer.media_sources.upload') }}
- </DropdownMenuItem>
- <DropdownMenuSeparator v-if="sources.length" />
- <template v-for="option in sources" :key="option.source">
- <DropdownMenuSub v-if="option.source === 'canva'">
- <DropdownMenuSubTrigger
- :data-testid="`media-source-${option.source}`"
+ <Tooltip v-else>
+ <TooltipTrigger as-child>
+ <span class="inline-flex">
+ <DropdownMenu
+ v-model:open="menuOpen"
+ @update:open="onMenuOpenChange"
+ >
+ <DropdownMenuTrigger as-child>
+ <button
+ type="button"
+ :data-testid="`${testIdPrefix}-media-source-menu`"
+ :aria-label="$t('posts.edit.add_media')"
+ class="flex size-8 items-center justify-center rounded-lg text-foreground transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[state=open]:bg-accent"
+ @pointerenter="preloadSources"
+ @focus="preloadSources"
+ >
+ <IconPhotoPlus class="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="top"
+ align="start"
+ :side-offset="8"
+ class="min-w-48"
+ :data-testid="`${testIdPrefix}-media-source-list`"
>
- <component
- :is="ICONS[option.source]"
- :class="['text-foreground', ICON_CLASSES[option.source]]"
- />
- {{ option.label }}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
<DropdownMenuItem
- v-for="preset in option.presets ?? []"
- :key="preset.value"
- :data-testid="`canva-preset-${preset.value}`"
- @select="pickCanvaPreset(option, preset.value)"
+ data-testid="media-source-upload"
+ @select="requestUpload"
>
- <span
- class="flex items-baseline gap-1.5 whitespace-nowrap"
- >
- {{
- $t(
- `posts.composer.media_sources.canva_presets.${preset.value}`,
- )
- }}
- <span
- class="text-xs text-muted-foreground tabular-nums"
- >
- ({{ preset.width }}×{{ preset.height }})
- <template v-if="preset.is_default">
- ·
- <span
- :data-testid="`canva-preset-${preset.value}-default`"
- >
- {{
- $t(
- 'posts.composer.media_sources.canva_default',
- )
- }}
- </span>
- </template>
- </span>
- </span>
+ <IconUpload class="text-foreground" />
+ {{ $t('posts.composer.media_sources.upload') }}
</DropdownMenuItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuItem
- v-else
- :data-testid="`media-source-${option.source}`"
- @select="pick(option)"
- >
- <component
- :is="ICONS[option.source]"
- :class="['text-foreground', ICON_CLASSES[option.source]]"
- />
- {{ option.label }}
- </DropdownMenuItem>
- </template>
- </DropdownMenuContent>
- </DropdownMenu>
+ <DropdownMenuSeparator v-if="filled(sources)" />
+ <template v-for="option in sources" :key="option.source">
+ <DropdownMenuSub v-if="option.source === 'canva'">
+ <DropdownMenuSubTrigger
+ :data-testid="`media-source-${option.source}`"
+ >
+ <component
+ :is="ICONS[option.source]"
+ :class="['text-foreground', ICON_CLASSES[option.source]]"
+ />
+ {{ option.label }}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuItem
+ v-for="preset in option.presets ?? []"
+ :key="preset.value"
+ :data-testid="`canva-preset-${preset.value}`"
+ @select="pickCanvaPreset(option, preset.value)"
+ >
+ <span
+ class="flex items-baseline gap-1.5 whitespace-nowrap"
+ >
+ {{
+ $t(
+ `posts.composer.media_sources.canva_presets.${preset.value}`,
+ )
+ }}
+ <span
+ class="text-xs text-muted-foreground tabular-nums"
+ >
+ ({{ preset.width }}×{{ preset.height }})
+ <template v-if="preset.is_default">
+ ·
+ <span
+ :data-testid="`canva-preset-${preset.value}-default`"
+ >
+ {{
+ $t(
+ 'posts.composer.media_sources.canva_default',
+ )
+ }}
+ </span>
+ </template>
+ </span>
+ </span>
+ </DropdownMenuItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuItem
+ v-else
+ :data-testid="`media-source-${option.source}`"
+ @select="pick(option)"
+ >
+ <component
+ :is="ICONS[option.source]"
+ :class="['text-foreground', ICON_CLASSES[option.source]]"
+ />
+ {{ option.label }}
+ </DropdownMenuItem>
+ </template>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent :data-testid="`${testIdPrefix}-media-source-tooltip`">
+ {{ $t('posts.edit.add_media') }}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
</template>
diff --git a/resources/js/components/posts/composer/PostComposerDialog.vue b/resources/js/components/posts/composer/PostComposerDialog.vue
index 67fb830bb..1e2f2d6dd 100644
--- a/resources/js/components/posts/composer/PostComposerDialog.vue
+++ b/resources/js/components/posts/composer/PostComposerDialog.vue
@@ -70,6 +70,7 @@ import ResumeUnfinishedPostDialog from '@/components/posts/composer/ResumeUnfini
import ChannelMediaWarnings from '@/components/posts/editor/ChannelMediaWarnings.vue';
import GoogleBusinessTopicTypeRadios from '@/components/posts/editor/GoogleBusinessTopicTypeRadios.vue';
import ThreadRepliesField from '@/components/posts/editor/ThreadRepliesField.vue';
+import XPollField from '@/components/posts/editor/XPollField.vue';
import PlatformPreview from '@/components/posts/previews/PlatformPreview.vue';
import PreviewPanelTitle from '@/components/posts/previews/PreviewPanelTitle.vue';
import PublishEmptyIllustration from '@/components/publish/PublishEmptyIllustration.vue';
@@ -92,6 +93,7 @@ import {
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip';
+import { useComposerPoll } from '@/composables/composer/useComposerPoll';
import { useComposerTimezone } from '@/composables/composer/useComposerTimezone';
import { useComposerUnsavedChanges } from '@/composables/composer/useComposerUnsavedChanges';
import { useLastUsedAccounts } from '@/composables/composer/useLastUsedAccounts';
@@ -158,6 +160,7 @@ import {
resolveGoogleBusinessTopicType,
} from '@/lib/googleBusiness';
import { countHashtags } from '@/lib/hashtags';
+import { blank, filled, transform } from '@/lib/helpers';
import { extractErrorMessage } from '@/lib/httpError';
import { getInstagramImageAspectIssues } from '@/lib/instagramImageAspect';
import { linkPreviewDroppable, linkPreviewUrl } from '@/lib/linkPreview';
@@ -171,10 +174,12 @@ import { acceptAttribute, mediaKey } from '@/lib/mediaType';
import { evaluatePlatformMeta } from '@/lib/platformMeta';
import {
newThreadReply,
+ replyErrorOf,
type ThreadReply,
threadRepliesOf,
} from '@/lib/threadReplies';
import { htmlToPlainText } from '@/lib/utils';
+import { pollLimitsOf } from '@/lib/xPoll';
import { userTimezone } from '@/preferences';
import { settings as channelSettings } from '@/routes/app/channels';
import { linkPreviewMedia } from '@/routes/app/posts';
@@ -187,6 +192,7 @@ import type {
import {
CAPTIONLESS_CONTENT_TYPES,
ContentType,
+ MEDIALESS_CONTENT_TYPE_REASONS,
} from '@/types/content-type';
import type { MediaItem } from '@/types/media';
import {
@@ -451,20 +457,87 @@ const groupDestination = (
composition.resolvedDestination(group.anchor);
const contentTypeOptionsFor = (group: NetworkGroup): ContentTypeOption[] => {
const options = getPickableContentTypeOptions(group.platform);
-
- if (group.platform !== Platform.Threads) return options;
-
- const attached = groupDestination(group).media.length > 0;
+ const attached =
+ filled(groupDestination(group).media) ||
+ uploaderFor(group.key).busy.value;
return options.map((option) =>
- option.value === ContentType.ThreadsGhostPost && attached
+ attached && MEDIALESS_CONTENT_TYPE_REASONS[option.value]
? {
...option,
- disabledReasonKey: 'posts.form.threads.ghost_post_attachments',
+ disabledReasonKey: MEDIALESS_CONTENT_TYPE_REASONS[option.value],
}
: option,
);
};
+/** The account's poll limits, served in its `publishConfig`; null off X. */
+const {
+ groupPollLimits,
+ accountTextLimit,
+ isPollGroup,
+ groupPoll,
+ setGroupPoll,
+ setGroupContentType,
+ removeGroupPoll,
+ forgetGroupPoll,
+ forgetPolls,
+ replyPollLimit,
+ replyTextLimit,
+ setReplyPoll,
+ replyPollAvailable,
+ replyPollDisabledReasonKey,
+ addReplyPoll,
+} = useComposerPoll(
+ composition,
+ (account) => pollLimitsOf(props.platformConfigs[account.id]?.publishConfig),
+ {
+ activeReply: (group) => activeReply(group),
+ replies: (group) => threadReplies(group),
+ setReplies: (group, replies) => setThreadReplies(group, replies),
+ replyLimit: (group) => threadReplyLimit(group),
+ uploading: (group, reply) =>
+ Boolean(replyUploaderFor(group, reply)?.busy.value),
+ },
+);
+/**
+ * Step 1 shows no post type, so an X poll, which takes no media, would quietly
+ * refuse the shared media there. Entering it (a second network added) puts
+ * the poll card back on X's first type and forgets its poll, as going back to
+ * step 1 does.
+ */
+watch(sharedStep, (shared) => {
+ if (!shared) return;
+
+ networkGroups.value
+ .filter(
+ (group) =>
+ groupDestination(group).content_type === ContentType.XPoll,
+ )
+ .forEach((group) => {
+ const [firstType] = getPickableContentTypeOptions(group.platform);
+ if (!firstType) return;
+
+ setGroupContentType(group, firstType.value);
+ forgetGroupPoll(group);
+ });
+});
+/** Why the media button is off: a type that takes no media says so, and so does a reply poll. */
+const groupMediaDisabledReasonKey = (group: NetworkGroup): string => {
+ const reply = activeReply(group);
+
+ if (filled(reply) && filled(reply.poll)) {
+ return MEDIALESS_CONTENT_TYPE_REASONS[ContentType.XPoll];
+ }
+
+ if (filled(reply)) {
+ return 'posts.composer.media_not_supported';
+ }
+
+ return (
+ MEDIALESS_CONTENT_TYPE_REASONS[groupDestination(group).content_type] ??
+ 'posts.composer.media_not_supported'
+ );
+};
const openNetwork = (
groupKey: string,
accountId: string | null = null,
@@ -993,8 +1066,14 @@ const writeContent = (groupKey: string | null, next: string): void => {
const assistantContent = computed(() =>
contentOf(sharedStep.value ? null : openGroupKey.value),
);
+/** The account's text limit for its current post type. */
+const contentLimit = (account: ComposerAccount): number | undefined =>
+ accountTextLimit(
+ account,
+ props.platformConfigs[account.id]?.maxContentLength,
+ );
const accountLimit = (account: ComposerAccount): number =>
- props.platformConfigs[account.id]?.maxContentLength ?? Infinity;
+ contentLimit(account) ?? Infinity;
const assistantChannel = computed<AssistantChannel | null>(() => {
const account = sharedStep.value
? undefined
@@ -1006,11 +1085,13 @@ const assistantChannel = computed<AssistantChannel | null>(() => {
undefined,
);
if (!account) return null;
- const limit = props.platformConfigs[account.id]?.maxContentLength;
+ const limit = contentLimit(account);
return {
accountId: account.id,
platform: account.platform,
+ contentType:
+ composition.resolvedDestination(account).content_type || null,
label: getPlatformLabel(account.platform),
limit: typeof limit === 'number' ? limit : null,
};
@@ -1035,7 +1116,7 @@ const contentWarningLength = (account: ComposerAccount): number =>
)
: 0;
const remainingCharacters = (account: ComposerAccount): number | null => {
- const limit = props.platformConfigs[account.id]?.maxContentLength;
+ const limit = contentLimit(account);
if (typeof limit !== 'number' || limit <= 0) return null;
const destination = composition.resolvedDestination(account);
if (CAPTIONLESS_CONTENT_TYPES.has(destination.content_type)) return null;
@@ -1111,27 +1192,43 @@ const startThreadFromCaption = (group: NetworkGroup): void => {
};
const activeRemaining = (group: NetworkGroup): number | null => {
const reply = activeReply(group);
- if (reply === undefined) return groupRemaining(group);
- const limit = threadReplyLimit(group);
- return limit === null
- ? null
- : limit -
- displayLength(contentFor(reply.text, group.platform));
+ if (filled(reply)) {
+ return transform(
+ replyTextLimit(group, reply),
+ (limit) => limit - displayLength(contentFor(reply.text, group.platform)),
+ );
+ }
+
+ return groupRemaining(group);
};
+/** Where the server reports an account's thread replies: one post on an edit, a batch on create. */
+const threadRepliesErrorPrefix = (account: ComposerAccount): string => {
+ if (props.initialPost) {
+ return 'meta.thread_replies';
+ }
+
+ return `destinations.${selectedAccounts.value.indexOf(account)}.meta.thread_replies`;
+};
+/** Each reply's error for the card, the first account's winning. */
const threadReplyErrors = (group: NetworkGroup): Record<number, string> => {
const found: Record<number, string> = {};
- for (const account of group.accounts) {
- const prefix = props.initialPost
- ? 'meta.thread_replies'
- : `destinations.${selectedAccounts.value.indexOf(account)}.meta.thread_replies`;
- for (const [key, message] of Object.entries(errors.value)) {
- const match = key.startsWith(`${prefix}.`)
- ? Number(key.slice(prefix.length + 1).split('.')[0])
- : NaN;
- if (Number.isInteger(match)) found[match] ??= message;
+
+ threadReplies(group).forEach((_, index) => {
+ const message = group.accounts
+ .map((account) =>
+ replyErrorOf(
+ errors.value,
+ threadRepliesErrorPrefix(account),
+ index,
+ ),
+ )
+ .find(filled);
+
+ if (filled(message)) {
+ found[index] = message;
}
- }
+ });
return found;
};
@@ -1254,8 +1351,15 @@ const onMediaFilesSelected = (event: Event): void => {
mediaFileTarget.value.add(files);
}
};
-const groupAcceptsMedia = (group: NetworkGroup): boolean =>
- activeReply(group) !== undefined || acceptsMedia(group.key);
+const groupAcceptsMedia = (group: NetworkGroup): boolean => {
+ const reply = activeReply(group);
+
+ if (filled(reply)) {
+ return reply.poll === undefined;
+ }
+
+ return acceptsMedia(group.key);
+};
const onGroupImportStarted = (
started: MediaImportStarted,
group: NetworkGroup,
@@ -1269,7 +1373,7 @@ const onGroupMediaDropped = (event: DragEvent, group: NetworkGroup): void => {
return;
}
const files = Array.from(event.dataTransfer?.files ?? []);
- if (files.length && !cropUploading.value) {
+ if (filled(files) && !cropUploading.value && groupAcceptsMedia(group)) {
groupMediaUploader(group).add(files);
}
};
@@ -1279,9 +1383,10 @@ const onReplyMediaPasted = (
): void => {
const files = Array.from(event.clipboardData?.files ?? []);
if (
- !files.length ||
- event.clipboardData?.getData('text/plain').trim() ||
- cropUploading.value
+ blank(files) ||
+ filled(event.clipboardData?.getData('text/plain')) ||
+ cropUploading.value ||
+ !groupAcceptsMedia(group)
) {
return;
}
@@ -1361,9 +1466,7 @@ const destinationIssues = (account: ComposerAccount): DestinationIssue[] => {
params: {
platform: getPlatformLabel(account.platform),
over: String(-remaining),
- limit: String(
- props.platformConfigs[account.id]?.maxContentLength ?? '',
- ),
+ limit: String(contentLimit(account) ?? ''),
},
contentType,
});
@@ -1607,6 +1710,7 @@ const customizeNetworks = (): void => {
const goBackToSharedStep = (): void => {
composition.discardCustomization();
+ forgetPolls();
confirmingBack.value = false;
};
@@ -1910,6 +2014,7 @@ const resumeUnfinishedPost = (): void => {
]),
);
composition.normalizeGroups();
+ forgetPolls();
const [firstGroup] = composition.networkGroups.value;
if (firstGroup) openNetwork(firstGroup.key);
const mode = snapshot.scheduleMode;
@@ -2653,11 +2758,7 @@ const onDialogOpenChange = (value: boolean): void => {
)
"
@update:content-type="
- composition.setGroupOverride(
- group.key,
- 'content_type',
- $event,
- )
+ setGroupContentType(group, $event)
"
@paste="onMediaPasted($event, group.key)"
@drop="onGroupMediaDropped($event, group)"
@@ -2834,11 +2935,32 @@ const onDialogOpenChange = (value: boolean): void => {
}}
</p>
</template>
+ <template
+ v-if="
+ isPollGroup(group) &&
+ groupPollLimits(group)
+ "
+ #attachment
+ >
+ <XPollField
+ :model-value="groupPoll(group)"
+ :limits="groupPollLimits(group)!"
+ :platform-index="
+ selectedAccounts.indexOf(group.anchor)
+ "
+ :disabled="cropUploading"
+ @update:model-value="
+ setGroupPoll(group, $event)
+ "
+ @remove="removeGroupPoll(group)"
+ />
+ </template>
<template #post-media>
<MediaTray
v-if="
- threadActive === -1 ||
- groupDestination(group).media.length ||
+ (threadActive === -1 &&
+ !isPollGroup(group)) ||
+ filled(groupDestination(group).media) ||
trayHasActivity(group.key)
"
class="px-[9px] pt-1"
@@ -2878,6 +3000,7 @@ const onDialogOpenChange = (value: boolean): void => {
:model-value="threadReplies(group)"
:platform="group.platform"
:limit="threadReplyLimit(group) ?? Infinity"
+ :poll-limit="replyPollLimit(group)"
:errors="threadReplyErrors(group)"
:disabled="cropUploading"
@update:model-value="
@@ -2886,8 +3009,31 @@ const onDialogOpenChange = (value: boolean): void => {
@paste="onReplyMediaPasted($event, group)"
>
<template #media="{ reply, index }">
- <div
+ <XPollField
v-if="
+ filled(reply.poll) &&
+ threadActive === index &&
+ groupPollLimits(group)
+ "
+ :key="`reply-poll-${index}`"
+ class="px-[9px]"
+ :model-value="reply.poll"
+ :limits="groupPollLimits(group)!"
+ :platform-index="
+ selectedAccounts.indexOf(group.anchor)
+ "
+ :field-prefix="`thread_replies.${index}.`"
+ :test-id-prefix="`thread-reply-${index}-poll`"
+ :disabled="cropUploading"
+ @update:model-value="
+ setReplyPoll(group, reply.key, $event)
+ "
+ @remove="
+ setReplyPoll(group, reply.key, undefined)
+ "
+ />
+ <div
+ v-else-if="
threadActive === index ||
reply.media.length ||
replyHasActivity(group, reply)
@@ -2964,6 +3110,14 @@ const onDialogOpenChange = (value: boolean): void => {
:test-id-prefix="`composer-${group.anchor.id}`"
:signatures="availableSignatures"
:media-disabled="!groupAcceptsMedia(group)"
+ :media-disabled-reason-key="
+ groupMediaDisabledReasonKey(group)
+ "
+ :poll-available="replyPollAvailable(group)"
+ :poll-disabled-reason-key="
+ replyPollDisabledReasonKey(group)
+ "
+ @add-poll="addReplyPoll(group)"
@import-started="
onGroupImportStarted($event, group)
"
@@ -3000,24 +3154,34 @@ const onDialogOpenChange = (value: boolean): void => {
$t('posts.form.thread.start')
}}</span>
</Button>
- <Button
+ <Tooltip
v-else-if="
threadReplies(group).length <
THREAD_MAX_REPLIES
"
- type="button"
- variant="ghost"
- size="icon"
- class="ms-1 size-7 text-primary-text"
- data-testid="thread-add-reply"
- :aria-label="
- $t('posts.form.thread.add')
- "
- :disabled="cropUploading"
- @click="addThreadReply(group)"
>
- <IconCirclePlus class="size-4" />
- </Button>
+ <TooltipTrigger as-child>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ class="ms-1 size-7 text-primary-text"
+ data-testid="thread-add-reply"
+ :aria-label="
+ $t('posts.form.thread.add')
+ "
+ :disabled="cropUploading"
+ @click="addThreadReply(group)"
+ >
+ <IconCirclePlus class="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent
+ data-testid="thread-add-reply-tooltip"
+ >
+ {{ $t('posts.form.thread.add') }}
+ </TooltipContent>
+ </Tooltip>
</template>
<CharacterCounter
v-if="(groupHashtagsRemaining(group) ?? -1) >= 0"
@@ -3210,6 +3374,10 @@ const onDialogOpenChange = (value: boolean): void => {
groupDestination(group).content_type
"
:meta="groupDestination(group).meta"
+ :publish-config="
+ platformConfigs[group.anchor.id]
+ ?.publishConfig
+ "
:active-post="threadActive"
/>
</section>
@@ -3233,6 +3401,10 @@ const onDialogOpenChange = (value: boolean): void => {
previewDestination.content_type
"
:meta="previewDestination.meta"
+ :publish-config="
+ platformConfigs[previewAccount.id]
+ ?.publishConfig
+ "
:active-post="threadActive"
/>
</div>
diff --git a/resources/js/components/posts/editor/AiGeneratedRow.vue b/resources/js/components/posts/editor/AiGeneratedRow.vue
index 0cec8cd17..55a2060c1 100644
--- a/resources/js/components/posts/editor/AiGeneratedRow.vue
+++ b/resources/js/components/posts/editor/AiGeneratedRow.vue
@@ -40,7 +40,10 @@ const checked = defineModel<boolean>({ required: true });
<IconInfoCircle class="size-4" />
</button>
</TooltipTrigger>
- <TooltipContent side="bottom">
+ <TooltipContent
+ side="top"
+ :data-testid="`${testId}-tooltip`"
+ >
{{ $t('posts.form.ai_generated.hint') }}
</TooltipContent>
</Tooltip>
diff --git a/resources/js/components/posts/editor/ThreadRepliesField.vue b/resources/js/components/posts/editor/ThreadRepliesField.vue
index 4b620b82a..a6cde387f 100644
--- a/resources/js/components/posts/editor/ThreadRepliesField.vue
+++ b/resources/js/components/posts/editor/ThreadRepliesField.vue
@@ -6,19 +6,26 @@ import PlatformLogo from '@/components/PlatformLogo.vue';
import { useXLinkDefuser } from '@/composables/useXLinkDefuser';
import { autosizeTextarea } from '@/lib/autosizeTextarea';
import { displayLength } from '@/lib/characters';
-import { newThreadReply, type ThreadReply } from '@/lib/threadReplies';
+import { filled } from '@/lib/helpers';
+import {
+ isBlankThreadReply,
+ newThreadReply,
+ type ThreadReply,
+} from '@/lib/threadReplies';
const props = withDefaults(
defineProps<{
platform: string;
limit: number;
+ /** A reply poll's question cap, kept even on an account with long posts. */
+ pollLimit?: number;
max?: number;
disabled?: boolean;
errors?: Record<number, string>;
/** Id of the element the active post's toolbar is teleported into. */
toolbarTarget?: string;
}>(),
- { max: Infinity, disabled: false, errors: () => ({}) },
+ { pollLimit: Infinity, max: Infinity, disabled: false, errors: () => ({}) },
);
const replies = defineModel<ThreadReply[]>({ required: true });
@@ -35,12 +42,17 @@ const activateReply = (index: number): void => {
const { contentFor } = useXLinkDefuser();
const editor = ref<HTMLTextAreaElement[]>([]);
-const remaining = (reply: ThreadReply): number =>
- props.limit -
- displayLength(contentFor(reply.text, props.platform));
+/** A reply's text limit: a poll's question keeps the poll's cap, even on an account with long posts. */
+const limitFor = (reply: ThreadReply): number => {
+ if (filled(reply.poll)) {
+ return Math.min(props.limit, props.pollLimit);
+ }
-const isEmpty = (reply: ThreadReply | undefined): boolean =>
- reply !== undefined && reply.text === '' && reply.media.length === 0;
+ return props.limit;
+};
+
+const remaining = (reply: ThreadReply): number =>
+ limitFor(reply) - displayLength(contentFor(reply.text, props.platform));
const setReply = (index: number, value: string): void => {
replies.value = replies.value.map((reply, position) =>
@@ -107,7 +119,7 @@ const onReplyKeydown = (event: KeyboardEvent, index: number): void => {
if (
event.key === 'Backspace' &&
- isEmpty(replies.value[index]) &&
+ isBlankThreadReply(replies.value[index]) &&
!event.repeat
) {
event.preventDefault();
@@ -149,7 +161,7 @@ watch(
<span
v-if="index < replies.length - 1"
aria-hidden="true"
- class="absolute start-[11px] top-7 -bottom-3 w-0.5 rounded-full bg-border"
+ class="absolute start-[11px] top-[26px] -bottom-[14px] w-0.5 rounded-full bg-border"
:data-testid="`thread-connector-${index}`"
/>
<PlatformLogo :platform="platform" :size="24" class="shrink-0" />
diff --git a/resources/js/components/posts/editor/XPollField.vue b/resources/js/components/posts/editor/XPollField.vue
new file mode 100644
index 000000000..9e98db0c6
--- /dev/null
+++ b/resources/js/components/posts/editor/XPollField.vue
@@ -0,0 +1,337 @@
+<script setup lang="ts">
+import { IconPlus, IconTrash, IconX } from '@tabler/icons-vue';
+import type { AcceptableValue } from 'reka-ui';
+import { computed, nextTick, useId } from 'vue';
+
+import InputError from '@/components/InputError.vue';
+import SettingsRow from '@/components/posts/editor/SettingsRow.vue';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { useMetaErrors } from '@/composables/useMetaErrors';
+import {
+ editablePollOptions,
+ fitPollChoice,
+ pollChoiceLength,
+ HOURS_PER_DAY,
+ joinPollDuration,
+ MINUTES_PER_HOUR,
+ pollMaxDays,
+ splitPollDuration,
+} from '@/lib/xPoll';
+import type { XPoll, XPollDuration, XPollLimits } from '@/types/x';
+
+const props = withDefaults(
+ defineProps<{
+ modelValue: Partial<XPoll>;
+ /** The account's poll limits, from its `publishConfig`. */
+ limits: XPollLimits;
+ /** This card's position in the submitted `destinations`; see useMetaErrors. */
+ platformIndex: number;
+ /** Where the poll sits in the meta: '' for the post, `thread_replies.{n}.` for a reply. */
+ fieldPrefix?: string;
+ /** Prefix of every test id, so a post and its replies can each show a poll. */
+ testIdPrefix?: string;
+ disabled?: boolean;
+ }>(),
+ { fieldPrefix: '', testIdPrefix: 'x-poll', disabled: false },
+);
+
+const emit = defineEmits<{
+ 'update:modelValue': [value: XPoll];
+ remove: [];
+}>();
+
+const id = useId();
+
+const metaError = useMetaErrors(() => props.platformIndex);
+const optionsError = metaError(`${props.fieldPrefix}poll.options`);
+const durationError = metaError(`${props.fieldPrefix}poll.duration_minutes`);
+const choiceErrors = Array.from(
+ { length: props.limits.maxOptions },
+ (_, index) => metaError(`${props.fieldPrefix}poll.options.${index}`),
+);
+
+const choiceId = (index: number): string => `${id}-choice-${index}`;
+
+const options = computed((): string[] =>
+ editablePollOptions(props.modelValue.options, props.limits.minOptions),
+);
+const durationMinutes = computed(
+ (): number =>
+ props.modelValue.duration_minutes ?? props.limits.defaultDuration,
+);
+const duration = computed(
+ (): XPollDuration => splitPollDuration(durationMinutes.value),
+);
+const atLongestLength = computed(
+ (): boolean => durationMinutes.value >= props.limits.maxDuration,
+);
+
+const lengthParts: {
+ part: keyof XPollDuration;
+ labelKey: string;
+ values: number[];
+}[] = [
+ {
+ part: 'days',
+ labelKey: 'posts.form.x.poll.days',
+ values: Array.from(
+ { length: pollMaxDays(props.limits) + 1 },
+ (_, value) => value,
+ ),
+ },
+ {
+ part: 'hours',
+ labelKey: 'posts.form.x.poll.hours',
+ values: Array.from({ length: HOURS_PER_DAY }, (_, value) => value),
+ },
+ {
+ part: 'minutes',
+ labelKey: 'posts.form.x.poll.minutes',
+ values: Array.from({ length: MINUTES_PER_HOUR }, (_, value) => value),
+ },
+];
+
+const update = (patch: Partial<XPoll>): void => {
+ emit('update:modelValue', {
+ options: options.value,
+ duration_minutes: durationMinutes.value,
+ ...patch,
+ });
+};
+
+/** A choice's length as the server measures it, without the spaces around it. */
+
+/** The `:number` a choice's labels show, counted from one. */
+const choiceNumber = (index: number): { number: string } => ({
+ number: String(index + 1),
+});
+
+const choiceLabelKey = (index: number): string =>
+ index < props.limits.minOptions
+ ? 'posts.form.x.poll.choice'
+ : 'posts.form.x.poll.choice_optional';
+
+const writeChoice = (index: number, choice: string): void => {
+ update({
+ options: options.value.map((option, position) =>
+ position === index ? choice : option,
+ ),
+ });
+};
+
+/**
+ * Keeps a choice within its limit while typing. When the cut choice is the one
+ * already stored, the input (which keeps its own copy) would hold on to the
+ * typed text, so the typed text goes in first and the cut one right after.
+ */
+const setChoice = async (
+ index: number,
+ value: string | number,
+): Promise<void> => {
+ const typed = String(value);
+ const choice = fitPollChoice(typed, props.limits.optionMaxLength);
+
+ if (choice !== typed && choice === options.value[index]) {
+ writeChoice(index, typed);
+ await nextTick();
+ }
+
+ writeChoice(index, choice);
+};
+
+const addChoice = async (): Promise<void> => {
+ if (options.value.length >= props.limits.maxOptions) return;
+
+ const added = options.value.length;
+ update({ options: [...options.value, ''] });
+ await nextTick();
+ document.getElementById(choiceId(added))?.focus();
+};
+
+const removeChoice = (index: number): void => {
+ update({
+ options: options.value.filter((_, position) => position !== index),
+ });
+};
+
+const setLengthPart = (
+ part: keyof XPollDuration,
+ value: AcceptableValue,
+): void => {
+ update({
+ duration_minutes: joinPollDuration(
+ { ...duration.value, [part]: Number(value) },
+ props.limits,
+ ),
+ });
+};
+
+const removePoll = (): void => {
+ emit('remove');
+};
+</script>
+
+<template>
+ <div class="mt-3 space-y-4" :data-testid="testIdPrefix">
+ <SettingsRow align-top>
+ <template #label>
+ <span data-single-line>{{
+ $t('posts.form.x.poll.choices')
+ }}</span>
+ </template>
+ <template v-for="(option, index) in options" :key="index">
+ <div class="flex items-center gap-2">
+ <Input
+ :id="choiceId(index)"
+ :model-value="option"
+ class="min-w-0 flex-1"
+ :aria-label="
+ $t(choiceLabelKey(index), choiceNumber(index))
+ "
+ :placeholder="
+ $t(choiceLabelKey(index), choiceNumber(index))
+ "
+ :aria-invalid="
+ choiceErrors[index]?.value ? true : undefined
+ "
+ :disabled="disabled"
+ :data-testid="`${testIdPrefix}-choice-${index}`"
+ @update:model-value="setChoice(index, $event)"
+ />
+ <span
+ class="w-11 shrink-0 text-end text-xs tabular-nums"
+ :class="
+ pollChoiceLength(option) > limits.optionMaxLength
+ ? 'text-destructive-text'
+ : 'text-muted-foreground'
+ "
+ :data-testid="`${testIdPrefix}-choice-${index}-count`"
+ >{{ pollChoiceLength(option) }} /
+ {{ limits.optionMaxLength }}</span
+ >
+ <Button
+ v-if="index >= limits.minOptions"
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ class="text-muted-foreground"
+ :aria-label="
+ $t(
+ 'posts.form.x.poll.remove_choice',
+ choiceNumber(index),
+ )
+ "
+ :disabled="disabled"
+ :data-testid="`${testIdPrefix}-remove-choice-${index}`"
+ @click="removeChoice(index)"
+ >
+ <IconX class="size-4" />
+ </Button>
+ <span v-else aria-hidden="true" class="size-7 shrink-0" />
+ </div>
+ <InputError
+ :message="choiceErrors[index]?.value"
+ :data-testid="`${testIdPrefix}-choice-${index}-error`"
+ />
+ </template>
+ <InputError
+ :message="optionsError"
+ :data-testid="`${testIdPrefix}-options-error`"
+ />
+ <Button
+ v-if="options.length < limits.maxOptions"
+ type="button"
+ variant="outline"
+ size="sm"
+ :disabled="disabled"
+ :data-testid="`${testIdPrefix}-add-choice`"
+ @click="addChoice"
+ >
+ <IconPlus class="size-4" />
+ <span data-single-line>{{
+ $t('posts.form.x.poll.add_choice')
+ }}</span>
+ </Button>
+ </SettingsRow>
+ <SettingsRow>
+ <template #label>
+ <span data-single-line>{{
+ $t('posts.form.x.poll.length')
+ }}</span>
+ </template>
+ <div class="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <div
+ v-for="lengthPart in lengthParts"
+ :key="lengthPart.part"
+ class="flex items-center gap-1.5"
+ >
+ <Select
+ :model-value="String(duration[lengthPart.part])"
+ :disabled="
+ disabled ||
+ (atLongestLength && lengthPart.part !== 'days')
+ "
+ @update:model-value="
+ setLengthPart(lengthPart.part, $event)
+ "
+ >
+ <SelectTrigger
+ :id="`${id}-${lengthPart.part}`"
+ class="w-16"
+ :data-testid="`${testIdPrefix}-${lengthPart.part}`"
+ >
+ <SelectValue>{{
+ duration[lengthPart.part]
+ }}</SelectValue>
+ </SelectTrigger>
+ <SelectContent class="max-h-64">
+ <SelectItem
+ v-for="value in lengthPart.values"
+ :key="value"
+ :value="String(value)"
+ :data-testid="`${testIdPrefix}-${lengthPart.part}-${value}`"
+ >{{ value }}</SelectItem
+ >
+ </SelectContent>
+ </Select>
+ <label
+ :for="`${id}-${lengthPart.part}`"
+ class="text-sm text-muted-foreground"
+ data-single-line
+ >{{ $t(lengthPart.labelKey) }}</label
+ >
+ </div>
+ </div>
+ <InputError
+ :message="durationError"
+ :data-testid="`${testIdPrefix}-duration-error`"
+ />
+ </SettingsRow>
+ <SettingsRow>
+ <div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ class="text-destructive-text hover:text-destructive-text"
+ :disabled="disabled"
+ :data-testid="`${testIdPrefix}-remove`"
+ @click="removePoll"
+ >
+ <IconTrash class="size-4" />
+ <span data-single-line>{{
+ $t('posts.form.x.poll.remove')
+ }}</span>
+ </Button>
+ </div>
+ </SettingsRow>
+ </div>
+</template>
diff --git a/resources/js/components/posts/previews/PlatformPreview.vue b/resources/js/components/posts/previews/PlatformPreview.vue
index c2f7bb228..05c233931 100644
--- a/resources/js/components/posts/previews/PlatformPreview.vue
+++ b/resources/js/components/posts/previews/PlatformPreview.vue
@@ -18,9 +18,15 @@ 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 { filled } from '@/lib/helpers';
+import {
+ type ThreadReply,
+ threadRepliesOf,
+ threadReplyContentType,
+} from '@/lib/threadReplies';
import type { MediaItem } from '@/types/media';
import { THREAD_PLATFORMS } from '@/types/network-options';
+import type { PublishConfig } from '@/types/platform';
interface Props {
platform: string;
@@ -33,6 +39,8 @@ interface Props {
postedAt?: string | null;
/** The thread post being edited: -1 is the first post, otherwise the reply index. */
activePost?: number;
+ /** The account's `publishConfig` (`Platform::publishConfig()`). */
+ publishConfig?: PublishConfig | null;
}
const props = defineProps<Props>();
@@ -52,7 +60,9 @@ const shownReplies = computed((): { reply: ThreadReply; index: number }[] =>
.map((reply, index) => ({ reply, index }))
.filter(
({ reply }) =>
- reply.text.trim() !== '' || reply.media.length > 0,
+ filled(reply.text) ||
+ filled(reply.media) ||
+ filled(reply.poll),
)
: [],
);
@@ -60,6 +70,12 @@ const threadReplies = computed((): ThreadReply[] =>
shownReplies.value.map(({ reply }) => reply),
);
+/** A reply repeats the post's content warning and carries its own poll. */
+const replyMeta = (reply: ThreadReply): Record<string, any> => ({
+ spoiler_text: props.meta?.spoiler_text,
+ poll: reply.poll,
+});
+
const thread = ref<HTMLElement | null>(null);
/** Keeps the post being edited in view: an empty reply has no preview, so the closest one above it stands in. */
@@ -146,6 +162,7 @@ const previewComponent = computed(() => {
:content-type="contentType"
:meta="meta"
:posted-at="postedAt"
+ :publish-config="publishConfig"
:thread-position="threadReplies.length ? 'first' : undefined"
/>
</div>
@@ -160,9 +177,10 @@ const previewComponent = computed(() => {
:social-account="resolvedSocialAccount"
:content="contentFor(reply.text, platform)"
:media="reply.media"
- :content-type="contentType"
- :meta="{ spoiler_text: meta?.spoiler_text }"
+ :content-type="threadReplyContentType(platform, reply)"
+ :meta="replyMeta(reply)"
:posted-at="postedAt"
+ :publish-config="publishConfig"
:thread-position="
index === threadReplies.length - 1 ? 'last' : 'middle'
"
diff --git a/resources/js/components/posts/previews/PreviewTextPost.vue b/resources/js/components/posts/previews/PreviewTextPost.vue
index 263bbf830..823b0a24f 100644
--- a/resources/js/components/posts/previews/PreviewTextPost.vue
+++ b/resources/js/components/posts/previews/PreviewTextPost.vue
@@ -238,8 +238,9 @@ const hasActions = computed(
<PreviewMedia
v-if="!concealed"
:media="media"
+ :class="{ 'px-4': isStacked && threadPosition }"
:layout="mediaLayout"
- :bleed="isStacked"
+ :bleed="isStacked && !threadPosition"
:mute-badge="muteBadge"
/>
<div
diff --git a/resources/js/components/posts/previews/XPreview.vue b/resources/js/components/posts/previews/XPreview.vue
index 9e50e2ad8..42b2f347e 100644
--- a/resources/js/components/posts/previews/XPreview.vue
+++ b/resources/js/components/posts/previews/XPreview.vue
@@ -7,11 +7,27 @@ import {
IconRepeat,
IconUpload,
} 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 XPreviewPoll from '@/components/posts/previews/XPreviewPoll.vue';
+import { pollLimitsOf } from '@/lib/xPoll';
+import { ContentType } from '@/types/content-type';
+import type { XPoll } from '@/types/x';
-defineProps<PreviewProps>();
+const props = defineProps<PreviewProps>();
+
+/** The poll the post shows: only a Poll post has one, whatever its meta still holds. */
+const poll = computed((): Partial<XPoll> | undefined => {
+ if (props.contentType !== ContentType.XPoll) {
+ return undefined;
+ }
+
+ return props.meta?.poll;
+});
+
+const pollLimits = computed(() => pollLimitsOf(props.publishConfig));
</script>
<template>
@@ -23,7 +39,7 @@ defineProps<PreviewProps>();
:handle="`@${socialAccount.username || socialAccount.handle_label}`"
content-testid="x-preview-content"
media-layout="grid"
- link-card
+ :link-card="!poll"
:actions="[
{ icon: IconMessageCircle },
{ icon: IconRepeat },
@@ -31,5 +47,9 @@ defineProps<PreviewProps>();
{ icon: IconChartBar },
]"
:trailing-actions="[{ icon: IconBookmark }, { icon: IconUpload }]"
- />
+ >
+ <template v-if="poll && pollLimits" #default>
+ <XPreviewPoll :poll="poll" :limits="pollLimits" />
+ </template>
+ </PreviewTextPost>
</template>
diff --git a/resources/js/components/posts/previews/XPreviewPoll.vue b/resources/js/components/posts/previews/XPreviewPoll.vue
new file mode 100644
index 000000000..a150a95f9
--- /dev/null
+++ b/resources/js/components/posts/previews/XPreviewPoll.vue
@@ -0,0 +1,35 @@
+<script setup lang="ts">
+import { computed } from 'vue';
+
+import { editablePollOptions, formatPollLength } from '@/lib/xPoll';
+import type { XPoll, XPollLimits } from '@/types/x';
+
+const props = defineProps<{
+ poll: Partial<XPoll>;
+ /** The account's poll limits, from its `publishConfig`. */
+ limits: XPollLimits;
+}>();
+
+const options = computed((): string[] =>
+ editablePollOptions(props.poll.options, props.limits.minOptions),
+);
+
+const length = computed((): string =>
+ formatPollLength(props.poll.duration_minutes ?? props.limits.defaultDuration),
+);
+</script>
+
+<template>
+ <div class="space-y-2" data-testid="x-preview-poll">
+ <div
+ v-for="(option, index) in options"
+ :key="index"
+ class="min-h-8 truncate rounded-full border border-info px-3 py-1.5 text-center font-bold text-info dark:text-info-text"
+ >
+ {{ option }}
+ </div>
+ <p class="text-muted-foreground">
+ {{ $t('posts.composer.preview.poll_summary', { time: length }) }}
+ </p>
+ </div>
+</template>
diff --git a/resources/js/components/posts/previews/types.ts b/resources/js/components/posts/previews/types.ts
index 5b87c0e54..04844257e 100644
--- a/resources/js/components/posts/previews/types.ts
+++ b/resources/js/components/posts/previews/types.ts
@@ -1,6 +1,7 @@
import type { Component } from 'vue';
import type { MediaItem } from '@/types/media';
+import type { PublishConfig } from '@/types/platform';
import type { VerifiedBadge } from '@/types/social-account';
export interface PreviewAccount {
@@ -21,6 +22,8 @@ export interface PreviewProps {
contentType?: string;
meta?: Record<string, any>;
postedAt?: string | null;
+ /** The account's `publishConfig` (`Platform::publishConfig()`), e.g. X's poll limits. */
+ publishConfig?: PublishConfig | null;
}
export interface PreviewAction {
diff --git a/resources/js/components/publish/PostCardThread.vue b/resources/js/components/publish/PostCardThread.vue
new file mode 100644
index 000000000..cbfe0f0ee
--- /dev/null
+++ b/resources/js/components/publish/PostCardThread.vue
@@ -0,0 +1,79 @@
+<script setup lang="ts">
+import ChannelAvatar from '@/components/ChannelAvatar.vue';
+import PostDetailsMedia from '@/components/publish/PostDetailsMedia.vue';
+import PostPollResults from '@/components/publish/PostPollResults.vue';
+import type { ThreadPost } from '@/lib/postThread';
+import type { PublishSocialAccount } from '@/types/publish';
+
+defineProps<{
+ account: PublishSocialAccount;
+ /** The channel's name, as the card's header shows it. */
+ name: string;
+ /** Every post of the thread, the first one included. */
+ posts: ThreadPost[];
+ /** The post poll's test id; each reply poll's adds `-reply-{n}`. */
+ pollTestId: string;
+ testKey: string;
+}>();
+</script>
+
+<template>
+ <ol class="-mt-3 flex flex-col" :data-testid="`post-thread-${testKey}`">
+ <li
+ v-for="(post, index) in posts"
+ :key="index"
+ class="flex gap-3"
+ :data-testid="`post-thread-${testKey}-${index}`"
+ >
+ <div class="flex w-9 shrink-0 flex-col">
+ <ChannelAvatar
+ v-if="index > 0"
+ :status="account.status"
+ :account-id="account.id"
+ :platform="account.platform"
+ :src="account.avatar_url"
+ :verified="account.verified_badge"
+ :name="name"
+ ring="card"
+ />
+ <span
+ v-if="index < posts.length - 1"
+ aria-hidden="true"
+ class="ms-[15px] w-0.5 flex-1 rounded-full bg-border"
+ :class="{ 'mt-1': index > 0 }"
+ />
+ </div>
+ <div
+ class="flex min-w-0 flex-1 flex-col gap-2"
+ :class="{
+ 'pt-1': index === 0,
+ 'pb-5': index < posts.length - 1,
+ }"
+ >
+ <p
+ v-if="index > 0"
+ class="flex min-h-8 items-center truncate text-sm leading-tight font-emphasis text-foreground"
+ >
+ {{ name }}
+ </p>
+ <p
+ v-if="post.text"
+ class="line-clamp-4 text-sm whitespace-pre-line text-foreground"
+ >
+ {{ post.text }}
+ </p>
+ <PostDetailsMedia
+ v-if="post.media.length"
+ :items="post.media"
+ :bleed="false"
+ :test-key="`card-${testKey}-${index}`"
+ />
+ <PostPollResults
+ v-if="post.poll"
+ :poll="post.poll"
+ :test-id="`${pollTestId}${post.pollTestSuffix}`"
+ />
+ </div>
+ </li>
+ </ol>
+</template>
diff --git a/resources/js/components/publish/PostDetailsDialog.vue b/resources/js/components/publish/PostDetailsDialog.vue
index 9e0059a0e..bee31d732 100644
--- a/resources/js/components/publish/PostDetailsDialog.vue
+++ b/resources/js/components/publish/PostDetailsDialog.vue
@@ -18,6 +18,8 @@ import PostCardLabels from '@/components/publish/PostCardLabels.vue';
import PostCardMenu from '@/components/publish/PostCardMenu.vue';
import PostDetailsMedia from '@/components/publish/PostDetailsMedia.vue';
import PostMetricsBand from '@/components/publish/PostMetricsBand.vue';
+import PostPollResults from '@/components/publish/PostPollResults.vue';
+import PostPollResultsList from '@/components/publish/PostPollResultsList.vue';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
@@ -38,11 +40,12 @@ import { getPostStatusConfig } from '@/composables/usePostStatus';
import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';
import date from '@/date';
import dayjs from '@/dayjs';
+import { filled } from '@/lib/helpers';
+import { postThreadOf } from '@/lib/postThread';
import { compactPublicationMetrics } from '@/lib/publicationMetrics';
import { isRecurring } from '@/lib/recurrence';
-import { type ThreadReply, threadRepliesOf } from '@/lib/threadReplies';
+import { postPollResults } from '@/lib/xPoll';
import type { MediaItem } from '@/types/media';
-import { THREAD_PLATFORMS } from '@/types/network-options';
import { Platform } from '@/types/platform';
import { PostOrigin, PostStatus, PublishStatus } from '@/types/post';
import type { PostCard, PostCardMenuAction } from '@/types/publish';
@@ -156,6 +159,8 @@ const metricsDetail = computed(() => {
: null;
});
+const pollResults = computed(() => postPollResults(current.value));
+
const moment = computed(() => {
if (current.value.published_at) {
return {
@@ -202,18 +207,12 @@ watch(
},
);
-const threadReplies = computed((): ThreadReply[] => {
- return channel.value && THREAD_PLATFORMS.includes(channel.value.platform)
- ? threadRepliesOf(current.value.meta ?? {}).filter(
- (reply) => reply.text.trim() !== '' || reply.media.length > 0,
- )
- : [];
-});
+/** The post's thread, each post with its own text, media and poll. */
+const thread = computed(() => postThreadOf(current.value));
const showsThread = computed(
- () =>
- threadReplies.value.length > 0 &&
- Boolean(channel.value?.social_account),
+ (): boolean =>
+ filled(thread.value) && filled(channel.value?.social_account),
);
const lightboxOpen = ref(false);
@@ -417,10 +416,18 @@ const siblingMoment = (sibling: PostCard): string | null => {
<ThreadView
v-if="showsThread && channel?.social_account"
:account="channel.social_account"
- :posts="[{ text: content, media }, ...threadReplies]"
+ :posts="thread"
:test-key="currentKey"
@open-media="openMediaPreview"
- />
+ >
+ <template #post-end="{ index }">
+ <PostPollResults
+ v-if="thread[index]?.poll"
+ :poll="thread[index].poll"
+ :test-id="`post-details-poll${thread[index].pollTestSuffix}`"
+ />
+ </template>
+ </ThreadView>
<template v-else>
<div class="flex flex-col items-start gap-1">
<p
@@ -461,6 +468,14 @@ const siblingMoment = (sibling: PostCard): string | null => {
:test-key="`details-${currentKey}`"
/>
+ <PostPollResultsList
+ v-if="!showsThread"
+ class="-mx-6"
+ :poll="pollResults.poll"
+ :thread-polls="pollResults.threadPolls"
+ test-id="post-details-poll"
+ />
+
<PostMetricsBand
v-if="metricsDetail"
:detail="metricsDetail"
diff --git a/resources/js/components/publish/PostPollResults.vue b/resources/js/components/publish/PostPollResults.vue
new file mode 100644
index 000000000..00da9a917
--- /dev/null
+++ b/resources/js/components/publish/PostPollResults.vue
@@ -0,0 +1,132 @@
+<script setup lang="ts">
+import { computed } from 'vue';
+
+import date from '@/date';
+import { transform } from '@/lib/helpers';
+import { formatFullNumber, formatPercent } from '@/lib/utils';
+import type { PublicationPoll } from '@/types/analytics';
+
+const props = defineProps<{
+ poll: PublicationPoll;
+ testId: string;
+ /** Names the thread post a reply poll sits on. */
+ caption?: string;
+}>();
+
+/** X shows each choice's share with one decimal ("33.3%"). */
+const PERCENT_DIGITS = 1;
+
+type PollStatus = { key: string; replacements?: Record<string, string> };
+
+const votes = computed((): number[] =>
+ props.poll.options.map((option) => option.votes),
+);
+
+const totalVotes = computed((): number =>
+ votes.value.reduce((sum, count) => sum + count, 0),
+);
+
+const topVotes = computed((): number => Math.max(...votes.value));
+
+const hasVotes = computed((): boolean => totalVotes.value > 0);
+
+/** A choice's percentage of the votes; none before the first vote. */
+const percentOf = (count: number): number => {
+ if (!hasVotes.value) {
+ return 0;
+ }
+
+ return (count / totalVotes.value) * 100;
+};
+
+/** The choice with the most votes leads, ties included; none before the first vote. */
+const isLeading = (count: number): boolean =>
+ hasVotes.value && count === topVotes.value;
+
+const rows = computed(() =>
+ props.poll.options.map(({ label, votes: count }) => {
+ const percent = percentOf(count);
+
+ return {
+ label,
+ votes: count,
+ width: `${percent}%`,
+ percent: formatPercent(percent, PERCENT_DIGITS),
+ leading: isLeading(count),
+ };
+ }),
+);
+
+/** When voting ends: already ended, or in how long. */
+const votingEnd = (endsAt: string): PollStatus => {
+ if (date.hasPassed(endsAt)) {
+ return { key: 'posts.poll_results.ended' };
+ }
+
+ return {
+ key: 'posts.poll_results.ends',
+ replacements: { time: date.diffForHumans(endsAt) },
+ };
+};
+
+/** The voting state shown after the total: final, ended or when voting ends. */
+const status = computed((): PollStatus | null => {
+ if (props.poll.voting_status === 'closed') {
+ return { key: 'posts.poll_results.final' };
+ }
+
+ return transform(props.poll.end_datetime, votingEnd);
+});
+</script>
+
+<template>
+ <div class="flex flex-col gap-1.5" :data-testid="testId">
+ <p
+ v-if="caption"
+ class="text-xs font-medium text-muted-foreground"
+ :data-testid="`${testId}-caption`"
+ >
+ {{ caption }}
+ </p>
+ <div
+ v-for="(row, index) in rows"
+ :key="index"
+ class="group relative flex items-center justify-between gap-3 overflow-hidden rounded-md bg-muted px-3 py-1.5 text-sm text-muted-foreground data-[leading=true]:font-semibold data-[leading=true]:text-foreground"
+ :data-testid="`${testId}-option-${index}`"
+ :data-leading="String(row.leading)"
+ >
+ <span
+ class="absolute inset-y-0 start-0 rounded-md bg-secondary group-data-[leading=true]:bg-primary-selected"
+ :style="{ width: row.width }"
+ aria-hidden="true"
+ />
+ <span class="relative min-w-0 truncate">{{ row.label }}</span>
+ <span
+ class="relative shrink-0 tabular-nums"
+ :data-testid="`${testId}-option-${index}-votes`"
+ >
+ {{
+ $tChoice('posts.poll_results.votes', row.votes, {
+ count: formatFullNumber(row.votes),
+ })
+ }}
+ ·
+ {{ row.percent }}
+ </span>
+ </div>
+
+ <p
+ class="text-xs text-muted-foreground"
+ :data-testid="`${testId}-summary`"
+ >
+ {{
+ $tChoice('posts.poll_results.votes', totalVotes, {
+ count: formatFullNumber(totalVotes),
+ })
+ }}
+ <template v-if="status"
+ >· {{ $t(status.key, status.replacements) }}</template
+ >
+ </p>
+ </div>
+</template>
diff --git a/resources/js/components/publish/PostPollResultsList.vue b/resources/js/components/publish/PostPollResultsList.vue
new file mode 100644
index 000000000..7e45e719e
--- /dev/null
+++ b/resources/js/components/publish/PostPollResultsList.vue
@@ -0,0 +1,38 @@
+<script setup lang="ts">
+import { computed } from 'vue';
+
+import PostPollResults from '@/components/publish/PostPollResults.vue';
+import { filled } from '@/lib/helpers';
+import type {
+ PublicationPoll,
+ PublicationThreadPoll,
+} from '@/types/analytics';
+
+const props = defineProps<{
+ poll: PublicationPoll | null;
+ threadPolls: PublicationThreadPoll[];
+ /** The post poll's test id; each reply poll's adds `-reply-{n}`. */
+ testId: string;
+}>();
+
+const hasPolls = computed(
+ (): boolean => filled(props.poll) || filled(props.threadPolls),
+);
+</script>
+
+<template>
+ <div v-if="hasPolls" class="flex flex-col gap-3 px-4 pb-3">
+ <PostPollResults v-if="poll" :poll="poll" :test-id="testId" />
+ <PostPollResults
+ v-for="threadPoll in threadPolls"
+ :key="threadPoll.reply"
+ :poll="threadPoll"
+ :caption="
+ $t('posts.poll_results.thread_post', {
+ number: String(threadPoll.reply + 2),
+ })
+ "
+ :test-id="`${testId}-reply-${threadPoll.reply}`"
+ />
+ </div>
+</template>
diff --git a/resources/js/components/publish/PostTimelineCard.vue b/resources/js/components/publish/PostTimelineCard.vue
index c0362ef1d..4df07451c 100644
--- a/resources/js/components/publish/PostTimelineCard.vue
+++ b/resources/js/components/publish/PostTimelineCard.vue
@@ -6,11 +6,13 @@ import {
IconCirclePlay,
IconEdit,
IconExternalLink,
+ IconGhost2,
IconMessageCircle,
IconMessageCircleFilled,
IconGripVertical,
IconClockPause,
IconHourglass,
+ IconListDetails,
IconLoader2,
IconPencil,
IconPlayerPlayFilled,
@@ -31,9 +33,11 @@ import AddToQueueButton from '@/components/publish/AddToQueueButton.vue';
import ApprovePostButton from '@/components/publish/ApprovePostButton.vue';
import PostCardLabels from '@/components/publish/PostCardLabels.vue';
import PostCardMenu from '@/components/publish/PostCardMenu.vue';
+import PostCardThread from '@/components/publish/PostCardThread.vue';
import PostDetailsDialog from '@/components/publish/PostDetailsDialog.vue';
import PostFailurePopover from '@/components/publish/PostFailurePopover.vue';
import PostMetricsBand from '@/components/publish/PostMetricsBand.vue';
+import PostPollResultsList from '@/components/publish/PostPollResultsList.vue';
import PostRecurrenceDialog from '@/components/publish/PostRecurrenceDialog.vue';
import PostRecurrenceSummary from '@/components/publish/PostRecurrenceSummary.vue';
import { Badge } from '@/components/ui/badge';
@@ -67,10 +71,13 @@ import { getPostStatusConfig } from '@/composables/usePostStatus';
import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';
import date from '@/date';
import dayjs from '@/dayjs';
+import { blank, filled } from '@/lib/helpers';
import { isImage, isVideo } from '@/lib/mediaType';
+import { postThreadOf } from '@/lib/postThread';
import { compactPublicationMetrics } from '@/lib/publicationMetrics';
import { recurrenceRuleOf } from '@/lib/recurrence';
import { videoFrameUrl } from '@/lib/videoFrame';
+import { postPollResults } from '@/lib/xPoll';
import { Platform } from '@/types/platform';
import {
PostOrigin,
@@ -209,6 +216,17 @@ const isPending = computed(
() => props.post.status === PostStatus.PendingApproval,
);
+/** What a post without a time shows: the queue slot its approval request asks for, else "No time". */
+const noTimeKey = computed((): string => {
+ const slot = props.post.approval_queue_position;
+
+ if (isPending.value && slot) {
+ return `posts.publish.pending_slot.${slot}`;
+ }
+
+ return 'posts.publish.no_time';
+});
+
const isEditable = computed(
() =>
props.post.status === PostStatus.Draft ||
@@ -253,6 +271,8 @@ const CONTENT_TYPE_ICONS: Record<string, Component> = {
facebook_story: IconCircleDashedPlus,
instagram_reel: IconCirclePlay,
facebook_reel: IconCirclePlay,
+ threads_ghost_post: IconGhost2,
+ x_poll: IconListDetails,
};
const contentTypeIcon = computed(() =>
@@ -273,10 +293,30 @@ const metricsDetail = computed(() => {
return detail && detail.available ? detail : null;
});
-const hasMetrics = computed(() =>
- metricsDetail.value
- ? compactPublicationMetrics(metricsDetail.value).length > 0
- : false,
+const hasMetrics = computed(
+ (): boolean =>
+ filled(metricsDetail.value) &&
+ filled(compactPublicationMetrics(metricsDetail.value)),
+);
+
+/** The publication's results (votes and metrics) show on the Sent tab only. */
+const sentDetail = computed(() => {
+ if (props.tab !== 'sent') {
+ return null;
+ }
+
+ return metricsDetail.value;
+});
+
+/** The post's thread, each post with its own text, media and poll. */
+const thread = computed(() => postThreadOf(props.post));
+
+/** The post's polls in every tab, with no votes until X has been read for them. */
+const polls = computed(() => postPollResults(props.post));
+
+/** On the Approvals tab every card is a request, so the badge would say nothing. */
+const showsApprovalBadge = computed(
+ (): boolean => isPending.value && props.tab !== 'approvals',
);
const showStatus = computed(
@@ -415,12 +455,17 @@ defineExpose({ openDetails });
>
{{ formatTime(time) }}
</time>
- <span v-else class="text-sm font-medium text-muted-foreground">
- {{ $t('posts.publish.no_time') }}
+ <span
+ v-else
+ class="text-sm font-medium whitespace-nowrap text-muted-foreground"
+ data-single-line
+ :data-testid="`post-no-time-${post.id}`"
+ >
+ {{ $t(noTimeKey) }}
</span>
</span>
<Badge
- v-if="isPending"
+ v-if="showsApprovalBadge"
variant="warning"
class="h-6 gap-1 px-2 [&>svg]:size-4"
:data-testid="`post-approval-badge-${post.id}`"
@@ -595,7 +640,16 @@ defineExpose({ openDetails });
{{ $t(contentTypeKey) }}
</Badge>
</div>
+ <PostCardThread
+ v-if="filled(thread) && account"
+ :account="account"
+ :name="account.display_label"
+ :posts="thread"
+ :poll-test-id="`post-poll-${post.id}`"
+ :test-key="post.id"
+ />
<p
+ v-else
class="line-clamp-4 text-sm whitespace-pre-line text-foreground"
:class="{
'text-muted-foreground': !preview,
@@ -605,7 +659,7 @@ defineExpose({ openDetails });
</p>
</div>
<div
- v-if="thumbnails.length"
+ v-if="thumbnails.length && blank(thread)"
class="relative z-10 grid w-24 shrink-0 content-start gap-2"
:class="[
thumbnails.length > 1 ? 'grid-cols-2' : '',
@@ -681,9 +735,16 @@ defineExpose({ openDetails });
:test-key="post.id"
/>
+ <PostPollResultsList
+ v-if="blank(thread)"
+ :poll="polls.poll"
+ :thread-polls="polls.threadPolls"
+ :test-id="`post-poll-${post.id}`"
+ />
+
<PostMetricsBand
- v-if="tab === 'sent' && metricsDetail && hasMetrics"
- :detail="metricsDetail"
+ v-if="sentDetail && hasMetrics"
+ :detail="sentDetail"
:channel-id="account?.id ?? null"
:metrics-test-id="`post-metrics-${post.id}`"
:insights-test-id="`post-insights-${post.id}`"
diff --git a/resources/js/components/publish/PublishTabs.vue b/resources/js/components/publish/PublishTabs.vue
index 7cb20dd87..5eb9f046a 100644
--- a/resources/js/components/publish/PublishTabs.vue
+++ b/resources/js/components/publish/PublishTabs.vue
@@ -84,7 +84,7 @@ const closeSelect = (): void => {
:href="hrefFor(key)"
:aria-current="tab === key ? 'page' : undefined"
:data-testid="`publish-tab-${key}`"
- class="relative inline-flex h-[45px] shrink-0 items-center gap-2 px-2 text-sm font-medium transition-control after:absolute after:inset-x-0.5 after:-bottom-px after:h-px after:bg-primary-text after:opacity-0 aria-[current=page]:after:opacity-100"
+ class="group relative inline-flex h-[45px] shrink-0 items-center gap-2 px-2 text-sm font-medium transition-control after:absolute after:inset-x-0.5 after:-bottom-px after:h-px after:bg-primary-text after:opacity-0 aria-[current=page]:after:opacity-100"
:class="
tab === key
? 'text-foreground'
@@ -93,7 +93,7 @@ const closeSelect = (): void => {
>
{{ $t(`posts.publish.tabs.${key}`) }}
<span
- class="inline-flex h-4.5 min-w-4.5 items-center justify-center rounded-full bg-secondary px-1 text-xs font-medium text-foreground"
+ class="inline-flex h-4.5 min-w-4.5 items-center justify-center rounded-full bg-secondary px-1 text-xs font-medium text-foreground group-aria-[current=page]:bg-primary-selected group-aria-[current=page]:text-primary-text"
:data-testid="`publish-tab-count-${key}`"
>{{ counts[key] }}</span
>
diff --git a/resources/js/composables/composer/useComposerPoll.ts b/resources/js/composables/composer/useComposerPoll.ts
new file mode 100644
index 000000000..2b0d97eba
--- /dev/null
+++ b/resources/js/composables/composer/useComposerPoll.ts
@@ -0,0 +1,294 @@
+import type {
+ ComposerAccount,
+ NetworkGroup,
+ usePostComposition,
+} from '@/composables/usePostComposition';
+import { blank, filled, transform } from '@/lib/helpers';
+import { type ThreadReply, withReplyPoll } from '@/lib/threadReplies';
+import { newPoll } from '@/lib/xPoll';
+import {
+ ContentType,
+ MEDIALESS_CONTENT_TYPE_REASONS,
+} from '@/types/content-type';
+import type { XPoll, XPollLimits } from '@/types/x';
+
+/** What the composer gives the card polls: each card's destination and the override that changes it. */
+type ComposerCards = Pick<
+ ReturnType<typeof usePostComposition>,
+ 'resolvedDestination' | 'setGroupOverride'
+>;
+
+/** What the composer's thread gives the reply polls: the reply being edited, the replies, a reply's text limit, and whether a reply's file is still uploading. */
+export interface ComposerThread {
+ activeReply: (group: NetworkGroup) => ThreadReply | undefined;
+ replies: (group: NetworkGroup) => ThreadReply[];
+ setReplies: (group: NetworkGroup, replies: ThreadReply[]) => void;
+ replyLimit: (group: NetworkGroup) => number | null;
+ uploading: (group: NetworkGroup, reply: ThreadReply) => boolean;
+}
+
+/**
+ * The X polls of each composer card: the post's (picking Poll starts one,
+ * editing writes it into the card's meta, and any other type drops it, as the
+ * server does) and each thread reply's (the toolbar's poll button).
+ */
+export const useComposerPoll = (
+ composition: ComposerCards,
+ pollLimits: (account: ComposerAccount) => XPollLimits | null,
+ thread: ComposerThread,
+) => {
+ const destination = (group: NetworkGroup) =>
+ composition.resolvedDestination(group.anchor);
+
+ /** The card's poll limits, or null on a network without polls. */
+ const groupPollLimits = (group: NetworkGroup): XPollLimits | null =>
+ pollLimits(group.anchor);
+
+ /** An account's text limit for its post type: a poll's question keeps the poll's cap, even with long posts. */
+ const accountTextLimit = (
+ account: ComposerAccount,
+ limit: number | undefined,
+ ): number | undefined => {
+ const questionCap = pollLimits(account)?.questionMaxLength;
+ const isPoll =
+ composition.resolvedDestination(account).content_type ===
+ ContentType.XPoll;
+
+ if (isPoll && filled(limit) && filled(questionCap)) {
+ return Math.min(limit, questionCap);
+ }
+
+ return limit;
+ };
+
+ /**
+ * Each card's meta from before a poll was added, put back as it was when
+ * the poll goes and nothing else changed: a post stored without meta
+ * arrives as `[]` (PHP's empty array), and putting back `{}` instead would
+ * count as an unsaved change.
+ */
+ const metaBeforePoll = new Map<string, Record<string, any>>();
+ /**
+ * Each card's meta, poll included, from before another type was picked:
+ * picking Poll again brings the poll back, and the very same object when
+ * nothing else changed, so its keys keep their order and the switch counts
+ * as no change.
+ */
+ const metaBeforeOtherType = new Map<string, Record<string, any>>();
+
+ const isPollGroup = (group: NetworkGroup): boolean =>
+ destination(group).content_type === ContentType.XPoll;
+
+ const groupPoll = (group: NetworkGroup): Partial<XPoll> =>
+ destination(group).meta?.poll ?? {};
+
+ const setGroupPoll = (group: NetworkGroup, poll: XPoll): void => {
+ composition.setGroupOverride(group.key, 'meta', {
+ ...destination(group).meta,
+ poll,
+ });
+ };
+
+ /**
+ * Whether two metas hold the same values in the same key order. A meta
+ * stored empty arrives as `[]` (PHP's empty array) and counts as `{}`.
+ */
+ const sameMeta = (
+ first: Record<string, any>,
+ second: Record<string, any>,
+ ): boolean => JSON.stringify({ ...first }) === JSON.stringify({ ...second });
+
+ /** Takes a card's saved meta out of `saved`, so it is used once. */
+ const takeSaved = (
+ saved: Map<string, Record<string, any>>,
+ group: NetworkGroup,
+ ): Record<string, any> | undefined => {
+ const meta = saved.get(group.key);
+ saved.delete(group.key);
+
+ return meta;
+ };
+
+ /** The card's last poll back on its meta: the very same object when nothing else changed. */
+ const restorePoll = (
+ previous: Record<string, any>,
+ current: Record<string, any>,
+ ): Record<string, any> => {
+ const { poll, ...previousMeta } = previous;
+
+ if (sameMeta(previousMeta, current)) {
+ return previous;
+ }
+
+ return { ...current, poll };
+ };
+
+ /** Picking Poll: the card's last poll comes back, else a new one starts. */
+ const metaWithPoll = (
+ group: NetworkGroup,
+ current: Record<string, any>,
+ ): Record<string, any> => {
+ metaBeforePoll.set(group.key, current);
+ const previous = takeSaved(metaBeforeOtherType, group);
+
+ if (filled(previous)) {
+ return restorePoll(previous, current);
+ }
+
+ return { ...current, poll: transform(groupPollLimits(group), newPoll, {}) };
+ };
+
+ /** Picking another type: the poll goes, and the meta from before it comes back when nothing else changed. */
+ const metaWithoutPoll = (
+ group: NetworkGroup,
+ current: Record<string, any>,
+ meta: Record<string, any>,
+ ): Record<string, any> => {
+ metaBeforeOtherType.set(group.key, current);
+ const before = takeSaved(metaBeforePoll, group);
+
+ if (before !== undefined && sameMeta(before, meta)) {
+ return before;
+ }
+
+ return meta;
+ };
+
+ /**
+ * The meta a card takes when its type becomes `contentType`: Poll adds a
+ * poll, any other type drops it. Null when the meta stays as it is.
+ */
+ const pollMetaForContentType = (
+ group: NetworkGroup,
+ contentType: string,
+ ): Record<string, any> | null => {
+ const current = destination(group).meta ?? {};
+ const { poll, ...meta } = current;
+ const hasPoll = poll !== undefined;
+ const picksPoll = contentType === ContentType.XPoll;
+
+ if (picksPoll && !hasPoll) {
+ return metaWithPoll(group, current);
+ }
+
+ if (!picksPoll && hasPoll) {
+ return metaWithoutPoll(group, current, meta);
+ }
+
+ return null;
+ };
+
+ /** Forgets the card's last poll, so picking Poll again starts a new one. */
+ const forgetGroupPoll = (group: NetworkGroup): void => {
+ metaBeforeOtherType.delete(group.key);
+ };
+
+ /** Picks the card's post type, adding or dropping its poll with it. */
+ const setGroupContentType = (
+ group: NetworkGroup,
+ contentType: string,
+ ): void => {
+ const meta = pollMetaForContentType(group, contentType);
+ composition.setGroupOverride(group.key, 'content_type', contentType);
+
+ if (meta !== null) {
+ composition.setGroupOverride(group.key, 'meta', meta);
+ }
+ };
+
+ /** The card's Remove poll: back to a plain post, and picking Poll again starts a new one. */
+ const removeGroupPoll = (group: NetworkGroup): void => {
+ setGroupContentType(group, ContentType.XPost);
+ forgetGroupPoll(group);
+ };
+
+ /** Forgets every card's last poll and earlier meta: the per-network edits were discarded. */
+ const forgetPolls = (): void => {
+ metaBeforePoll.clear();
+ metaBeforeOtherType.clear();
+ };
+
+ /** A reply poll's question keeps the poll's cap, even on an account with long posts. */
+ const replyPollLimit = (group: NetworkGroup): number =>
+ groupPollLimits(group)?.questionMaxLength ?? Infinity;
+
+ /** A reply's text limit: a poll's question keeps the poll's cap, even on an account with long posts. */
+ const replyTextLimit = (
+ group: NetworkGroup,
+ reply: ThreadReply,
+ ): number | null => {
+ const limit = thread.replyLimit(group);
+
+ if (filled(limit) && filled(reply.poll)) {
+ return Math.min(limit, replyPollLimit(group));
+ }
+
+ return limit;
+ };
+
+ const setReplyPoll = (
+ group: NetworkGroup,
+ replyKey: string,
+ poll: XPoll | undefined,
+ ): void => {
+ const replies = thread.replies(group).map((reply) => {
+ if (reply.key !== replyKey) {
+ return reply;
+ }
+
+ return withReplyPoll(reply, poll);
+ });
+
+ thread.setReplies(group, replies);
+ };
+
+ /** The poll button shows on an X reply that is not a poll yet. */
+ const replyPollAvailable = (group: NetworkGroup): boolean => {
+ const reply = thread.activeReply(group);
+
+ return (
+ filled(reply) && blank(reply.poll) && filled(groupPollLimits(group))
+ );
+ };
+
+ /** Media in the reply (or on its way) keeps the poll button off, saying why. */
+ const replyPollDisabledReasonKey = (group: NetworkGroup): string | null => {
+ const reply = thread.activeReply(group);
+ const carriesMedia =
+ filled(reply) &&
+ (filled(reply.media) || thread.uploading(group, reply));
+
+ if (carriesMedia) {
+ return MEDIALESS_CONTENT_TYPE_REASONS[ContentType.XPoll];
+ }
+
+ return null;
+ };
+
+ const addReplyPoll = (group: NetworkGroup): void => {
+ const reply = thread.activeReply(group);
+ const limits = groupPollLimits(group);
+
+ if (filled(reply) && filled(limits)) {
+ setReplyPoll(group, reply.key, newPoll(limits));
+ }
+ };
+
+ return {
+ groupPollLimits,
+ accountTextLimit,
+ isPollGroup,
+ groupPoll,
+ setGroupPoll,
+ setGroupContentType,
+ removeGroupPoll,
+ forgetGroupPoll,
+ forgetPolls,
+ replyPollLimit,
+ replyTextLimit,
+ setReplyPoll,
+ replyPollAvailable,
+ replyPollDisabledReasonKey,
+ addReplyPoll,
+ };
+};
diff --git a/resources/js/composables/usePlatformLogo.ts b/resources/js/composables/usePlatformLogo.ts
index 39a059176..846bd8377 100644
--- a/resources/js/composables/usePlatformLogo.ts
+++ b/resources/js/composables/usePlatformLogo.ts
@@ -48,7 +48,7 @@ const PLATFORM_CONTENT_TYPES: Record<string, string[]> = {
facebook: ['facebook_post', 'facebook_reel', 'facebook_story'],
tiktok: ['tiktok_video', 'tiktok_photo'],
youtube: ['youtube_short'],
- x: ['x_post'],
+ x: ['x_post', 'x_poll'],
threads: ['threads_post', 'threads_ghost_post'],
pinterest: ['pinterest_pin', 'pinterest_video_pin', 'pinterest_carousel'],
bluesky: ['bluesky_post'],
@@ -63,6 +63,7 @@ const PLATFORM_CONTENT_TYPE_BADGES: Record<string, string[]> = {
'instagram-facebook': ['instagram_reel', 'instagram_story'],
facebook: ['facebook_reel', 'facebook_story'],
threads: ['threads_ghost_post'],
+ x: ['x_poll'],
};
export interface ContentTypeOption {
diff --git a/resources/js/date.ts b/resources/js/date.ts
index a44941d8b..e5fddf72b 100644
--- a/resources/js/date.ts
+++ b/resources/js/date.ts
@@ -351,6 +351,11 @@ export default {
return dayjs.utc(date).tz(getUserTimezone());
},
+ /** Whether a UTC instant is behind now, compared as instants (the zone does not matter). */
+ hasPassed(date: string) {
+ return dayjs.utc(date).isBefore(dayjs());
+ },
+
diffForHumans(date: string) {
return dayjs().to(dayjs.utc(date));
},
diff --git a/resources/js/lib/helpers.ts b/resources/js/lib/helpers.ts
new file mode 100644
index 000000000..813064bdd
--- /dev/null
+++ b/resources/js/lib/helpers.ts
@@ -0,0 +1,58 @@
+/**
+ * Laravel's `blank()` and `filled()` for the front end, so an emptiness check
+ * reads the same on both sides. They follow PHP's rules, kept equal by
+ * `HelpersParityTest`: null, undefined, a string of only whitespace and an
+ * empty array or plain object are blank; numbers and booleans (zero and false
+ * included) and any other object, like a Date, never are.
+ */
+export const blank = (value: unknown): boolean => {
+ if (value === null || value === undefined) {
+ return true;
+ }
+
+ if (typeof value === 'string') {
+ return value.trim() === '';
+ }
+
+ if (Array.isArray(value)) {
+ return value.length === 0;
+ }
+
+ if (Object.getPrototypeOf(value) === Object.prototype) {
+ return Object.keys(value).length === 0;
+ }
+
+ return false;
+};
+
+/** The opposite of `blank()`; a filled value is never null or undefined. */
+export const filled = <T>(value: T): value is NonNullable<T> => !blank(value);
+
+/**
+ * Laravel's `isEmpty()` on a string (`Str::of()`) or a list (`collect()`): no
+ * characters or no items. Unlike `blank()`, a string of spaces is not empty.
+ */
+export const isEmpty = (value: string | unknown[]): boolean =>
+ value.length === 0;
+
+/** Whether a value is a string, like PHP's `is_string()`. */
+export const isString = (value: unknown): value is string =>
+ typeof value === 'string';
+
+/** Whether a value is a number, like PHP's `is_int()` or `is_float()`; NaN is not. */
+export const isNumber = (value: unknown): value is number =>
+ typeof value === 'number' && !Number.isNaN(value);
+
+/**
+ * Laravel's `transform()`: the callback's result when the value is filled,
+ * else the fallback (null by default).
+ */
+export const transform = <T, R, F = null>(
+ value: T,
+ callback: (value: NonNullable<T>) => R,
+ fallback: F = null as F,
+): R | F => (filled(value) ? callback(value) : fallback);
+
+/** Laravel's `Number::clamp()`: the value kept between `min` and `max`. */
+export const clamp = (value: number, min: number, max: number): number =>
+ Math.min(Math.max(value, min), max);
diff --git a/resources/js/lib/inAppHistory.ts b/resources/js/lib/inAppHistory.ts
index 89158b0b6..565d41d46 100644
--- a/resources/js/lib/inAppHistory.ts
+++ b/resources/js/lib/inAppHistory.ts
@@ -47,6 +47,28 @@ export const cameFromAppPage = (): boolean => {
);
};
+/**
+ * Runs `then` once Inertia has written the current page into its history
+ * entry. On a full page load it writes it only after the page has mounted,
+ * and a `preserveUrl` visit answered meanwhile makes it skip that write, which
+ * leaves an entry the browser's Back can never bring back. Returns a cancel,
+ * for a page that unmounts before the write.
+ */
+export const afterPageInHistory = (then: () => void): (() => void) => {
+ if (window.history.state?.page) {
+ then();
+
+ return () => {};
+ }
+
+ const stop = router.on('navigate', () => {
+ stop();
+ then();
+ });
+
+ return stop;
+};
+
let settling: Promise<void> | null = null;
/**
diff --git a/resources/js/lib/postThread.ts b/resources/js/lib/postThread.ts
new file mode 100644
index 000000000..65adee6ae
--- /dev/null
+++ b/resources/js/lib/postThread.ts
@@ -0,0 +1,67 @@
+import { blank } from '@/lib/helpers';
+import {
+ isBlankThreadReply,
+ type ThreadReply,
+ threadRepliesOf,
+} from '@/lib/threadReplies';
+import { postPollResults } from '@/lib/xPoll';
+import type {
+ PublicationPoll,
+ PublicationThreadPoll,
+} from '@/types/analytics';
+import type { MediaItem } from '@/types/media';
+import { THREAD_PLATFORMS } from '@/types/network-options';
+import type { PostCard } from '@/types/publish';
+
+/** One post of a thread as the post card and its details show it, with its own poll. */
+export type ThreadPost = {
+ text: string;
+ media: MediaItem[];
+ poll: PublicationPoll | null;
+ /** Added to the poll's test id: none for the first post, `-reply-{n}` for a reply. */
+ pollTestSuffix: string;
+};
+
+const replyPostOf = (
+ reply: ThreadReply,
+ index: number,
+ polls: PublicationThreadPoll[],
+): ThreadPost => ({
+ text: reply.text,
+ media: reply.media,
+ poll: polls.find((poll) => poll.reply === index) ?? null,
+ pollTestSuffix: `-reply-${index}`,
+});
+
+/**
+ * Every post of a post's thread in publishing order, the first one included,
+ * each with its text, media and poll, as the composer previews them. Empty
+ * when the post has no reply to show.
+ */
+export const postThreadOf = (post: PostCard): ThreadPost[] => {
+ if (!THREAD_PLATFORMS.includes(post.platform ?? '')) {
+ return [];
+ }
+
+ const { poll, threadPolls } = postPollResults(post);
+ const replies = threadRepliesOf(post.meta).flatMap((reply, index) => {
+ if (isBlankThreadReply(reply)) {
+ return [];
+ }
+
+ return [replyPostOf(reply, index, threadPolls)];
+ });
+
+ if (blank(replies)) {
+ return [];
+ }
+
+ const first: ThreadPost = {
+ text: post.content?.trim() ?? '',
+ media: post.media ?? [],
+ poll,
+ pollTestSuffix: '',
+ };
+
+ return [first, ...replies];
+};
diff --git a/resources/js/lib/threadReplies.ts b/resources/js/lib/threadReplies.ts
index 1e573a54f..42febafb3 100644
--- a/resources/js/lib/threadReplies.ts
+++ b/resources/js/lib/threadReplies.ts
@@ -1,15 +1,21 @@
+import { blank, filled, isEmpty } from '@/lib/helpers';
import { uuid } from '@/lib/uuid';
+import { ContentType } from '@/types/content-type';
import type { MediaItem } from '@/types/media';
+import { THREAD_REPLY_CONTENT_TYPES } from '@/types/network-options';
+import type { XPoll } from '@/types/x';
/**
* One post of a thread after the first. `key` only lives in the composer: it
* keeps an upload attached to its reply while replies are added or removed
- * above it, and the server drops it.
+ * above it, and the server drops it. On X a reply may carry a poll instead of
+ * media, its text being the question.
*/
export type ThreadReply = {
key: string;
text: string;
media: MediaItem[];
+ poll?: Partial<XPoll>;
};
export const newThreadReply = (): ThreadReply => ({
@@ -18,31 +24,64 @@ export const newThreadReply = (): ThreadReply => ({
media: [],
});
-/** Replies stored as plain strings are text-only replies. */
+/** A reply with nothing in it yet: no text, no media and no poll. */
+export const isBlankThreadReply = ({
+ text,
+ media,
+ poll,
+}: ThreadReply): boolean =>
+ isEmpty(text) && blank(media) && blank(poll);
+
+/** A reply as the server stores it; `key` only exists in a draft the composer saved. */
+type StoredThreadReply = Omit<ThreadReply, 'key'> & { key?: string };
+
+/** A stored reply as the composer edits it, keyed by its position when it has no key yet. */
+const fromStored = (
+ { key, text, media, poll }: StoredThreadReply,
+ index: number,
+): ThreadReply =>
+ withReplyPoll({ key: key ?? `stored-${index}`, text, media }, poll);
+
+/** The replies of a post's thread, read from its meta. */
export const threadRepliesOf = (
meta: Record<string, any> | null | undefined,
-): ThreadReply[] =>
- Array.isArray(meta?.thread_replies)
- ? meta.thread_replies.map(
- (reply: unknown, index: number): ThreadReply => {
- const stored =
- reply !== null && typeof reply === 'object'
- ? (reply as Partial<ThreadReply>)
- : {};
-
- return {
- key:
- typeof stored.key === 'string'
- ? stored.key
- : `stored-${index}`,
- text:
- typeof reply === 'string'
- ? reply
- : typeof stored.text === 'string'
- ? stored.text
- : '',
- media: Array.isArray(stored.media) ? stored.media : [],
- };
- },
- )
- : [];
+): ThreadReply[] => (meta?.thread_replies ?? []).map(fromStored);
+
+/** The reply as a poll, which carries no media, or as a plain post without one. */
+export const withReplyPoll = (
+ { key, text, media }: ThreadReply,
+ poll: Partial<XPoll> | undefined,
+): ThreadReply => {
+ if (blank(poll)) {
+ return { key, text, media };
+ }
+
+ return { key, text, media: [], poll };
+};
+
+/**
+ * The error a reply shows under its text, from the page's validation errors
+ * under `prefix` (`meta.thread_replies`, or `destinations.{n}.meta.thread_replies`
+ * in a batch): the reply's own, its text's or its media's. Its poll's errors
+ * show under the poll.
+ */
+export const replyErrorOf = (
+ errors: Record<string, string>,
+ prefix: string,
+ index: number,
+): string | undefined =>
+ errors[`${prefix}.${index}`] ??
+ errors[`${prefix}.${index}.text`] ??
+ errors[`${prefix}.${index}.media`];
+
+/** The post type a reply publishes as: a poll, or its network's reply type. */
+export const threadReplyContentType = (
+ platform: string,
+ reply: ThreadReply,
+): string | undefined => {
+ if (filled(reply.poll)) {
+ return ContentType.XPoll;
+ }
+
+ return THREAD_REPLY_CONTENT_TYPES[platform];
+};
diff --git a/resources/js/lib/utils.ts b/resources/js/lib/utils.ts
index 8d1998406..67d85854f 100644
--- a/resources/js/lib/utils.ts
+++ b/resources/js/lib/utils.ts
@@ -85,10 +85,10 @@ export const distinctCountLabels = (values: number[]): string[] => {
};
export const formatPercent = withDash(
- (value: number): string =>
+ (value: number, digits: number = 2): string =>
new Intl.NumberFormat(activeLocale.value, {
style: 'percent',
- maximumFractionDigits: 2,
+ maximumFractionDigits: digits,
}).format(value / 100),
);
diff --git a/resources/js/lib/xPoll.ts b/resources/js/lib/xPoll.ts
new file mode 100644
index 000000000..56700f1a9
--- /dev/null
+++ b/resources/js/lib/xPoll.ts
@@ -0,0 +1,180 @@
+import dayjs from '@/dayjs';
+import { activeLocale } from '@/language';
+import { clamp, filled, transform } from '@/lib/helpers';
+import { threadRepliesOf } from '@/lib/threadReplies';
+import type {
+ PublicationPoll,
+ PublicationThreadPoll,
+} from '@/types/analytics';
+import { ContentType } from '@/types/content-type';
+import type { PublishConfig } from '@/types/platform';
+import type { PostCard } from '@/types/publish';
+import type { XPoll, XPollDuration, XPollLimits } from '@/types/x';
+
+export const MINUTES_PER_HOUR = 60;
+export const HOURS_PER_DAY = 24;
+const MINUTES_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR;
+
+/** The poll limits in an account's `publishConfig`, or null on a network without polls. */
+export const pollLimitsOf = (
+ publishConfig: PublishConfig | null | undefined,
+): XPollLimits | null => publishConfig?.poll ?? null;
+
+/** The longest a poll runs, in whole days. */
+export const pollMaxDays = (limits: XPollLimits): number =>
+ Math.floor(limits.maxDuration / MINUTES_PER_DAY);
+
+export const splitPollDuration = (minutes: number): XPollDuration => ({
+ days: Math.floor(minutes / MINUTES_PER_DAY),
+ hours: Math.floor((minutes % MINUTES_PER_DAY) / MINUTES_PER_HOUR),
+ minutes: minutes % MINUTES_PER_HOUR,
+});
+
+/** Minutes for the picked parts, within the poll's shortest and longest length; the longest takes no hours or minutes. */
+export const joinPollDuration = (
+ parts: XPollDuration,
+ limits: XPollLimits,
+): number => {
+ if (parts.days >= pollMaxDays(limits)) return limits.maxDuration;
+
+ const total =
+ parts.days * MINUTES_PER_DAY +
+ parts.hours * MINUTES_PER_HOUR +
+ parts.minutes;
+
+ return clamp(total, limits.minDuration, limits.maxDuration);
+};
+
+export const newPoll = (limits: XPollLimits): XPoll => ({
+ options: Array.from({ length: limits.minOptions }, () => ''),
+ duration_minutes: limits.defaultDuration,
+});
+
+/**
+ * A choice's length as X counts it, without the spaces around it: in UTF-16
+ * units (a string's `length`), so an emoji like 🐧 counts two, as on the server
+ * (`XPoll::choiceLength()`).
+ */
+export const pollChoiceLength = (choice: string): number => choice.trim().length;
+
+/**
+ * A choice cut to the longest X accepts, counted as X counts it
+ * (`pollChoiceLength`): the last character goes until it fits, so a character
+ * is never split and the spaces before the choice stay.
+ */
+export const fitPollChoice = (choice: string, maxLength: number): string => {
+ let characters = Array.from(choice);
+
+ while (pollChoiceLength(characters.join('')) > maxLength) {
+ characters = characters.slice(0, -1);
+ }
+
+ return characters.join('');
+};
+
+/** The choices the editor shows: the stored ones, padded to the number a poll starts with. */
+export const editablePollOptions = (
+ options: string[] | undefined,
+ minOptions: number,
+): string[] => {
+ const stored = Array.isArray(options) ? options.map(String) : [];
+
+ return Array.from(
+ { length: Math.max(minOptions, stored.length) },
+ (_, index) => stored[index] ?? '',
+ );
+};
+
+/** The units a poll's length is shown in, largest first, with their minutes. */
+const POLL_LENGTH_UNITS = [
+ ['day', MINUTES_PER_DAY],
+ ['hour', MINUTES_PER_HOUR],
+ ['minute', 1],
+] as const;
+
+/** The poll's length in its largest whole unit, as X shows it ("1 day", "23 hours", "5 minutes"). */
+export const formatPollLength = (minutes: number): string => {
+ const [unit, size] =
+ POLL_LENGTH_UNITS.find(([, size]) => minutes >= size) ??
+ POLL_LENGTH_UNITS[POLL_LENGTH_UNITS.length - 1];
+
+ return new Intl.NumberFormat(activeLocale.value, {
+ style: 'unit',
+ unit,
+ unitDisplay: 'long',
+ }).format(Math.floor(minutes / size));
+};
+
+/**
+ * A poll before X has been read for it: its choices with no votes. Once its
+ * post is published it is open until its length from publishing; before
+ * that, voting has not started and has no end.
+ */
+const unreadPollResult = (
+ poll: Partial<XPoll>,
+ publishedAt: string | null,
+): PublicationPoll => ({
+ options: (poll.options ?? []).map((label) => ({ label, votes: 0 })),
+ voting_status: transform(publishedAt, (): 'open' => 'open'),
+ end_datetime: transform(publishedAt, (at) =>
+ transform(poll.duration_minutes, (minutes) =>
+ dayjs.utc(at).add(minutes, 'minute').toISOString(),
+ ),
+ ),
+ duration_minutes: poll.duration_minutes ?? null,
+});
+
+/** A post's own poll: only an X poll has one, whatever its meta still holds. */
+const ownPollOf = (post: PostCard): Partial<XPoll> | undefined => {
+ if (post.content_type !== ContentType.XPoll) {
+ return undefined;
+ }
+
+ return post.meta?.poll;
+};
+
+/** A post's own polls (the post's and its replies') with no votes yet. */
+const unreadPollsOf = (
+ post: PostCard,
+): { poll: PublicationPoll | null; threadPolls: PublicationThreadPoll[] } => ({
+ poll: transform(ownPollOf(post), (poll) =>
+ unreadPollResult(poll, post.published_at),
+ ),
+ threadPolls: threadRepliesOf(post.meta).flatMap((reply, index) => {
+ if (filled(reply.poll)) {
+ return [
+ {
+ reply: index,
+ ...unreadPollResult(reply.poll, post.published_at),
+ },
+ ];
+ }
+
+ return [];
+ }),
+});
+
+/**
+ * The polls a post shows, in every tab: each one as X returned it at the last
+ * read, or, until X has been read for it (about an hour after publishing, and
+ * never for a post still in the queue, a draft or a request), with its
+ * choices and no votes.
+ */
+export const postPollResults = (
+ post: PostCard,
+): { poll: PublicationPoll | null; threadPolls: PublicationThreadPoll[] } => {
+ const read = post.metrics?.available ? post.metrics.publication : null;
+ const readReplies = read?.thread_polls ?? [];
+ const unread = unreadPollsOf(post);
+ const unreadReplies = unread.threadPolls.filter(
+ (unreadReply) =>
+ !readReplies.some((readReply) => readReply.reply === unreadReply.reply),
+ );
+
+ return {
+ poll: read?.poll ?? unread.poll,
+ threadPolls: [...readReplies, ...unreadReplies].sort(
+ (first, second) => first.reply - second.reply,
+ ),
+ };
+};
diff --git a/resources/js/pages/posts/Calendar.vue b/resources/js/pages/posts/Calendar.vue
index 244cce01d..1ef83109f 100644
--- a/resources/js/pages/posts/Calendar.vue
+++ b/resources/js/pages/posts/Calendar.vue
@@ -58,6 +58,7 @@ import dayjs from '@/dayjs';
import { activeLocale } from '@/language';
import AppLayout from '@/layouts/AppLayout.vue';
import { calendarDayKey } from '@/lib/calendarItems';
+import { afterPageInHistory } from '@/lib/inAppHistory';
import { calendar } from '@/routes/app';
import {
calendar as channelCalendar,
@@ -144,9 +145,11 @@ provide(
const now = ref(dayjs());
let clock: ReturnType<typeof setInterval> | undefined;
+let cancelSlotsReload = (): void => {};
onUnmounted(() => {
clearInterval(clock);
+ cancelSlotsReload();
});
const userTimezone = computed(
@@ -331,7 +334,9 @@ onMounted(() => {
}, 60_000);
if (showSlots.value && props.slots === undefined) {
- reload(['slots'], [], true);
+ cancelSlotsReload = afterPageInHistory(() =>
+ reload(['slots'], [], true),
+ );
}
});
diff --git a/resources/js/types/analytics.ts b/resources/js/types/analytics.ts
index 5d123bec7..55bb1ab35 100644
--- a/resources/js/types/analytics.ts
+++ b/resources/js/types/analytics.ts
@@ -275,6 +275,18 @@ export interface PublicationMetricFact {
provider_metric?: string | null;
}
+export interface PublicationPoll {
+ options: { label: string; votes: number }[];
+ voting_status: 'open' | 'closed' | null;
+ end_datetime: string | null;
+ duration_minutes: number | null;
+}
+
+/** The poll of one thread reply; `reply` is its position among the replies, from 0. */
+export interface PublicationThreadPoll extends PublicationPoll {
+ reply: number;
+}
+
export interface PublicationAnalyticsDetail {
available: true;
reason: null;
@@ -290,6 +302,8 @@ export interface PublicationAnalyticsDetail {
permalink: string | null;
excerpt: string | null;
preview_metadata: Record<string, unknown> | null;
+ poll: PublicationPoll | null;
+ thread_polls: PublicationThreadPoll[];
account_display_name: string | null;
account_username: string | null;
account_avatar_url: string | null;
diff --git a/resources/js/types/channel.ts b/resources/js/types/channel.ts
index dd517b275..ff797b97d 100644
--- a/resources/js/types/channel.ts
+++ b/resources/js/types/channel.ts
@@ -1,4 +1,5 @@
import type { PinterestBoard } from '@/types';
+import type { PublishConfig } from '@/types/platform';
import type { VerifiedBadge } from '@/types/social-account';
import type { SocialAccountStatusValue } from '@/types/social-account-status';
import type { TikTokPrivacyLevelValue } from '@/types/tiktok-privacy';
@@ -37,7 +38,7 @@ export interface Channel {
issueDocsUrl?: string | null;
status?: string | null;
contentTypeError?: string;
- publishConfig?: Record<string, any> | null;
+ publishConfig?: PublishConfig | null;
creatorInfo?: ChannelTikTokCreatorInfo | null;
boards?: PinterestBoard[];
boardsTruncated?: boolean;
diff --git a/resources/js/types/content-type.ts b/resources/js/types/content-type.ts
index 274947504..e1e8102fb 100644
--- a/resources/js/types/content-type.ts
+++ b/resources/js/types/content-type.ts
@@ -11,6 +11,7 @@ export const ContentType = {
TikTokPhoto: 'tiktok_photo',
YouTubeShort: 'youtube_short',
XPost: 'x_post',
+ XPoll: 'x_poll',
ThreadsPost: 'threads_post',
ThreadsGhostPost: 'threads_ghost_post',
PinterestPin: 'pinterest_pin',
@@ -31,7 +32,13 @@ export const CAPTIONLESS_CONTENT_TYPES: ReadonlySet<string> = new Set([
ContentType.InstagramStory,
]);
+/** Content types that carry no media, with why a card holding media cannot switch to one (`maxMediaCount()` 0 on the server). */
+export const MEDIALESS_CONTENT_TYPE_REASONS: Readonly<Record<string, string>> = {
+ [ContentType.ThreadsGhostPost]: 'posts.form.threads.ghost_post_attachments',
+ [ContentType.XPoll]: 'posts.form.x.poll.attachments',
+};
+
/** Content types that carry no media: the composer hides the media tray. */
-export const MEDIALESS_CONTENT_TYPES: ReadonlySet<string> = new Set([
- ContentType.ThreadsGhostPost,
-]);
+export const MEDIALESS_CONTENT_TYPES: ReadonlySet<string> = new Set(
+ Object.keys(MEDIALESS_CONTENT_TYPE_REASONS),
+);
diff --git a/resources/js/types/platform.ts b/resources/js/types/platform.ts
index d0744d1a4..9afd3cfb2 100644
--- a/resources/js/types/platform.ts
+++ b/resources/js/types/platform.ts
@@ -1,3 +1,5 @@
+import type { XPollLimits } from '@/types/x';
+
export const Platform = {
LinkedIn: 'linkedin',
LinkedInPage: 'linkedin-page',
@@ -17,3 +19,16 @@ export const Platform = {
} as const;
export type PlatformValue = (typeof Platform)[keyof typeof Platform];
+
+/** What `Platform::publishConfig()` serves for an account: each network fills only its own keys. */
+export interface PublishConfig {
+ /** TikTok: the privacy levels the creator may pick, and the policy links. */
+ privacyLevelOptions?: string[];
+ musicUsageConfirmationUrl?: string;
+ brandedContentPolicyUrl?: string;
+ /** YouTube: the category list and the default category. */
+ categoryOptions?: { value: string; labelKey: string }[];
+ defaultCategoryId?: string;
+ /** X: the poll limits. */
+ poll?: XPollLimits;
+}
diff --git a/resources/js/types/x.ts b/resources/js/types/x.ts
new file mode 100644
index 000000000..3b94e761a
--- /dev/null
+++ b/resources/js/types/x.ts
@@ -0,0 +1,23 @@
+/** The poll limits X sets, served by `Platform::publishConfig()` (`publishConfig.poll`). */
+export interface XPollLimits {
+ minOptions: number;
+ maxOptions: number;
+ optionMaxLength: number;
+ minDuration: number;
+ maxDuration: number;
+ defaultDuration: number;
+ questionMaxLength: number;
+}
+
+/** A poll's length split into the units the editor picks. */
+export interface XPollDuration {
+ days: number;
+ hours: number;
+ minutes: number;
+}
+
+/** An X poll as `meta.poll` (or a thread reply's `poll`) stores it. */
+export interface XPoll {
+ options: string[];
+ duration_minutes: number;
+}
diff --git a/tests/Browser/CalendarPageTest.php b/tests/Browser/CalendarPageTest.php
index 995c7ce56..fb85ac538 100644
--- a/tests/Browser/CalendarPageTest.php
+++ b/tests/Browser/CalendarPageTest.php
@@ -384,6 +384,38 @@ test('show posting times renders empty slots in the week and month views', funct
$month->assertNoJavaScriptErrors();
});
+test('a calendar opened by its link asks for its posting times only once its page is in the browser history, so Back still returns to it', function () {
+ [$user, $linkedin] = calendarPageSetup();
+ $post = calendarPagePost($linkedin, now('UTC')->startOfWeek()->addWeek()->addDays(2)->setTime(10, 0));
+ $this->actingAs($user);
+
+ $page = visit(route('app.settings.preferences'));
+ $page->page()->context()->addInitScript(<<<'JS'
+ window.__slotsAskedWith = [];
+ const setRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
+ XMLHttpRequest.prototype.setRequestHeader = function (name, value) {
+ if (name.toLowerCase() === 'x-inertia-partial-data' && String(value).split(',').includes('slots')) {
+ window.__slotsAskedWith.push(window.history.state?.page ? 'page' : 'nothing');
+ }
+
+ return setRequestHeader.call(this, name, value);
+ };
+ JS);
+ $page->navigate(route('app.calendar', ['view' => 'week']));
+ waitForCondition($page, 'window.__slotsAskedWith.length === 1');
+
+ expect($page->script('window.__slotsAskedWith'))->toBe(['page']);
+
+ $page->click('@calendar-next');
+ waitFor($page, "@calendar-post-{$post->id}");
+ $page->back();
+ waitForGone($page, "@calendar-post-{$post->id}");
+
+ $page->assertPathIs(route('app.calendar', ['view' => 'week'], false))
+ ->assertScript("new URLSearchParams(location.search).has('week')", false)
+ ->assertNoJavaScriptErrors();
+});
+
test('in the month a post shows its network in color and a status icon with a tooltip, and a free posting time reads as a hatched empty slot', function () {
[$user, $linkedin] = calendarPageSetup();
$schedule = PostingSchedule::empty();
diff --git a/tests/Browser/ComposerChannelSettingsTest.php b/tests/Browser/ComposerChannelSettingsTest.php
index 806c29189..b8f9a84fc 100644
--- a/tests/Browser/ComposerChannelSettingsTest.php
+++ b/tests/Browser/ComposerChannelSettingsTest.php
@@ -908,8 +908,9 @@ test('the threads card offers a topic and a ghost post drops the topic and the m
->assertMissing("@composer-{$id}-media-source-menu")
->assertVisible("@composer-{$id}-media-source-disabled")
->hover("@composer-{$id}-media-source-disabled");
- waitForText($page, '[data-slot="tooltip-content"]', __('posts.composer.media_not_supported'));
- $page->click("@composer-type-{$id}-threads_post");
+ waitForText($page, '[data-slot="tooltip-content"]', __('posts.form.threads.ghost_post_attachments'));
+ $page->assertSeeIn('[data-slot="tooltip-content"]', __('posts.form.threads.ghost_post_attachments'))
+ ->click("@composer-type-{$id}-threads_post");
waitFor($page, '@threads-topic-tag');
$page->assertVisible("@composer-{$id}-media-source-menu")
->assertMissing("@composer-{$id}-media-source-disabled")
@@ -1018,12 +1019,39 @@ test('a server error on a thread reply shows under that reply', function () {
->assertNoJavaScriptErrors();
});
+test('a Mastodon reply keeps its media inside the preview, in line with its text', function () {
+ fakeChannelSettingsApis();
+ $post = seedChannelSettingsPost(Platform::Mastodon, ContentType::MastodonPost);
+ $image = Media::factory()->ownedByPost($post)->create(['mime_type' => 'image/png']);
+ $post->update(['meta' => ['thread_replies' => [['text' => 'With a photo', 'media' => [MediaItem::fromMedia($image)->toArray()]]]]]);
+
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
+ waitFor($page, '@preview-thread-reply-0 img');
+
+ $edges = $page->script(<<<'JS'
+ (() => {
+ const reply = document.querySelector('[data-testid="preview-thread-reply-0"]');
+ const walker = document.createTreeWalker(reply, NodeFilter.SHOW_TEXT, (node) => node.textContent.includes('With a photo') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP);
+ const text = document.createRange();
+ text.selectNodeContents(walker.nextNode());
+ const image = reply.querySelector('img').getBoundingClientRect();
+ const box = reply.getBoundingClientRect();
+
+ return { gap: box.right - image.right, offset: Math.abs(Math.round(image.left - text.getBoundingClientRect().left)) };
+ })()
+ JS);
+
+ expect($edges['gap'])->toBeGreaterThanOrEqual(16)
+ ->and($edges['offset'])->toBeLessThanOrEqual(1);
+ $page->assertNoJavaScriptErrors();
+});
+
test('a thread reply shows its own media under it and keeps it on save', function () {
fakeChannelSettingsApis();
$post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
$id = $post->social_account_id;
$image = Media::factory()->ownedByPost($post)->create(['mime_type' => 'image/png']);
- $post->update(['meta' => ['thread_replies' => [['text' => 'With a photo', 'media' => [MediaItem::fromMedia($image)->toArray()]], 'Plain reply']]]);
+ $post->update(['meta' => ['thread_replies' => [['text' => 'With a photo', 'media' => [MediaItem::fromMedia($image)->toArray()]], ['text' => 'Plain reply', 'media' => []]]]]);
$page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitFor($page, "@composer-{$id}-reply-0-media-item-0");
@@ -1059,7 +1087,7 @@ test('a thread reply shows its own media under it and keeps it on save', functio
test('the mastodon preview hides the post behind its content warning on every post of the thread', function () {
fakeChannelSettingsApis();
$post = seedChannelSettingsPost(Platform::Mastodon, ContentType::MastodonPost);
- $post->update(['meta' => ['spoiler_text' => 'Spoilers', 'thread_replies' => ['Hidden reply']]]);
+ $post->update(['meta' => ['spoiler_text' => 'Spoilers', 'thread_replies' => [['text' => 'Hidden reply', 'media' => []]]]]);
$page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitFor($page, '@mastodon-preview-content-warning');
@@ -1149,7 +1177,7 @@ test('arrow keys move between the posts of a thread from the end and the start o
fakeChannelSettingsApis();
$post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
$post->update(['content' => 'Root']);
- $post->update(['meta' => ['thread_replies' => ['First reply', 'Second reply']]]);
+ $post->update(['meta' => ['thread_replies' => [['text' => 'First reply', 'media' => []], ['text' => 'Second reply', 'media' => []]]]]);
$id = $post->social_account_id;
$page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
@@ -1184,7 +1212,11 @@ test('the preview scrolls to the thread post being edited', function () {
fakeChannelSettingsApis();
$post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
$post->update(['content' => str_repeat('Root post text. ', 40)]);
- $post->update(['meta' => ['thread_replies' => [str_repeat('First reply text. ', 40), str_repeat('Second reply text. ', 40), 'Last reply']]]);
+ $post->update(['meta' => ['thread_replies' => [
+ ['text' => str_repeat('First reply text. ', 40), 'media' => []],
+ ['text' => str_repeat('Second reply text. ', 40), 'media' => []],
+ ['text' => 'Last reply', 'media' => []],
+ ]]]);
$id = $post->social_account_id;
$page = visit(route('app.posts.edit', $post))->resize(1280, 700);
diff --git a/tests/Browser/ComposerXPollTest.php b/tests/Browser/ComposerXPollTest.php
new file mode 100644
index 000000000..2f6641151
--- /dev/null
+++ b/tests/Browser/ComposerXPollTest.php
@@ -0,0 +1,985 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Ai\Agents\PostWritingAssistant;
+use App\Dto\MediaItem;
+use App\Enums\Post\Status;
+use App\Enums\PostPlatform\ContentType;
+use App\Enums\SocialAccount\Platform;
+use App\Models\Media;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use App\Support\Social\XPoll;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Str;
+use Laravel\Ai\Prompts\AgentPrompt;
+
+/**
+ * @param array<string, mixed> $attributes
+ * @param array<string, mixed> $accountMeta
+ * @param array<string, mixed> $userAttributes
+ */
+function seedXPollPost(ContentType $contentType = ContentType::XPost, array $attributes = [], array $accountMeta = [], array $userAttributes = []): Post
+{
+ Http::fake(['*' => Http::response([], 200)]);
+
+ $user = User::factory()->create($userAttributes);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $workspace->members()->attach($user->id, membershipPivot('member'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ connectAiTo($user);
+
+ $account = SocialAccount::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'platform' => Platform::X,
+ 'username' => 'trypostit',
+ 'access_token' => 'x-token',
+ 'token_expires_at' => now()->addDays(20),
+ 'meta' => $accountMeta,
+ ]);
+
+ $post = Post::factory()->forAccount($account, $contentType)->create([
+ 'user_id' => $user->id,
+ 'content' => 'Which network brings you the most customers?',
+ ...$attributes,
+ ]);
+
+ test()->actingAs($user);
+
+ return $post;
+}
+
+function openXPollComposer(Post $post): mixed
+{
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
+ waitFor($page, "@composer-type-{$post->social_account_id}-x_poll");
+
+ return $page;
+}
+
+function pickXPoll(mixed $page, Post $post): void
+{
+ $page->click("@composer-type-{$post->social_account_id}-x_poll");
+ waitFor($page, '@x-poll-choice-0');
+}
+
+test('picking poll shows two choices and turns media off', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+
+ $page->assertVisible("@composer-{$id}-media-source-menu");
+ pickXPoll($page, $post);
+
+ $page->assertVisible('@x-poll-choice-1')
+ ->assertMissing('@x-poll-choice-2')
+ ->assertMissing("@composer-{$id}-dropzone")
+ ->assertMissing("@composer-{$id}-media-source-menu")
+ ->assertVisible("@composer-{$id}-media-source-disabled")
+ ->hover("@composer-{$id}-media-source-disabled");
+ waitForText($page, '[data-slot="tooltip-content"]', __('posts.form.x.poll.attachments'));
+ $page->assertSeeIn('[data-slot="tooltip-content"]', __('posts.form.x.poll.attachments'))
+ ->assertNoJavaScriptErrors();
+});
+
+test('adds choices up to four and removes one', function () {
+ $post = seedXPollPost();
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->assertMissing('@x-poll-remove-choice-0')
+ ->assertMissing('@x-poll-remove-choice-1')
+ ->click('@x-poll-add-choice');
+ waitFor($page, '@x-poll-choice-2');
+ $page->click('@x-poll-add-choice');
+ waitFor($page, '@x-poll-choice-3');
+ $page->assertMissing('@x-poll-add-choice')
+ ->assertVisible('@x-poll-remove-choice-2')
+ ->click('@x-poll-remove-choice-3');
+ waitForGone($page, '@x-poll-choice-3');
+
+ $page->assertVisible('@x-poll-choice-2')
+ ->assertVisible('@x-poll-add-choice')
+ ->fill('@x-poll-choice-0', 'Yes');
+ waitForText($page, '@x-poll-choice-0-count', '3 / 25');
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a new choice takes focus after one was removed', function () {
+ $post = seedXPollPost();
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->click('@x-poll-add-choice');
+ waitFor($page, '@x-poll-choice-2');
+ $page->fill('@x-poll-choice-2', 'Maybe')
+ ->click('@x-poll-add-choice');
+ waitFor($page, '@x-poll-choice-3');
+ $page->click('@x-poll-remove-choice-2');
+ waitForGone($page, '@x-poll-choice-3');
+ $page->click('@x-poll-add-choice');
+ waitFor($page, '@x-poll-choice-3');
+
+ waitForState($page, '@x-poll-choice-3', 'element === document.activeElement');
+ expect($page->script('document.activeElement?.dataset.testid'))->toBe('x-poll-choice-3')
+ ->and($page->script('document.activeElement.value'))->toBe('')
+ ->and($page->script("document.querySelector('[data-testid=\"x-poll-choice-2\"]').value"))->toBe('');
+ $page->assertNoJavaScriptErrors();
+});
+
+test('duplicate choices show the error under the choices', function () {
+ $post = seedXPollPost(ContentType::XPost, ['status' => Status::Scheduled, 'scheduled_at' => now()->addDay()]);
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->fill('@x-poll-choice-0', 'Yes')
+ ->fill('@x-poll-choice-1', 'yes')
+ ->click('@composer-submit');
+ waitForText($page, '@x-poll-options-error', __('posts.form.x.poll.options_distinct'));
+
+ $page->assertSeeIn('@x-poll-options-error', __('posts.form.x.poll.options_distinct'))
+ ->assertVisible('@post-composer-dialog')
+ ->assertNoJavaScriptErrors();
+});
+
+test('seven days zeroes hours and minutes', function () {
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1520]]]);
+ $page = openXPollComposer($post);
+ waitFor($page, '@x-poll-days');
+
+ $page->assertSeeIn('@x-poll-days', '1')
+ ->assertSeeIn('@x-poll-hours', '1')
+ ->assertSeeIn('@x-poll-minutes', '20')
+ ->click('@x-poll-days');
+ waitFor($page, '@x-poll-days-7');
+ $page->click('@x-poll-days-7');
+ waitForText($page, '@x-poll-days', '7');
+
+ $page->assertSeeIn('@x-poll-hours', '0')
+ ->assertSeeIn('@x-poll-minutes', '0')
+ ->assertNoJavaScriptErrors();
+
+ $page->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+
+ expect(data_get($post->fresh()->meta, 'poll.duration_minutes'))->toBe(10080);
+});
+
+test('remove poll returns to post', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->assertMissing("@composer-{$id}-dropzone")
+ ->click('@x-poll-remove');
+ waitForGone($page, '@x-poll-choice-0');
+
+ $page->assertAttribute("@composer-type-{$id}-x_post", 'aria-checked', 'true')
+ ->assertPresent("@composer-{$id}-dropzone")
+ ->assertVisible("@composer-{$id}-media-source-menu")
+ ->assertNoJavaScriptErrors();
+
+ $page->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+
+ expect($post->fresh()->content_type)->toBe(ContentType::XPost)
+ ->and($post->fresh()->meta)->toEqual([]);
+});
+
+test('poll is disabled while the card has media', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $image = Media::factory()->ownedByPost($post)->create(['mime_type' => 'image/png']);
+ $post->update(['media' => [MediaItem::fromMedia($image)->toArray()]]);
+ $page = openXPollComposer($post);
+
+ expect($page->script("document.querySelector('[data-testid=\"composer-type-{$id}-x_poll\"]').disabled"))->toBeTrue();
+
+ $page->hover("@composer-type-{$id}-x_poll-label");
+ waitFor($page, "@composer-type-{$id}-x_poll-reason");
+
+ $page->assertSeeIn("@composer-type-{$id}-x_poll-reason", __('posts.form.x.poll.attachments'))
+ ->assertNoJavaScriptErrors();
+});
+
+test('the preview shows the choices and length', function () {
+ $post = seedXPollPost();
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->fill('@x-poll-choice-0', 'Yes')
+ ->fill('@x-poll-choice-1', 'No');
+ waitForText($page, '@x-preview-poll', 'No');
+
+ $page->assertSeeIn('@x-preview-poll', 'Yes')
+ ->assertSeeIn('@x-preview-poll', '1 day left')
+ ->assertNoJavaScriptErrors();
+});
+
+test('schedules a poll', function () {
+ $post = seedXPollPost(ContentType::XPost, ['status' => Status::Scheduled, 'scheduled_at' => now()->addDay()]);
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->fill('@x-poll-choice-0', ' Yes ')
+ ->fill('@x-poll-choice-1', 'No')
+ ->click('@composer-submit');
+ waitForGone($page, '@post-composer-dialog');
+
+ $post->refresh();
+ expect($post->content_type)->toBe(ContentType::XPoll)
+ ->and($post->status)->toBe(Status::Scheduled)
+ ->and($post->meta['poll'])->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => 1440]);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a reopened poll draft shows two choices', function () {
+ $post = seedXPollPost();
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+ expect($post->fresh()->content_type)->toBe(ContentType::XPoll);
+
+ $page = openXPollComposer($post);
+ waitFor($page, '@x-poll-choice-0');
+
+ $page->assertVisible('@x-poll-choice-1')
+ ->assertMissing('@x-poll-choice-2')
+ ->assertNoJavaScriptErrors();
+});
+
+test('editing a choice is an unsaved change', function () {
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]]);
+ $page = openXPollComposer($post);
+ waitFor($page, '@x-poll-choice-0');
+
+ $page->click('@composer-close');
+ waitForGone($page, '@post-composer-dialog');
+ $page->assertMissing('@unsaved-changes-dialog');
+
+ $page = openXPollComposer($post);
+ waitFor($page, '@x-poll-choice-0');
+ $page->click('@x-poll-choice-1')
+ ->fill('@x-poll-choice-1', 'Nope')
+ ->click('@composer-close');
+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');
+
+ $page->assertVisible('@unsaved-changes-dialog')->assertNoJavaScriptErrors();
+});
+
+test('picking poll then post again leaves no unsaved change', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->click("@composer-type-{$id}-x_post");
+ waitForGone($page, '@x-poll-choice-0');
+
+ $page->click('@composer-close');
+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');
+
+ $page->assertMissing('@unsaved-changes-dialog')
+ ->assertMissing('@post-composer-dialog')
+ ->assertNoJavaScriptErrors();
+});
+
+test('switching to post and back to poll brings the typed poll back', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->fill('@x-poll-choice-0', 'Yes')
+ ->fill('@x-poll-choice-1', 'No')
+ ->click('@x-poll-add-choice');
+ waitFor($page, '@x-poll-choice-2');
+ $page->fill('@x-poll-choice-2', 'Maybe')
+ ->click('@x-poll-days');
+ waitFor($page, '@x-poll-days-3');
+ $page->click('@x-poll-days-3');
+ waitForText($page, '@x-poll-days', '3');
+
+ $page->click("@composer-type-{$id}-x_post");
+ waitForGone($page, '@x-poll-choice-0');
+ pickXPoll($page, $post);
+ waitFor($page, '@x-poll-choice-2');
+
+ expect($page->script('[0, 1, 2].map((index) => document.querySelector(`[data-testid="x-poll-choice-${index}"]`).value)'))->toBe(['Yes', 'No', 'Maybe']);
+ $page->assertSeeIn('@x-poll-days', '3')->assertNoJavaScriptErrors();
+
+ $page->click("@composer-type-{$id}-x_post");
+ waitForGone($page, '@x-poll-choice-0');
+ $page->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+
+ expect($post->fresh()->content_type)->toBe(ContentType::XPost)
+ ->and($post->fresh()->meta)->not->toHaveKey('poll');
+});
+
+test('a saved poll switched to post and back has no unsaved change', function () {
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 4320]]]);
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+ waitFor($page, '@x-poll-choice-2');
+
+ $page->click("@composer-type-{$id}-x_post");
+ waitForGone($page, '@x-poll-choice-0');
+ pickXPoll($page, $post);
+ waitFor($page, '@x-poll-choice-2');
+
+ $page->click('@composer-close');
+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');
+
+ $page->assertMissing('@unsaved-changes-dialog')
+ ->assertMissing('@post-composer-dialog')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a saved draft with a poll on a thread reply closes without an unsaved change', function () {
+ $post = seedXPollPost(attributes: ['meta' => ['thread_replies' => [
+ ['text' => 'Tabs or spaces?', 'media' => [], 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],
+ ]]]);
+ $page = openXPollComposer($post);
+ waitFor($page, '@thread-reply-collapsed-0');
+
+ $page->click('@composer-close');
+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');
+
+ $page->assertMissing('@unsaved-changes-dialog')
+ ->assertMissing('@post-composer-dialog')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a saved poll with other settings switched to post and back has no unsaved change', function () {
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440], 'is_ai_generated' => true]]);
+ $id = $post->social_account_id;
+ expect(array_keys($post->fresh()->meta))->toBe(['poll', 'is_ai_generated']);
+ $page = openXPollComposer($post);
+ waitFor($page, '@x-poll-choice-1');
+
+ $page->click("@composer-type-{$id}-x_post");
+ waitForGone($page, '@x-poll-choice-0');
+ pickXPoll($page, $post);
+
+ $page->click('@composer-close');
+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');
+
+ $page->assertMissing('@unsaved-changes-dialog')
+ ->assertMissing('@post-composer-dialog')
+ ->assertNoJavaScriptErrors();
+});
+
+/**
+ * Opens a new post's composer on the X account of `$post` and LinkedIn, past
+ * step 1, with the X card open.
+ *
+ * @return array{0: mixed, 1: SocialAccount, 2: SocialAccount}
+ */
+function openCustomizedXPollComposer(Post $post): array
+{
+ $x = $post->socialAccount;
+ $linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);
+
+ $page = visit(route('app.posts.create'))->resize(1280, 900);
+ waitForState($page, '@post-composer-dialog', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ $page->click('@composer-add-account');
+ waitFor($page, "@composer-account-option-{$linkedIn->id}");
+ $page->click("@composer-account-option-{$linkedIn->id}");
+ waitFor($page, "@composer-account-option-{$x->id}");
+ $page->click("@composer-account-option-{$x->id}");
+ waitFor($page, '@composer-base-content');
+ $page->fill('@composer-base-content', 'Tabs or spaces?')
+ ->click('@composer-next');
+ waitFor($page, "@composer-account-{$x->id}");
+ $page->click("@composer-account-{$x->id}");
+ waitFor($page, "@composer-type-{$x->id}-x_poll");
+
+ return [$page, $x, $linkedIn];
+}
+
+test('going back to step 1 forgets the poll, so picking poll again starts empty', function () {
+ $post = seedXPollPost();
+ [$page, $x] = openCustomizedXPollComposer($post);
+ $page->click("@composer-type-{$x->id}-x_poll");
+ waitFor($page, '@x-poll-choice-1');
+ $page->fill('@x-poll-choice-0', 'Tabs')
+ ->fill('@x-poll-choice-1', 'Spaces')
+ ->click("@composer-type-{$x->id}-x_post");
+ waitForGone($page, '@x-poll');
+
+ $page->click('@composer-back');
+ waitFor($page, '@composer-back-confirm-go');
+ $page->click('@composer-back-confirm-go');
+ waitFor($page, '@composer-next');
+ $page->click('@composer-next');
+ waitFor($page, "@composer-account-{$x->id}");
+ $page->click("@composer-account-{$x->id}");
+ waitFor($page, "@composer-type-{$x->id}-x_poll");
+ $page->click("@composer-type-{$x->id}-x_poll");
+ waitFor($page, '@x-poll-choice-1');
+
+ $page->assertValue('@x-poll-choice-0', '')
+ ->assertValue('@x-poll-choice-1', '')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a poll picked while x was the only network turns back into a post when another network joins, so shared media saves', function () {
+ $post = seedXPollPost();
+ $x = $post->socialAccount;
+ $linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+
+ $page = visit(route('app.posts.create'))->resize(1280, 900);
+ waitForState($page, '@post-composer-dialog', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ $page->click('@composer-add-account');
+ waitFor($page, "@composer-account-option-{$x->id}");
+ $page->click("@composer-account-option-{$x->id}")
+ ->click('@composer-header');
+ waitForGone($page, "@composer-account-option-{$x->id}");
+ waitFor($page, "@composer-type-{$x->id}-x_poll");
+ $page->click("@composer-type-{$x->id}-x_poll");
+ waitFor($page, '@x-poll-choice-1');
+ $page->fill('@x-poll-choice-0', 'Tabs')
+ ->fill('@x-poll-choice-1', 'Spaces');
+
+ $page->click('@composer-add-account');
+ waitFor($page, "@composer-account-option-{$linkedIn->id}");
+ $page->click("@composer-account-option-{$linkedIn->id}")
+ ->click('@composer-header');
+ waitForGone($page, "@composer-account-option-{$linkedIn->id}");
+ waitFor($page, '@composer-file-input');
+ $page->fill('@composer-base-content', 'Tabs or spaces?');
+ $page->script(<<<JS
+ (() => {
+ const input = document.querySelector('[data-testid="composer-file-input"]');
+ const transfer = new DataTransfer();
+ transfer.items.add(new File([Uint8Array.from(atob('{$png}'), (character) => character.charCodeAt(0))], 'shared.png', { type: 'image/png' }));
+ input.files = transfer.files;
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ })();
+ JS);
+ waitFor($page, '@composer-media-item');
+ $page->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+
+ $posts = Post::query()->where('workspace_id', $post->workspace_id)->whereKeyNot($post->id)->get()->keyBy('social_account_id');
+ expect($posts)->toHaveCount(2)
+ ->and($posts[$x->id]->content_type)->toBe(ContentType::XPost)
+ ->and($posts[$x->id]->meta)->not->toHaveKey('poll')
+ ->and($posts[$x->id]->media)->toHaveCount(1)
+ ->and($posts[$linkedIn->id]->media)->toHaveCount(1);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a threads ghost post stays a ghost post when another network joins, since only a poll goes back to a post', function () {
+ $post = seedXPollPost();
+ $threads = SocialAccount::factory()->threads()->create(['workspace_id' => $post->workspace_id]);
+ $linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);
+
+ $page = visit(route('app.posts.create'))->resize(1280, 900);
+ waitForState($page, '@post-composer-dialog', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ $page->click('@composer-add-account');
+ waitFor($page, "@composer-account-option-{$threads->id}");
+ $page->click("@composer-account-option-{$threads->id}")
+ ->click('@composer-header');
+ waitForGone($page, "@composer-account-option-{$threads->id}");
+ waitFor($page, "@composer-type-{$threads->id}-threads_ghost_post");
+ $page->click("@composer-type-{$threads->id}-threads_ghost_post");
+ waitForState($page, "@composer-type-{$threads->id}-threads_ghost_post", "element.getAttribute('aria-checked') === 'true'");
+
+ $page->click('@composer-add-account');
+ waitFor($page, "@composer-account-option-{$linkedIn->id}");
+ $page->click("@composer-account-option-{$linkedIn->id}")
+ ->click('@composer-header');
+ waitForGone($page, "@composer-account-option-{$linkedIn->id}");
+ $page->fill('@composer-base-content', 'Boo')
+ ->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+
+ expect(Post::query()->where('social_account_id', $threads->id)->sole()->content_type)->toBe(ContentType::ThreadsGhostPost);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('poll is disabled while a file is still uploading to the card', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $uploadUrl = route('app.media.store-chunked', absolute: false);
+ $page = openXPollComposer($post);
+ waitFor($page, "@composer-{$id}-file-input");
+
+ $page->script(<<<JS
+ (() => {
+ const { open, send } = XMLHttpRequest.prototype;
+ XMLHttpRequest.prototype.open = function (method, url, ...rest) {
+ this.__url = url;
+ return open.call(this, method, url, ...rest);
+ };
+ XMLHttpRequest.prototype.send = function (body) {
+ if (String(this.__url ?? '').includes('{$uploadUrl}')) return;
+ return send.call(this, body);
+ };
+ const input = document.querySelector('[data-testid="composer-{$id}-file-input"]');
+ const transfer = new DataTransfer();
+ transfer.items.add(new File([Uint8Array.from(atob('{$png}'), (character) => character.charCodeAt(0))], 'held.png', { type: 'image/png' }));
+ input.files = transfer.files;
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ })();
+ JS);
+ waitFor($page, "@composer-{$id}-upload-item");
+
+ $page->assertMissing("@composer-{$id}-media-item");
+ expect($page->script("document.querySelector('[data-testid=\"composer-type-{$id}-x_poll\"]').disabled"))->toBeTrue();
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a choice counter does not count the spaces around it', function () {
+ $post = seedXPollPost();
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->fill('@x-poll-choice-0', Str::repeat('a', 25).' ');
+ waitForText($page, '@x-poll-choice-0-count', '25 / 25');
+
+ expect($page->script("document.querySelector('[data-testid=\"x-poll-choice-0-count\"]').classList.contains('text-destructive-text')"))->toBeFalse();
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a choice stops at 25 characters while typing, counted as x counts them (a penguin emoji is two) and leaving out the spaces before it', function () {
+ $post = seedXPollPost();
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->fill('@x-poll-choice-0', Str::repeat('a', 30));
+ waitForText($page, '@x-poll-choice-0-count', '25 / 25');
+ $page->append('@x-poll-choice-0', 'xyz')
+ ->fill('@x-poll-choice-1', ' 🐧'.Str::repeat('b', 30));
+ waitForText($page, '@x-poll-choice-1-count', '25 / 25');
+
+ expect($page->script("document.querySelector('[data-testid=\"x-poll-choice-0\"]').value"))->toBe(Str::repeat('a', 25))
+ ->and($page->script("document.querySelector('[data-testid=\"x-poll-choice-1\"]').value"))->toBe(' 🐧'.Str::repeat('b', 23));
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a thread reply under a poll can still take media while the poll root cannot', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ waitFor($page, '@thread-start');
+ $page->click('@thread-start');
+ waitFor($page, '@thread-reply-0');
+ waitFor($page, "@composer-{$id}-media-source-menu");
+
+ $page->assertMissing("@composer-{$id}-media-source-disabled")
+ ->assertPresent("@composer-{$id}-reply-0-dropzone");
+
+ $page->click("@composer-{$id}-caption-collapsed");
+ waitFor($page, "@composer-{$id}-media-source-disabled");
+
+ $page->assertMissing("@composer-{$id}-media-source-menu")
+ ->assertMissing("@composer-{$id}-dropzone")
+ ->assertNoJavaScriptErrors();
+});
+
+test('in a thread the poll shows on the root and hides while a reply is edited', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ waitFor($page, '@thread-start');
+ $page->click('@thread-start');
+ waitForGone($page, '@x-poll');
+ $page->assertMissing('@x-poll-choice-0');
+
+ $page->click("@composer-{$id}-caption-collapsed");
+ waitFor($page, '@x-poll-choice-0');
+ $page->fill('@x-poll-choice-0', 'Tabs')
+ ->assertValue('@x-poll-choice-0', 'Tabs')
+ ->click('@thread-reply-collapsed-0');
+ waitForGone($page, '@x-poll');
+
+ $page->assertMissing('@x-poll-choice-0')->assertNoJavaScriptErrors();
+});
+
+test('a poll question on a long post account counts against 280', function () {
+ $post = seedXPollPost(ContentType::XPoll, [
+ 'content' => Str::repeat('a', 290),
+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]],
+ ], ['x_subscription_type' => 'Premium']);
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+ waitForText($page, "@composer-char-count-{$id}", '-10');
+
+ $page->assertSeeIn("@composer-char-count-{$id}", '-10')
+ ->hover('@composer-submit');
+ waitForText($page, '@composer-blocked-tooltip', 'max 280');
+
+ $page->assertSeeIn('@composer-blocked-tooltip', __('posts.form.content_exceeds_platform', ['platform' => 'X', 'over' => '10', 'limit' => '280']))
+ ->assertNoJavaScriptErrors();
+});
+
+test('a server error on the poll shows on the x card when x is not the first channel', function (array $choices, string $errorTestId, string $message) {
+ $post = seedXPollPost();
+ $x = $post->socialAccount;
+ $linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);
+
+ $page = visit(route('app.posts.create'))->resize(1280, 900);
+ waitForState($page, '@post-composer-dialog', "element.getAttribute('data-state') === 'open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+ $page->click('@composer-add-account');
+ waitFor($page, "@composer-account-option-{$linkedIn->id}");
+ $page->click("@composer-account-option-{$linkedIn->id}");
+ waitFor($page, "@composer-account-option-{$x->id}");
+ $page->click("@composer-account-option-{$x->id}");
+ waitFor($page, '@composer-base-content');
+ $page->fill('@composer-base-content', 'Tabs or spaces?')
+ ->click('@composer-next');
+ waitFor($page, "@composer-account-{$x->id}");
+ $page->click("@composer-account-{$x->id}");
+ waitFor($page, "@composer-type-{$x->id}-x_poll");
+ $page->click("@composer-type-{$x->id}-x_poll");
+ waitFor($page, '@x-poll-choice-1');
+
+ $page->fill('@x-poll-choice-0', $choices[0])
+ ->fill('@x-poll-choice-1', $choices[1])
+ ->click('@composer-save-draft');
+ waitForText($page, "@{$errorTestId}", $message);
+
+ $page->assertSeeIn("@{$errorTestId}", $message)
+ ->assertVisible('@post-composer-dialog')
+ ->assertNoJavaScriptErrors();
+ expect(Post::query()->where('workspace_id', $post->workspace_id)->count())->toBe(1);
+})->with([
+ 'repeated choices' => fn () => [['Yes', 'yes'], 'x-poll-options-error', __('posts.form.x.poll.options_distinct')],
+]);
+
+test('the ai-generated switch survives a switch from poll to post', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ waitFor($page, '@x-ai-generated');
+ $page->click('@x-ai-generated');
+ waitForState($page, '@x-ai-generated', "element.getAttribute('aria-checked') === 'true'");
+ $page->click("@composer-type-{$id}-x_post");
+ waitForGone($page, '@x-poll');
+
+ $page->assertAttribute('@x-ai-generated', 'aria-checked', 'true')
+ ->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+
+ expect($post->fresh())
+ ->content_type->toBe(ContentType::XPost)
+ ->meta->toEqual(['is_ai_generated' => true]);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('removing the poll forgets it, so picking poll again starts empty', function () {
+ $post = seedXPollPost();
+ $page = openXPollComposer($post);
+ pickXPoll($page, $post);
+
+ $page->fill('@x-poll-choice-0', 'Yes')
+ ->fill('@x-poll-choice-1', 'No')
+ ->click('@x-poll-days');
+ waitFor($page, '@x-poll-days-3');
+ $page->click('@x-poll-days-3');
+ waitForText($page, '@x-poll-days', '3');
+
+ $page->click('@x-poll-remove');
+ waitForGone($page, '@x-poll');
+ pickXPoll($page, $post);
+
+ $page->assertValue('@x-poll-choice-0', '')
+ ->assertValue('@x-poll-choice-1', '')
+ ->assertSeeIn('@x-poll-days', '1')
+ ->assertSeeIn('@x-poll-hours', '0')
+ ->assertSeeIn('@x-poll-minutes', '0')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a length of zero saves the shortest poll and seven days locks hours and minutes', function () {
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]]);
+ $page = openXPollComposer($post);
+ waitFor($page, '@x-poll-days');
+
+ $page->click('@x-poll-days');
+ waitFor($page, '@x-poll-days-0');
+ $page->click('@x-poll-days-0');
+ waitForText($page, '@x-poll-minutes', '5');
+
+ $page->assertSeeIn('@x-poll-days', '0')
+ ->assertSeeIn('@x-poll-hours', '0')
+ ->assertSeeIn('@x-poll-minutes', '5')
+ ->click('@x-poll-days');
+ waitFor($page, '@x-poll-days-7');
+ $page->click('@x-poll-days-7');
+ waitForState($page, '@x-poll-hours', 'element.disabled');
+
+ expect($page->script("['days', 'hours', 'minutes'].map((part) => document.querySelector(`[data-testid=\"x-poll-\${part}\"]`).disabled)"))->toBe([false, true, true]);
+
+ $page->click('@x-poll-days');
+ waitFor($page, '@x-poll-days-0');
+ $page->click('@x-poll-days-0');
+ waitForState($page, '@x-poll-hours', '! element.disabled');
+ $page->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+
+ expect(data_get($post->fresh()->meta, 'poll.duration_minutes'))->toBe(5);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('on a phone the poll editor fits the screen', function () {
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]]);
+ $page = visit(route('app.posts.edit', $post))->resize(390, 844);
+ waitFor($page, '@x-poll-minutes');
+
+ expect($page->script("(() => { const poll = document.querySelector('[data-testid=\"x-poll\"]'); return poll.scrollWidth <= poll.clientWidth; })()"))->toBeTrue()
+ ->and($page->script("['days', 'hours', 'minutes'].every((part) => { const box = document.querySelector(`[data-testid=\"x-poll-\${part}\"]`).getBoundingClientRect(); return box.left >= 0 && box.right <= window.innerWidth; })"))->toBeTrue();
+ $page->assertNoJavaScriptErrors();
+});
+
+test('the length selects are labelled and a choice is added with the keyboard', function () {
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]]);
+ $page = openXPollComposer($post);
+ waitFor($page, '@x-poll-add-choice');
+
+ expect($page->script("['days', 'hours', 'minutes'].map((part) => document.querySelector(`[data-testid=\"x-poll-\${part}\"]`).labels[0]?.textContent.trim())"))
+ ->toBe([__('posts.form.x.poll.days'), __('posts.form.x.poll.hours'), __('posts.form.x.poll.minutes')]);
+
+ $page->keys('@x-poll-add-choice', 'Enter');
+ waitFor($page, '@x-poll-choice-2');
+
+ $page->assertVisible('@x-poll-choice-2')->assertNoJavaScriptErrors();
+});
+
+test('the writing assistant writes a poll question for 280 characters on a long post account', function () {
+ config()->set('trypost.self_hosted', true);
+ PostWritingAssistant::fake(['Tabs or spaces?']);
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 1440]]], ['x_subscription_type' => 'Premium']);
+ $page = openXPollComposer($post);
+
+ $page->click('@composer-ai-assistant');
+ waitFor($page, '@writing-assistant-channel');
+ $page->assertSeeIn('@writing-assistant-channel', '280')
+ ->click('@writing-assistant-mode-generate')
+ ->fill('@writing-assistant-prompt', 'ask our followers about tabs or spaces')
+ ->click('@writing-assistant-generate');
+ waitForText($page, '@writing-assistant-suggestion', 'Tabs or spaces?');
+
+ $page->assertSeeIn('@writing-assistant-suggestion', 'Tabs or spaces?')->assertNoJavaScriptErrors();
+ PostWritingAssistant::assertPrompted(fn (AgentPrompt $prompt): bool => Str::contains($prompt->agent->instructions(), 'Hard limit: '.XPoll::QUESTION_MAX_LENGTH.' characters'));
+});
+
+test('a link in a poll question shows no link card in the preview', function () {
+ Http::fake(['https://93.184.216.34/*' => Http::response('<meta property="og:title" content="Article card">')]);
+ $post = seedXPollPost(ContentType::XPost, ['content' => 'Read https://93.184.216.34/article']);
+ $page = openXPollComposer($post);
+ waitForText($page, '@link-card-title', 'Article card');
+ $page->assertPresent('@link-card');
+
+ pickXPoll($page, $post);
+ waitForGone($page, '@link-card');
+
+ $page->assertMissing('@link-card')
+ ->assertVisible('@x-preview-poll')
+ ->assertNoJavaScriptErrors();
+});
+
+test('the preview shows the poll length in its largest unit and the user language', function (int $minutes, string $locale, string $expected) {
+ $post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => $minutes]]], userAttributes: ['locale' => $locale]);
+ $page = openXPollComposer($post);
+ waitForText($page, '@x-preview-poll', $expected);
+
+ $page->assertSeeIn('@x-preview-poll', $expected)->assertNoJavaScriptErrors();
+})->with([
+ 'hours' => [120, 'en', '2 hours left'],
+ 'minutes' => [30, 'en', '30 minutes left'],
+ 'days in portuguese' => [1440, 'pt-BR', 'termina em 1 dia'],
+]);
+
+test('a thread reply turns into a poll from its toolbar, turns its media off and saves the poll on the reply', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+
+ waitFor($page, '@thread-start');
+ $page->click('@thread-start');
+ waitFor($page, '@thread-reply-0');
+ $page->fill('@thread-reply-0', 'Tabs or spaces?');
+ waitFor($page, "@composer-{$id}-poll");
+ $page->click("@composer-{$id}-poll");
+ waitFor($page, '@thread-reply-0-poll-choice-0');
+
+ $page->fill('@thread-reply-0-poll-choice-0', 'Tabs')
+ ->fill('@thread-reply-0-poll-choice-1', 'Spaces');
+ waitFor($page, "@composer-{$id}-media-source-disabled");
+ waitForText($page, '@preview-thread-reply-0 [data-testid="x-preview-poll"]', 'Spaces');
+
+ $page->assertMissing("@composer-{$id}-poll")
+ ->assertMissing('@x-poll')
+ ->assertAttribute("@composer-{$id}-media-source-disabled", 'aria-label', __('posts.form.x.poll.attachments'))
+ ->assertSeeIn('[data-testid="preview-thread-reply-0"] [data-testid="x-preview-poll"]', 'Tabs');
+
+ $page->click('@composer-save-draft');
+ waitForGone($page, '@post-composer-dialog');
+
+ expect($post->fresh()->meta['thread_replies'])->toEqual([
+ ['text' => 'Tabs or spaces?', 'media' => [], 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => XPoll::DEFAULT_DURATION]],
+ ])->and($post->fresh()->content_type)->toBe(ContentType::XPost);
+ $page->assertNoJavaScriptErrors();
+});
+
+test('a thread reply poll shows in the preview before its question, and its choice errors only under the choices', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+
+ waitFor($page, '@thread-start');
+ $page->click('@thread-start');
+ waitFor($page, "@composer-{$id}-poll");
+ $page->click("@composer-{$id}-poll");
+ waitFor($page, '@thread-reply-0-poll-choice-0');
+ $page->fill('@thread-reply-0-poll-choice-0', 'Tabs')
+ ->fill('@thread-reply-0-poll-choice-1', 'Tabs');
+ waitForText($page, '@preview-thread-reply-0 [data-testid="x-preview-poll"]', 'Tabs');
+ $page->assertVisible('[data-testid="preview-thread-reply-0"] [data-testid="x-preview-poll"]')
+ ->click('@composer-save-draft');
+ waitForText($page, '@thread-reply-0-poll-options-error', __('posts.form.x.poll.options_distinct'));
+
+ $page->assertSeeIn('@thread-reply-0-poll-options-error', __('posts.form.x.poll.options_distinct'))
+ ->assertMissing('@thread-reply-error-0')
+ ->assertAttributeMissing('@thread-reply-0', 'aria-invalid')
+ ->assertVisible('@post-composer-dialog')
+ ->assertNoJavaScriptErrors();
+});
+
+test('removing a thread reply poll gives the reply its media back', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+
+ waitFor($page, '@thread-start');
+ $page->click('@thread-start');
+ waitFor($page, "@composer-{$id}-poll");
+ $page->click("@composer-{$id}-poll");
+ waitFor($page, '@thread-reply-0-poll-remove');
+ $page->click('@thread-reply-0-poll-remove');
+ waitFor($page, "@composer-{$id}-media-source-menu");
+
+ $page->assertMissing('@thread-reply-0-poll')
+ ->assertPresent("@composer-{$id}-poll")
+ ->assertMissing("@composer-{$id}-media-source-disabled")
+ ->assertNoJavaScriptErrors();
+});
+
+test('a thread reply with media cannot turn into a poll and says why', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $image = Media::factory()->ownedByPost($post)->create(['mime_type' => 'image/png']);
+ $post->update(['meta' => ['thread_replies' => [['text' => 'With a photo', 'media' => [MediaItem::fromMedia($image)->toArray()]]]]]);
+ $page = openXPollComposer($post);
+
+ waitFor($page, '@thread-reply-collapsed-0');
+ $page->click('@thread-reply-collapsed-0');
+ waitFor($page, "@composer-{$id}-poll-disabled");
+
+ $page->assertMissing("@composer-{$id}-poll")
+ ->assertAttribute("@composer-{$id}-poll-disabled", 'aria-label', __('posts.form.x.poll.attachments'))
+ ->assertNoJavaScriptErrors();
+});
+
+test('a thread reply poll question on a long post account counts against 280', function () {
+ $post = seedXPollPost(attributes: ['meta' => ['thread_replies' => [
+ ['text' => Str::repeat('a', 290), 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]],
+ ]]], accountMeta: ['x_subscription_type' => 'Premium']);
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+
+ waitFor($page, '@thread-reply-collapsed-0');
+ $page->click('@thread-reply-collapsed-0');
+ waitForText($page, "@composer-char-count-{$id}", '-10');
+
+ $page->assertSeeIn("@composer-char-count-{$id}", '-10')
+ ->assertValue('@thread-reply-0-poll-choice-1', 'No')
+ ->assertNoJavaScriptErrors();
+});
+
+test('pasting an image into a thread reply poll adds no media to it', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
+ $page = openXPollComposer($post);
+
+ waitFor($page, '@thread-start');
+ $page->click('@thread-start');
+ waitFor($page, "@composer-{$id}-poll");
+ $page->click("@composer-{$id}-poll");
+ waitFor($page, '@thread-reply-0-poll-choice-0');
+
+ $prevented = $page->script(<<<JS
+ (() => {
+ const transfer = new DataTransfer();
+ transfer.items.add(new File([Uint8Array.from(atob('{$png}'), (character) => character.charCodeAt(0))], 'pasted.png', { type: 'image/png' }));
+ return !document.querySelector('[data-testid="thread-reply-0"]').dispatchEvent(new ClipboardEvent('paste', { clipboardData: transfer, bubbles: true, cancelable: true }));
+ })()
+ JS);
+ $page->script('new Promise((resolve) => setTimeout(resolve, 500))');
+
+ expect($prevented)->toBeFalse();
+ $page->assertMissing("@composer-{$id}-reply-0-upload-item")
+ ->assertMissing("@composer-{$id}-reply-0-media-item")
+ ->assertVisible('@thread-reply-0-poll-choice-0')
+ ->assertNoJavaScriptErrors();
+});
+
+test('every toolbar button names itself in a tooltip and the ai-generated hint opens above its icon', function () {
+ $post = seedXPollPost();
+ $id = $post->social_account_id;
+ $page = openXPollComposer($post);
+
+ foreach ([
+ "composer-{$id}-media-source" => __('posts.edit.add_media'),
+ "composer-{$id}-emoji" => __('posts.edit.emoji_picker.search'),
+ "composer-{$id}-signature" => __('posts.edit.signatures'),
+ ] as $button => $label) {
+ $trigger = $button === "composer-{$id}-media-source" ? "@{$button}-menu" : "@{$button}";
+ waitFor($page, $trigger);
+ $page->hover($trigger);
+ waitFor($page, "@{$button}-tooltip");
+ $page->assertSeeIn("@{$button}-tooltip", $label);
+ $page->hover('@composer-header');
+ waitForGone($page, "@{$button}-tooltip");
+ }
+
+ waitFor($page, '@thread-start');
+ $page->click('@thread-start');
+ waitFor($page, "@composer-{$id}-poll");
+ $page->hover("@composer-{$id}-poll");
+ waitFor($page, "@composer-{$id}-poll-tooltip");
+ $page->assertSeeIn("@composer-{$id}-poll-tooltip", __('posts.form.x.poll.add'))
+ ->hover('@composer-header');
+ waitForGone($page, "@composer-{$id}-poll-tooltip");
+
+ $page->hover('@thread-add-reply');
+ waitFor($page, '@thread-add-reply-tooltip');
+ $page->assertSeeIn('@thread-add-reply-tooltip', __('posts.form.thread.add'))
+ ->hover('@composer-header');
+ waitForGone($page, '@thread-add-reply-tooltip');
+
+ $page->hover('@x-ai-generated-info');
+ waitForState($page, '@x-ai-generated-tooltip', "element.getAttribute('data-state') === 'delayed-open' && element.getAnimations().every((animation) => animation.playState !== 'running')");
+
+ expect($page->script("document.querySelector('[data-testid=\"x-ai-generated-tooltip\"]').getBoundingClientRect().bottom <= document.querySelector('[data-testid=\"x-ai-generated-info\"]').getBoundingClientRect().top"))->toBeTrue();
+ $page->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/PostApprovalsTest.php b/tests/Browser/PostApprovalsTest.php
index eac90953c..d873fd677 100644
--- a/tests/Browser/PostApprovalsTest.php
+++ b/tests/Browser/PostApprovalsTest.php
@@ -99,7 +99,8 @@ test('an approver adds a queue request to the queue and rejects another', functi
waitForApprovalsTestId($page, "post-approve-{$queued->id}");
$page->assertSeeIn('@publish-tab-count-approvals', '2')
- ->assertVisible("@post-approval-badge-{$queued->id}")
+ ->assertMissing("@post-approval-badge-{$queued->id}")
+ ->assertSeeIn("@post-no-time-{$queued->id}", 'Next slot')
->assertSeeIn("@post-approve-{$queued->id}", 'Add to queue')
->assertSeeIn("@post-approve-{$timed->id}", 'Schedule')
->click("@post-approve-{$queued->id}");
@@ -213,3 +214,15 @@ test('a new time for a late request is typed in the channel zone', function () {
->toBe(CarbonImmutable::parse("{$day} 10:00", 'America/Sao_Paulo')->utc()->toIso8601String());
$page->assertNoJavaScriptErrors();
});
+
+test('a request for the top of the queue says so where the time goes', function () {
+ [$owner, $workspace, $channel, $requester] = approvalsBrowserSetup();
+ $top = approvalsBrowserRequest($workspace, $requester, $channel, ['queue' => 'top']);
+ $this->actingAs($owner);
+
+ $page = visit(route('app.posts.index', ['tab' => 'approvals']));
+ waitFor($page, "@post-no-time-{$top->id}");
+
+ $page->assertSeeIn("@post-no-time-{$top->id}", __('posts.publish.pending_slot.top'))
+ ->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/PostDetailsDialogTest.php b/tests/Browser/PostDetailsDialogTest.php
index 27e77acb9..6ab627bec 100644
--- a/tests/Browser/PostDetailsDialogTest.php
+++ b/tests/Browser/PostDetailsDialogTest.php
@@ -347,7 +347,7 @@ test('the details of a sent thread show every post of the thread with its own me
'original_filename' => 'reply.jpg',
'size' => 1024,
]]],
- 'Third post of the thread',
+ ['text' => 'Third post of the thread', 'media' => []],
]],
]);
$this->actingAs($user);
diff --git a/tests/Browser/PostPollResultsTest.php b/tests/Browser/PostPollResultsTest.php
new file mode 100644
index 000000000..94e0a6d66
--- /dev/null
+++ b/tests/Browser/PostPollResultsTest.php
@@ -0,0 +1,350 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Post\Status;
+use App\Enums\PostPlatform\ContentType;
+use App\Enums\SocialAccount\Platform;
+use App\Models\AnalyticsPublication;
+use App\Models\AnalyticsPublicationDailySnapshot;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use Database\Factories\AnalyticsPublicationFactory;
+
+/**
+ * @param array<string, mixed>|null $poll
+ * @return array{0: User, 1: SocialAccount, 2: Post}
+ */
+function pollResultsSetup(?array $poll, bool $withMetrics = true, string $theme = 'light'): array
+{
+ $user = User::factory()->create(['timezone' => 'UTC', 'theme' => $theme]);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ subscribeAccount($user->account);
+ connectAiTo($user);
+
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([
+ 'user_id' => $user->id,
+ 'scheduled_at' => now()->subHour(),
+ 'published_at' => now()->subHour(),
+ ]);
+ $publication = AnalyticsPublication::factory()->when(filled($poll), fn (AnalyticsPublicationFactory $factory): AnalyticsPublicationFactory => $factory->withPoll($poll))->create([
+ 'workspace_id' => $workspace->id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'post_id' => $post->id,
+ 'platform' => Platform::X,
+ 'network' => Platform::X->network(),
+ 'remote_id' => $post->platform_post_id,
+ ]);
+ AnalyticsPublicationDailySnapshot::factory()->create([
+ 'publication_id' => $publication->id,
+ 'metrics' => $withMetrics ? [
+ 'impressions' => ['value' => 900, 'unit' => 'count', 'availability' => 'available'],
+ 'reactions' => ['value' => 40, 'unit' => 'count', 'availability' => 'available'],
+ ] : [],
+ ]);
+
+ return [$user, $account, $post];
+}
+
+/**
+ * @return array<string, mixed>
+ */
+function refundPoll(string $status = 'open'): array
+{
+ return [
+ 'options' => [['label' => '✅ Refund', 'votes' => 1], ['label' => '❌ No refund', 'votes' => 2]],
+ 'voting_status' => $status,
+ 'end_datetime' => now()->addHours(5)->toIso8601String(),
+ 'duration_minutes' => 1440,
+ ];
+}
+
+test('the sent card shows each choice with its votes and percentage', function () {
+ [$user, $account, $post] = pollResultsSetup(refundPoll());
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}");
+
+ $page->assertSeeIn("@post-poll-{$post->id}-option-0", '✅ Refund')
+ ->assertSeeIn("@post-poll-{$post->id}-option-0", '33.3%')
+ ->assertSeeIn("@post-poll-{$post->id}-option-0", '1 vote')
+ ->assertSeeIn("@post-poll-{$post->id}-option-1", '2 votes')
+ ->assertSeeIn("@post-poll-{$post->id}-option-1", '66.7%')
+ ->assertSeeIn("@post-poll-{$post->id}-summary", '3 votes')
+ ->assertAttribute("@post-poll-{$post->id}-option-1", 'data-leading', 'true')
+ ->assertAttribute("@post-poll-{$post->id}-option-0", 'data-leading', 'false')
+ ->assertNoJavaScriptErrors();
+});
+
+test('the summary says where voting stands', function (Closure $overrides, string $shown, array $hidden) {
+ [$user, $account, $post] = pollResultsSetup([...refundPoll(), ...$overrides()]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}");
+
+ $page->assertSeeIn("@post-poll-{$post->id}-summary", $shown);
+
+ foreach ($hidden as $text) {
+ $page->assertDontSeeIn("@post-poll-{$post->id}-summary", $text);
+ }
+
+ $page->assertNoJavaScriptErrors();
+})->with([
+ 'closed: final results' => [fn (): array => ['voting_status' => 'closed'], 'Final results', ['Voting ended']],
+ 'open, end ahead: when it ends' => [fn (): array => [], 'Ends', ['Voting ended', 'Final results']],
+ 'open, end passed: voting ended' => [fn (): array => ['end_datetime' => now()->subHours(2)->toIso8601String()], 'Voting ended', ['Final results', 'Ends']],
+ 'unknown state, end passed: never final' => [fn (): array => ['voting_status' => null, 'end_datetime' => now()->subHours(2)->toIso8601String()], 'Voting ended', ['Final results']],
+]);
+
+test('where voting stands is read from the instant, whatever zone the browser is in', function (string $browserZone, Closure $endsAt, string $shown, string $hidden) {
+ [$user, $account, $post] = pollResultsSetup([...refundPoll(), 'end_datetime' => $endsAt()]);
+ $user->update(['timezone' => 'UTC']);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']))->withTimezone($browserZone);
+ waitFor($page, "@post-poll-{$post->id}");
+
+ $page->assertSeeIn("@post-poll-{$post->id}-summary", $shown)
+ ->assertDontSeeIn("@post-poll-{$post->id}-summary", $hidden)
+ ->assertNoJavaScriptErrors();
+})->with([
+ 'still open, browser behind the user' => ['America/Sao_Paulo', fn (): string => now()->addMinutes(30)->toIso8601String(), 'Ends', 'Voting ended'],
+ 'just ended, browser ahead of the user' => ['Asia/Tokyo', fn (): string => now()->subMinutes(30)->toIso8601String(), 'Voting ended', 'Ends'],
+]);
+
+test('a poll whose publication x has not read yet shows its choices with no votes and when it ends', function () {
+ $user = User::factory()->create(['timezone' => 'UTC']);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ subscribeAccount($user->account);
+ connectAiTo($user);
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([
+ 'user_id' => $user->id,
+ 'scheduled_at' => now()->subMinutes(5),
+ 'published_at' => now()->subMinutes(5),
+ 'meta' => [
+ 'poll' => ['options' => ['Mac', 'Linux'], 'duration_minutes' => 1440],
+ 'thread_replies' => [['text' => 'And at work?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]],
+ ],
+ ]);
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'post_id' => $post->id,
+ 'platform' => Platform::X,
+ 'network' => Platform::X->network(),
+ 'remote_id' => $post->platform_post_id,
+ ]);
+ AnalyticsPublicationDailySnapshot::factory()->create([
+ 'publication_id' => $publication->id,
+ 'date' => now()->toDateString(),
+ 'collected_at' => now(),
+ ]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}");
+
+ $page->assertSeeIn("@post-poll-{$post->id}-option-0", 'Mac')
+ ->assertSeeIn("@post-poll-{$post->id}-option-0-votes", '0 votes')
+ ->assertSeeIn("@post-poll-{$post->id}-option-1", 'Linux')
+ ->assertSeeIn("@post-poll-{$post->id}-summary", 'Ends')
+ ->assertSeeIn("@post-poll-{$post->id}-reply-0-option-0", 'Yes')
+ ->assertSeeIn("@post-poll-{$post->id}-reply-0-summary", 'Ends')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a poll still in the queue shows its choices with no votes and no end yet', function () {
+ $user = User::factory()->create(['timezone' => 'UTC']);
+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ subscribeAccount($user->account);
+ connectAiTo($user);
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->create([
+ 'user_id' => $user->id,
+ 'status' => Status::Scheduled,
+ 'scheduled_at' => now()->addDay(),
+ 'meta' => ['poll' => ['options' => ['Mac', 'Linux'], 'duration_minutes' => 1440]],
+ ]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', $account));
+ waitFor($page, "@post-poll-{$post->id}");
+
+ $page->assertSeeIn("@post-poll-{$post->id}-option-0", 'Mac')
+ ->assertSeeIn("@post-poll-{$post->id}-option-0-votes", '0 votes')
+ ->assertSeeIn("@post-poll-{$post->id}-option-1", 'Linux')
+ ->assertDontSeeIn("@post-poll-{$post->id}-summary", 'Ends')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a post without a poll shows no results', function () {
+ [$user, $account, $post] = pollResultsSetup(null);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-metrics-{$post->id}");
+
+ $page->assertMissing("@post-poll-{$post->id}")->assertNoJavaScriptErrors();
+});
+
+test('the post details show the poll too', function () {
+ [$user, $account, $post] = pollResultsSetup(refundPoll());
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-card-menu-{$post->id}");
+ $page->click("@post-card-menu-{$post->id}");
+ waitFor($page, "@post-details-open-{$post->id}");
+ $page->click("@post-details-open-{$post->id}");
+ waitFor($page, '@post-details-poll');
+
+ $page->assertSeeIn('@post-details-poll', '66.7%')->assertNoJavaScriptErrors();
+});
+
+test('a poll with no votes shows 0% and no leader', function () {
+ [$user, $account, $post] = pollResultsSetup([
+ ...refundPoll(),
+ 'options' => [['label' => 'Yes', 'votes' => 0], ['label' => 'No', 'votes' => 0]],
+ ]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}");
+
+ $page->assertSeeIn("@post-poll-{$post->id}-option-0", '0%')
+ ->assertSeeIn("@post-poll-{$post->id}-option-1", '0%')
+ ->assertSeeIn("@post-poll-{$post->id}-summary", '0 votes')
+ ->assertNoJavaScriptErrors();
+
+ expect($page->script("document.querySelectorAll('[data-testid^=\"post-poll-{$post->id}-option-\"][data-leading=\"true\"]').length"))->toBe(0);
+});
+
+test('tied choices are both marked as leading', function () {
+ [$user, $account, $post] = pollResultsSetup([
+ ...refundPoll(),
+ 'options' => [['label' => 'Yes', 'votes' => 2], ['label' => 'No', 'votes' => 2], ['label' => 'Maybe', 'votes' => 1]],
+ ]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}");
+
+ $page->assertAttribute("@post-poll-{$post->id}-option-0", 'data-leading', 'true')
+ ->assertAttribute("@post-poll-{$post->id}-option-1", 'data-leading', 'true')
+ ->assertAttribute("@post-poll-{$post->id}-option-2", 'data-leading', 'false')
+ ->assertNoJavaScriptErrors();
+});
+
+test('the post details show the poll of a post without other metrics', function () {
+ [$user, $account, $post] = pollResultsSetup(refundPoll(), withMetrics: false);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}");
+ $page->click("@post-card-menu-{$post->id}");
+ waitFor($page, "@post-details-open-{$post->id}");
+ $page->click("@post-details-open-{$post->id}");
+ waitFor($page, '@post-details-poll');
+
+ $page->assertSeeIn('@post-details-poll', '66.7%')
+ ->assertMissing("@post-details-metrics-{$post->id}")
+ ->assertNoJavaScriptErrors();
+});
+
+test('a poll without a known state or end shows only the votes', function () {
+ [$user, $account, $post] = pollResultsSetup([...refundPoll(), 'voting_status' => null, 'end_datetime' => null]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}");
+
+ expect($page->script("document.querySelector('[data-testid=\"post-poll-{$post->id}-summary\"]').textContent.replace(/\\s+/g, ' ').trim()"))->toBe('3 votes');
+ $page->assertNoJavaScriptErrors();
+});
+
+test('the leading choice stays readable in both themes', function (string $theme) {
+ [$user, $account, $post] = pollResultsSetup([
+ ...refundPoll(),
+ 'options' => [['label' => 'Yes', 'votes' => 9], ['label' => 'No', 'votes' => 1]],
+ ], theme: $theme);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}-option-0");
+
+ $contrast = $page->script(<<<JS
+ (() => {
+ const parse = (color) => {
+ const [r, g, b, a = 1] = color.match(/[\\d.]+/g).map(Number);
+
+ return { r, g, b, a };
+ };
+ const over = (top, bottom) => ({
+ r: top.r * top.a + bottom.r * (1 - top.a),
+ g: top.g * top.a + bottom.g * (1 - top.a),
+ b: top.b * top.a + bottom.b * (1 - top.a),
+ a: 1,
+ });
+ const luminance = ({ r, g, b }) => {
+ const [lr, lg, lb] = [r, g, b].map((channel) => {
+ const value = channel / 255;
+
+ return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
+ });
+
+ return 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;
+ };
+ const row = document.querySelector('[data-testid="post-poll-{$post->id}-option-0"]');
+ const [bar, label] = row.children;
+ const background = over(parse(getComputedStyle(bar).backgroundColor), parse(getComputedStyle(row).backgroundColor));
+ const [light, dark] = [luminance(parse(getComputedStyle(label).color)), luminance(background)].sort((a, b) => b - a);
+
+ return (light + 0.05) / (dark + 0.05);
+ })()
+ JS);
+
+ expect($contrast)->toBeGreaterThanOrEqual(4.5);
+ expect($page->script("document.documentElement.classList.contains('dark')"))->toBe($theme === 'dark');
+ $page->assertNoJavaScriptErrors();
+})->with(['light', 'dark']);
+
+test('the polls of thread replies show under the post on the sent card and in the details, each naming its post', function () {
+ [$user, $account, $post] = pollResultsSetup(refundPoll());
+ $publication = AnalyticsPublication::query()->where('post_id', $post->id)->sole();
+ $publication->forceFill(['provider_metadata' => [...$publication->provider_metadata, 'thread_polls' => [
+ ['reply' => 1, ...refundPoll(), 'options' => [['label' => 'Tabs', 'votes' => 3], ['label' => 'Spaces', 'votes' => 1]]],
+ ]]])->save();
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));
+ waitFor($page, "@post-poll-{$post->id}-reply-1");
+
+ $page->assertSeeIn("@post-poll-{$post->id}-reply-1-caption", __('posts.poll_results.thread_post', ['number' => '3']))
+ ->assertSeeIn("@post-poll-{$post->id}-reply-1-option-0", 'Tabs')
+ ->assertSeeIn("@post-poll-{$post->id}-reply-1-option-0", '75%')
+ ->assertSeeIn("@post-poll-{$post->id}-option-1", '66.7%')
+ ->assertMissing("@post-poll-{$post->id}-caption");
+
+ $page->click("@post-card-menu-{$post->id}");
+ waitFor($page, "@post-details-open-{$post->id}");
+ $page->click("@post-details-open-{$post->id}");
+ waitFor($page, '@post-details-poll-reply-1');
+
+ $page->assertSeeIn('@post-details-poll-reply-1-caption', __('posts.poll_results.thread_post', ['number' => '3']))
+ ->assertSeeIn('@post-details-poll-reply-1', '25%')
+ ->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/PublishPageTest.php b/tests/Browser/PublishPageTest.php
index 1094bd20a..e0c815458 100644
--- a/tests/Browser/PublishPageTest.php
+++ b/tests/Browser/PublishPageTest.php
@@ -17,6 +17,7 @@ use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
use App\Support\PostingSchedule;
+use Illuminate\Support\Str;
/**
* @return array{0: User, 1: Workspace, 2: SocialAccount}
@@ -635,10 +636,10 @@ test('on a phone the view switch and the new post button fit inside the card, on
'a channel' => [false],
])->with(['approvals', 'sent']);
-test('the reel and story badges on a post card show a 16px icon', function (ContentType $contentType) {
+test('the reel, story, ghost post and poll badges on a post card show a 16px icon', function (Platform $platform, ContentType $contentType) {
[$user, $workspace] = publishPageSetup();
- $instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->forAccount($instagram, $contentType)->create(['user_id' => $user->id, 'content' => 'Badge']);
+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform]);
+ $post = Post::factory()->forAccount($account, $contentType)->create(['user_id' => $user->id, 'content' => 'Badge']);
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
@@ -646,7 +647,30 @@ test('the reel and story badges on a post card show a 16px icon', function (Cont
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]);
+})->with([
+ 'instagram reel' => [Platform::Instagram, ContentType::InstagramReel],
+ 'instagram story' => [Platform::Instagram, ContentType::InstagramStory],
+ 'threads ghost post' => [Platform::Threads, ContentType::ThreadsGhostPost],
+ 'x poll' => [Platform::X, ContentType::XPoll],
+]);
+
+test('a post card names an x poll and leaves a regular x post unmarked', function (ContentType $contentType, bool $badged) {
+ [$user, $workspace] = publishPageSetup();
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($x, $contentType)->create(['user_id' => $user->id, 'content' => 'Tabs or spaces?']);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['tab' => 'drafts']));
+ waitFor($page, "@post-card-{$post->id}");
+
+ $badged
+ ? $page->assertSeeIn("@post-content-type-{$post->id}", __('posts.content_types.x_poll.label'))
+ : $page->assertMissing("@post-content-type-{$post->id}");
+ $page->assertNoJavaScriptErrors();
+})->with([
+ 'poll' => [ContentType::XPoll, true],
+ 'post' => [ContentType::XPost, false],
+]);
test('on a phone the channel filter opens as a sheet on the publish page and the calendar', function (string $route) {
[$user, $workspace] = publishPageSetup();
@@ -661,3 +685,89 @@ test('on a phone the channel filter opens as a sheet on the publish page and the
$page->assertVisible('@posts-channel-sheet')
->assertNoJavaScriptErrors();
})->with(['app.posts.index', 'app.calendar']);
+
+test('a thread in the queue shows each post with its own text and media, as the composer previews it', function () {
+ [$user, $workspace] = publishPageSetup();
+ connectAiTo($user);
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($x)->create([
+ 'user_id' => $user->id,
+ 'status' => PostStatus::Scheduled,
+ 'scheduled_at' => now()->addDay(),
+ 'content' => 'First post of the thread',
+ 'media' => [threadCardImage('root')],
+ 'meta' => ['thread_replies' => [
+ ['text' => 'Second post of the thread', 'media' => []],
+ ['text' => 'Third post, with a photo', 'media' => [threadCardImage('reply')]],
+ ]],
+ ]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', $x));
+ waitFor($page, "@post-thread-{$post->id}");
+
+ $page->assertSeeIn("@post-thread-{$post->id}-0", 'First post of the thread')
+ ->assertPresent("[data-testid=\"post-thread-{$post->id}-0\"] img[src=\"https://cdn.example.test/root.jpg\"]")
+ ->assertSeeIn("@post-thread-{$post->id}-1", 'Second post of the thread')
+ ->assertMissing("[data-testid=\"post-thread-{$post->id}-1\"] img[src^=\"https://cdn.example.test\"]")
+ ->assertSeeIn("@post-thread-{$post->id}-2", 'Third post, with a photo')
+ ->assertPresent("[data-testid=\"post-thread-{$post->id}-2\"] img[src=\"https://cdn.example.test/reply.jpg\"]")
+ ->assertMissing("@post-thumbnail-{$post->id}-0")
+ ->assertNoJavaScriptErrors();
+});
+
+test('a thread of polls in the queue shows each poll under its own post', function () {
+ [$user, $workspace] = publishPageSetup();
+ connectAiTo($user);
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($x)->create([
+ 'user_id' => $user->id,
+ 'status' => PostStatus::Scheduled,
+ 'scheduled_at' => now()->addDay(),
+ 'content_type' => ContentType::XPoll,
+ 'content' => 'Which desktop?',
+ 'meta' => [
+ 'poll' => ['options' => ['Linux', 'macOS'], 'duration_minutes' => 1440],
+ 'thread_replies' => [
+ ['text' => 'And on the server?', 'media' => [], 'poll' => ['options' => ['Linux', 'Windows Server'], 'duration_minutes' => 1440]],
+ ['text' => 'Thanks for voting', 'media' => [threadCardImage('reply')]],
+ ],
+ ],
+ ]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.channels.publish', $x));
+ waitFor($page, "@post-thread-{$post->id}");
+
+ $page->assertSeeIn("[data-testid=\"post-thread-{$post->id}-0\"] [data-testid=\"post-poll-{$post->id}\"]", 'macOS')
+ ->assertSeeIn("[data-testid=\"post-thread-{$post->id}-1\"] [data-testid=\"post-poll-{$post->id}-reply-0\"]", 'Windows Server')
+ ->assertMissing("[data-testid=\"post-thread-{$post->id}-2\"] [data-testid^=\"post-poll-\"]")
+ ->assertPresent("[data-testid=\"post-thread-{$post->id}-2\"] img[src=\"https://cdn.example.test/reply.jpg\"]")
+ ->assertMissing("@post-poll-{$post->id}-reply-0-caption");
+
+ $page->click("@post-card-menu-{$post->id}");
+ waitFor($page, "@post-details-open-{$post->id}");
+ $page->click("@post-details-open-{$post->id}");
+ waitFor($page, "@thread-view-{$post->id}");
+
+ $page->assertSeeIn("[data-testid=\"thread-view-post-{$post->id}-0\"] [data-testid=\"post-details-poll\"]", 'macOS')
+ ->assertSeeIn("[data-testid=\"thread-view-post-{$post->id}-1\"] [data-testid=\"post-details-poll-reply-0\"]", 'Windows Server')
+ ->assertMissing('@post-details-poll-reply-0-caption')
+ ->assertNoJavaScriptErrors();
+});
+
+/**
+ * @return array<string, int|string>
+ */
+function threadCardImage(string $name): array
+{
+ return [
+ 'id' => (string) Str::uuid(),
+ 'path' => "medias/{$name}.jpg",
+ 'url' => "https://cdn.example.test/{$name}.jpg",
+ 'type' => 'image',
+ 'mime_type' => 'image/jpeg',
+ 'original_filename' => "{$name}.jpg",
+ 'size' => 1024,
+ ];
+}
diff --git a/tests/Browser/RepurposeTest.php b/tests/Browser/RepurposeTest.php
index c43325d7d..f6b8ccbc8 100644
--- a/tests/Browser/RepurposeTest.php
+++ b/tests/Browser/RepurposeTest.php
@@ -515,6 +515,34 @@ test('the destination post types sit centered in their settings panel', function
$page->assertNoJavaScriptErrors();
});
+test('an x destination offers no poll, while a threads destination still offers a ghost post', function () {
+ [$user, $workspace, $source] = repurposeOwnerWithAccounts();
+ $x = SocialAccount::factory()->for($workspace)->x()->create();
+ $threads = SocialAccount::factory()->for($workspace)->create(['platform' => Platform::Threads]);
+ $repurpose = Repurpose::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'user_id' => $user->id,
+ 'source_social_account_id' => $source->id,
+ 'destinations' => [
+ ['social_account_id' => $x->id, 'content_type' => ContentType::XPost->value, 'meta' => []],
+ ['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => []],
+ ],
+ ]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.repurposes.show', $repurpose))->resize(1440, 1000);
+ waitFor($page, "@channel-row-{$x->id}");
+ waitFor($page, "@channel-row-{$threads->id}");
+ waitForState($page, "@channel-{$x->id}", "element.getAttribute('aria-checked') === 'true'");
+
+ $page->assertAttribute("@channel-{$threads->id}", 'aria-checked', 'true')
+ ->assertMissing("@channel-type-{$x->id}-x_poll")
+ ->assertMissing("@channel-type-{$x->id}")
+ ->assertMissing("@channel-settings-{$x->id}")
+ ->assertPresent("@channel-type-{$threads->id}-threads_ghost_post")
+ ->assertNoJavaScriptErrors();
+});
+
test('on a phone the header puts the summary and the actions on their own rows', function () {
[$user, $workspace, $source, $destination] = repurposeOwnerWithAccounts();
diff --git a/tests/Feature/Actions/Post/DuplicatePostTest.php b/tests/Feature/Actions/Post/DuplicatePostTest.php
index cd9187488..d888b4af6 100644
--- a/tests/Feature/Actions/Post/DuplicatePostTest.php
+++ b/tests/Feature/Actions/Post/DuplicatePostTest.php
@@ -97,3 +97,20 @@ test('execute refuses a duplicate when the channel was removed', function () {
expect(fn () => DuplicatePost::execute($original->fresh(), $user))
->toThrow(ValidationException::class);
});
+
+test('execute keeps an x poll with its choices and length', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
+ $poll = ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 4320];
+ $original = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([
+ 'user_id' => $user->id,
+ 'content' => 'Tabs or spaces?',
+ 'meta' => ['poll' => $poll],
+ ]);
+
+ $copy = DuplicatePost::execute($original, $user)->fresh();
+
+ expect($copy->content_type)->toBe(ContentType::XPoll)
+ ->and($copy->meta['poll'])->toEqual($poll);
+});
diff --git a/tests/Feature/Ai/PostAiAssistantTest.php b/tests/Feature/Ai/PostAiAssistantTest.php
index 1b1184e76..713b8995a 100644
--- a/tests/Feature/Ai/PostAiAssistantTest.php
+++ b/tests/Feature/Ai/PostAiAssistantTest.php
@@ -6,6 +6,7 @@ use App\Ai\Agents\PostContentShortener;
use App\Ai\Agents\PostWritingAssistant;
use App\Enums\Ai\PostAssistantMode;
use App\Enums\PostHog\AiEvent;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\User\Locale;
use App\Jobs\PostHog\CaptureAccountEvent;
@@ -14,11 +15,13 @@ use App\Models\User;
use App\Models\Workspace;
use App\Services\Social\ContentSanitizer;
use App\Support\AiPromptRules;
+use App\Support\Social\XPoll;
use Illuminate\Auth\Access\Response as AuthResponse;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Route;
+use Illuminate\Support\Str;
use Laravel\Ai\Prompts\AgentPrompt;
use Symfony\Component\HttpFoundation\Response;
@@ -74,6 +77,7 @@ test('assistant validates the prompt, content and platform', function (array $pa
'generate without prompt' => [['mode' => 'generate'], 'prompt'],
'rephrase without content' => [['mode' => 'rephrase'], 'current_content'],
'unknown platform' => [['mode' => 'generate', 'prompt' => 'announce our summer launch today', 'platform' => 'myspace'], 'platform'],
+ 'unknown content type' => [['mode' => 'generate', 'prompt' => 'announce our summer launch today', 'content_type' => 'x_story'], 'content_type'],
'prompt under four words' => [['mode' => 'generate', 'prompt' => 'make it pop'], 'prompt'],
'prompt over the length limit' => [['mode' => 'generate', 'prompt' => str_repeat('word ', 2000).'x'], 'prompt'],
]);
@@ -149,7 +153,7 @@ test('a suggestion for X is shortened to fit what X counts', function () {
->json('content');
expect($content)->toBe('Great news, short and sweet.')
- ->and(Platform::X->contentOverflow(app(ContentSanitizer::class)->displayText($content, Platform::X)))->toBe(0);
+ ->and(mb_strlen(app(ContentSanitizer::class)->displayText($content, Platform::X)))->toBeLessThanOrEqual(Platform::X->maxContentLength());
PostContentShortener::assertPrompted(fn (AgentPrompt $prompt): bool => str_contains($prompt->prompt, 'Great news for everyone.'));
});
@@ -177,6 +181,57 @@ test('the assistant writes for the account limit of the card it serves', functio
'free account' => [[], 280, true],
]);
+test('the assistant keeps the long post limit for a regular post on an account with long posts', function () {
+ config()->set('trypost.self_hosted', true);
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id, 'meta' => ['x_subscription_type' => 'Premium']]);
+ PostWritingAssistant::fake(['Big news.']);
+
+ $this->actingAs($this->user)
+ ->postJson(route('app.posts.ai.assist'), [
+ 'mode' => 'generate',
+ 'prompt' => 'announce our summer launch today',
+ 'platform' => Platform::X->value,
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::XPost->value,
+ ])
+ ->assertOk();
+
+ PostWritingAssistant::assertPrompted(fn (AgentPrompt $prompt): bool => Str::contains($prompt->agent->instructions(), 'Hard limit: '.SocialAccount::X_LONG_POST_LENGTH.' characters'));
+});
+
+test('the assistant writes a poll question within 280 characters even on an account with long posts', function () {
+ config()->set('trypost.self_hosted', true);
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id, 'meta' => ['x_subscription_type' => 'Premium']]);
+ PostWritingAssistant::fake(['Tabs or spaces?']);
+
+ $this->actingAs($this->user)
+ ->postJson(route('app.posts.ai.assist'), [
+ 'mode' => 'generate',
+ 'prompt' => 'ask our followers about tabs or spaces',
+ 'platform' => Platform::X->value,
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::XPoll->value,
+ ])
+ ->assertOk();
+
+ PostWritingAssistant::assertPrompted(fn (AgentPrompt $prompt): bool => Str::contains($prompt->agent->instructions(), 'Hard limit: '.XPoll::QUESTION_MAX_LENGTH.' characters'));
+});
+
+test('the assistant ignores a post type of another network when picking the limit', function () {
+ PostWritingAssistant::fake(['Big news.']);
+
+ $this->actingAs($this->user)
+ ->postJson(route('app.posts.ai.assist'), [
+ 'mode' => 'generate',
+ 'prompt' => 'announce our summer launch today',
+ 'platform' => Platform::LinkedIn->value,
+ 'content_type' => ContentType::XPoll->value,
+ ])
+ ->assertOk();
+
+ PostWritingAssistant::assertPrompted(fn (AgentPrompt $prompt): bool => Str::contains($prompt->agent->instructions(), 'Hard limit: '.Platform::LinkedIn->maxContentLength().' characters'));
+});
+
test('the assistant rewrites a post as long as the longest post', function () {
PostWritingAssistant::fake(['Shorter']);
diff --git a/tests/Feature/Analytics/AnalyticsObservationWriterTest.php b/tests/Feature/Analytics/AnalyticsObservationWriterTest.php
index ea9d45502..fc9257c39 100644
--- a/tests/Feature/Analytics/AnalyticsObservationWriterTest.php
+++ b/tests/Feature/Analytics/AnalyticsObservationWriterTest.php
@@ -177,6 +177,33 @@ test('a partial same-day read never lowers a lifetime count from a fuller one',
->and(data_get($snapshot->metrics, 'engagements.value'))->toBe(7);
});
+test('a provider metadata write keeps what changed on the publication since it was loaded', function () {
+ $publication = AnalyticsPublication::factory()->create([
+ 'platform' => Platform::X,
+ 'provider_metadata' => ['poll' => ['options' => [['label' => 'Yes', 'votes' => 1]]]],
+ ]);
+ $updatedAt = $publication->updated_at;
+ $media = [['type' => 'photo', 'url' => 'https://pbs.twimg.com/media/a.jpg']];
+ AnalyticsPublication::withoutTimestamps(fn (): bool => AnalyticsPublication::query()->findOrFail($publication->id)->forceFill([
+ 'provider_metadata' => ['poll' => ['options' => [['label' => 'Yes', 'votes' => 1]]], 'media' => $media],
+ ])->save());
+ $this->travel(1)->hours();
+ $poll = ['options' => [['label' => 'Yes', 'votes' => 5]], 'voting_status' => 'open', 'end_datetime' => null, 'duration_minutes' => 60];
+ $date = now('UTC')->toDateString();
+
+ app(WritePublicationDailySnapshot::class)->handle($publication, new PublicationMetricObservation(
+ date: CarbonImmutable::parse($date, 'UTC'),
+ metrics: [metric(MetricKey::Impressions, 10)],
+ providerMetadata: ['poll' => $poll],
+ ));
+ app(WritePublicationDailySnapshot::class)->handle($publication, publicationObservation($date, [metric(MetricKey::Impressions, 12)]));
+
+ $fresh = $publication->fresh();
+
+ expect($fresh->provider_metadata)->toEqual(['poll' => $poll, 'media' => $media])
+ ->and($fresh->updated_at->equalTo($updatedAt))->toBeTrue();
+});
+
function accountObservation(string $date, ?int $followers): AccountDailyObservation
{
return new AccountDailyObservation(
diff --git a/tests/Feature/Analytics/ChannelInsightsFiltersTest.php b/tests/Feature/Analytics/ChannelInsightsFiltersTest.php
index 15a9d85c1..2cf467c61 100644
--- a/tests/Feature/Analytics/ChannelInsightsFiltersTest.php
+++ b/tests/Feature/Analytics/ChannelInsightsFiltersTest.php
@@ -229,3 +229,42 @@ test('the channel export is not available for another workspace channel', functi
->get(route('app.channels.insights.download', ['account' => $other, 'format' => 'csv']))
->assertNotFound();
});
+
+test('the poll type counts polls made on x that were never imported', function (string $type, array $expected) {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $publish = function (string $key, int $daysAgo, ?ContentType $contentType = null, PublicationContentType $publicationType = PublicationContentType::Text) use ($x): array {
+ $post = filled($contentType)
+ ? Post::factory()->forAccount($x, $contentType)->published()->create(['user_id' => $this->user->id])
+ : null;
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'social_account_id' => $x->id,
+ 'social_account_key' => $x->id,
+ 'network' => $x->platform->network(),
+ 'platform_user_id' => $x->platform_user_id,
+ 'platform' => Platform::X,
+ 'post_id' => $post?->id,
+ 'content_type' => $publicationType,
+ 'provider_published_at' => now('UTC')->subDays($daysAgo),
+ ]);
+
+ return [$key => $publication->id];
+ };
+ $ids = [
+ ...$publish('post', 2, ContentType::XPost),
+ ...$publish('poll', 3, ContentType::XPoll),
+ ...$publish('external_post', 4),
+ ...$publish('external_poll', 5, publicationType: PublicationContentType::Poll),
+ ];
+
+ $this->actingAs($this->user)
+ ->get(filteredInsightsUrl($x, ['types' => [$type]]))
+ ->assertOk()
+ ->assertInertia(fn (Assert $page) => $page
+ ->where('report.summary.posts.value', count($expected))
+ ->where('publications.data', fn ($publications): bool => collect($publications)->pluck('id')->sort()->values()->all() === collect($expected)->map(fn (string $key): string => $ids[$key])->sort()->values()->all())
+ ->etc());
+})->with([
+ 'poll' => ['x_poll', ['poll', 'external_poll']],
+ 'post' => ['x_post', ['post', 'external_post']],
+]);
diff --git a/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php b/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php
index 8292d2bba..62ace8eac 100644
--- a/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php
+++ b/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php
@@ -12,6 +12,7 @@ use App\Services\Analytics\Collectors\Publications\PublicationHistoryCollectorFa
use App\Services\Analytics\Collectors\Publications\TikTokPublicationCollector;
use App\Services\Analytics\Collectors\Publications\XPublicationCollector;
use App\Services\Analytics\Collectors\Publications\YouTubePublicationCollector;
+use App\Support\Social\XPoll;
use Carbon\CarbonImmutable;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Bus;
@@ -450,3 +451,56 @@ test('x counts toward the timeline cap only the rows it walked before the cutoff
->and($page->providerRowCount)->toBe(1)
->and($page->nextCursor)->toBeNull();
});
+
+test('x discovery keeps the poll of a post made on x', function () {
+ $createdAt = now()->subDay()->toIso8601ZuluString();
+ $endsAt = now()->addHour()->toIso8601ZuluString();
+ Http::fake(['*' => Http::response([
+ 'data' => [
+ [
+ 'id' => 'tweet-poll',
+ 'text' => 'Should we refund?',
+ 'created_at' => $createdAt,
+ 'attachments' => ['poll_ids' => ['poll-1']],
+ ],
+ [
+ 'id' => 'tweet-media',
+ 'text' => 'A photo',
+ 'created_at' => $createdAt,
+ 'attachments' => ['media_keys' => ['media-1']],
+ ],
+ ['id' => 'tweet-plain', 'text' => 'Plain', 'created_at' => $createdAt],
+ ],
+ 'includes' => [
+ 'media' => [['media_key' => 'media-1', 'type' => 'photo', 'url' => 'https://cdn.example/tweet.jpg']],
+ 'polls' => [[
+ 'id' => 'poll-1',
+ 'duration_minutes' => 1440,
+ 'end_datetime' => $endsAt,
+ 'voting_status' => 'open',
+ 'options' => [
+ ['position' => 2, 'label' => '❌ No refund', 'votes' => 1],
+ ['position' => 1, 'label' => '✅ Refund', 'votes' => 3],
+ ],
+ ]],
+ ],
+ ])]);
+ $account = SocialAccount::factory()->create(['platform' => Platform::X, 'username' => 'example']);
+
+ $page = app(XPublicationCollector::class)->page($account, null, now()->subYear()->toImmutable());
+
+ expect($page->publications[0]->contentType)->toBe(PublicationContentType::Poll)
+ ->and($page->publications[1]->contentType)->toBe(PublicationContentType::Image)
+ ->and($page->publications[2]->contentType)->toBe(PublicationContentType::Text)
+ ->and($page->publications[0]->providerMetadata['poll'])->toEqual([
+ 'options' => [['label' => '✅ Refund', 'votes' => 3], ['label' => '❌ No refund', 'votes' => 1]],
+ 'voting_status' => 'open',
+ 'end_datetime' => $endsAt,
+ 'duration_minutes' => 1440,
+ ])
+ ->and($page->publications[1]->providerMetadata)->toHaveKey('media')->not->toHaveKey('poll')
+ ->and($page->publications[2]->providerMetadata)->toBeNull();
+ Http::assertSentCount(1);
+ Http::assertSent(fn (Request $request): bool => $request['expansions'] === 'attachments.media_keys,attachments.poll_ids'
+ && $request['poll.fields'] === XPoll::LOOKUP_FIELDS);
+});
diff --git a/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php b/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php
index 0960c0ca7..ed9546651 100644
--- a/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php
+++ b/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php
@@ -24,8 +24,10 @@ use App\Services\Analytics\Collectors\Metrics\TikTokPublicationMetricsCollector;
use App\Services\Analytics\Collectors\Metrics\XPublicationMetricsCollector;
use App\Services\Analytics\Collectors\Metrics\YouTubePublicationMetricsCollector;
use App\Services\Analytics\Collectors\Publications\FacebookPublicationCollector;
+use App\Support\Social\XPoll;
use Carbon\CarbonImmutable;
use Illuminate\Http\Client\Request;
+use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
@@ -926,3 +928,202 @@ test('TikTok classifies an invalid access token as an authentication failure', f
expect(fn () => app(TikTokPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC')))
->toThrow(fn (AnalyticsCollectionException $exception): bool => $exception->category === 'authentication');
});
+
+/**
+ * @return array<string, mixed>
+ */
+function xPollResponse(string $endsAt): array
+{
+ return [
+ 'data' => [
+ 'attachments' => ['poll_ids' => ['2117330255450890240']],
+ 'public_metrics' => ['impression_count' => 200, 'like_count' => 4],
+ ],
+ 'includes' => ['polls' => [[
+ 'id' => '2117330255450890240',
+ 'duration_minutes' => 1440,
+ 'end_datetime' => $endsAt,
+ 'voting_status' => 'open',
+ 'options' => [
+ ['position' => 2, 'label' => '❌ No refund', 'votes' => 2],
+ ['position' => 1, 'label' => '✅ Refund', 'votes' => 1],
+ ],
+ ]]],
+ ];
+}
+
+test('the x collector reads the poll with the metrics in one request', function () {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'platform' => Platform::X,
+ 'platform_user_id' => $account->platform_user_id,
+ 'remote_id' => '2117330256323379666',
+ ]);
+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString('millisecond');
+ Http::fake([config('trypost.platforms.x.api').'/tweets/2117330256323379666*' => Http::response(xPollResponse($endsAt))]);
+
+ $observation = app(XPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));
+
+ Http::assertSentCount(1);
+ Http::assertSent(fn (Request $request): bool => $request['expansions'] === 'attachments.poll_ids'
+ && $request['poll.fields'] === XPoll::LOOKUP_FIELDS);
+ expect($observation->providerMetadata['poll'])->toEqual([
+ 'options' => [
+ ['label' => '✅ Refund', 'votes' => 1],
+ ['label' => '❌ No refund', 'votes' => 2],
+ ],
+ 'voting_status' => 'open',
+ 'end_datetime' => $endsAt,
+ 'duration_minutes' => 1440,
+ ]);
+ $metrics = collect($observation->metrics)->mapWithKeys(fn ($metric) => [$metric->key->value => $metric->value]);
+ expect($metrics->all())->toMatchArray(['impressions' => 200, 'reactions' => 4]);
+});
+
+test('a poll whose voting state x does not report stores no state', function (array $poll) {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'platform' => Platform::X,
+ 'platform_user_id' => $account->platform_user_id,
+ 'remote_id' => '2117330256323379666',
+ ]);
+ $response = xPollResponse(now('UTC')->addDay()->toIso8601ZuluString('millisecond'));
+ data_set($response, 'includes.polls.0', [...Arr::except(data_get($response, 'includes.polls.0'), 'voting_status'), ...$poll]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets/2117330256323379666*' => Http::response($response)]);
+
+ $observation = app(XPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));
+
+ expect(data_get($observation->providerMetadata, 'poll.voting_status'))->toBeNull();
+})->with([
+ 'missing' => [[]],
+ 'unknown' => [['voting_status' => 'paused']],
+]);
+
+test('a post without a poll stores no poll result', function () {
+ Http::fake(['*' => Http::response(['data' => ['public_metrics' => ['impression_count' => 200, 'like_count' => 4]]])]);
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'platform' => Platform::X,
+ 'platform_user_id' => $account->platform_user_id,
+ ]);
+
+ $observation = app(XPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));
+
+ expect($observation->providerMetadata)->toBeNull();
+ $metrics = collect($observation->metrics)->mapWithKeys(fn ($metric) => [$metric->key->value => $metric->value]);
+ expect($metrics->all())->toMatchArray(['impressions' => 200, 'reactions' => 4]);
+});
+
+test('the x collector reads the polls of the thread replies in the same request as the post', function () {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([
+ 'meta' => ['poll' => ['options' => ['✅ Refund', '❌ No refund'], 'duration_minutes' => 1440], 'thread_replies' => [
+ ['text' => 'Why?', 'media' => []],
+ ['text' => 'And next time?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],
+ ]],
+ ]);
+ $post->forceFill(['thread_reply_ids' => ['2117330256323379667', '2117330256323379668']])->save();
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'post_id' => $post->id,
+ 'platform' => Platform::X,
+ 'platform_user_id' => $account->platform_user_id,
+ 'remote_id' => '2117330256323379666',
+ ]);
+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString('millisecond');
+ $root = xPollResponse($endsAt);
+ Http::fake([config('trypost.platforms.x.api').'/tweets*' => Http::response([
+ 'data' => [
+ ['id' => '2117330256323379666', ...$root['data']],
+ ['id' => '2117330256323379668', 'attachments' => ['poll_ids' => ['2117330255450890241']], 'public_metrics' => ['impression_count' => 9]],
+ ],
+ 'includes' => ['polls' => [...$root['includes']['polls'], [
+ 'id' => '2117330255450890241',
+ 'duration_minutes' => 60,
+ 'end_datetime' => $endsAt,
+ 'voting_status' => 'open',
+ 'options' => [['position' => 1, 'label' => 'Yes', 'votes' => 5], ['position' => 2, 'label' => 'No', 'votes' => 3]],
+ ]]],
+ ])]);
+
+ $observation = app(XPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));
+
+ Http::assertSentCount(1);
+ Http::assertSent(fn (Request $request): bool => str_starts_with($request->url(), config('trypost.platforms.x.api').'/tweets?')
+ && $request['ids'] === '2117330256323379666,2117330256323379668');
+ expect($observation->providerMetadata['poll']['options'])->toEqual([
+ ['label' => '✅ Refund', 'votes' => 1],
+ ['label' => '❌ No refund', 'votes' => 2],
+ ])->and($observation->providerMetadata['thread_polls'])->toEqual([[
+ 'reply' => 1,
+ 'options' => [['label' => 'Yes', 'votes' => 5], ['label' => 'No', 'votes' => 3]],
+ 'voting_status' => 'open',
+ 'end_datetime' => $endsAt,
+ 'duration_minutes' => 60,
+ ]]);
+ $metrics = collect($observation->metrics)->mapWithKeys(fn ($metric) => [$metric->key->value => $metric->value]);
+ expect($metrics->all())->toMatchArray(['impressions' => 200, 'reactions' => 4]);
+});
+
+test('the x collector reads the post alone when the reply with a poll never went live', function () {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([
+ 'meta' => ['poll' => ['options' => ['✅ Refund', '❌ No refund'], 'duration_minutes' => 1440], 'thread_replies' => [
+ ['text' => 'Why?', 'media' => []],
+ ['text' => 'And next time?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],
+ ]],
+ ]);
+ $post->forceFill(['thread_reply_ids' => ['2117330256323379667']])->save();
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'post_id' => $post->id,
+ 'platform' => Platform::X,
+ 'platform_user_id' => $account->platform_user_id,
+ 'remote_id' => '2117330256323379666',
+ ]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets/2117330256323379666*' => Http::response(xPollResponse(now('UTC')->addDay()->toIso8601ZuluString('millisecond')))]);
+
+ $observation = app(XPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));
+
+ Http::assertSentCount(1);
+ Http::assertSent(fn (Request $request): bool => str_starts_with($request->url(), config('trypost.platforms.x.api').'/tweets/2117330256323379666'));
+ expect($observation->providerMetadata)->toHaveKey('poll')->not->toHaveKey('thread_polls');
+});
+
+test('the x collector leaves out a reply poll whose tweet is gone and still reads the post', function () {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([
+ 'meta' => ['poll' => ['options' => ['✅ Refund', '❌ No refund'], 'duration_minutes' => 1440], 'thread_replies' => [
+ ['text' => 'And next time?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],
+ ]],
+ ]);
+ $post->forceFill(['thread_reply_ids' => ['2117330256323379668']])->save();
+ $publication = AnalyticsPublication::factory()->create([
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'post_id' => $post->id,
+ 'platform' => Platform::X,
+ 'platform_user_id' => $account->platform_user_id,
+ 'remote_id' => '2117330256323379666',
+ ]);
+ $root = xPollResponse(now('UTC')->addDay()->toIso8601ZuluString('millisecond'));
+ Http::fake([config('trypost.platforms.x.api').'/tweets*' => Http::response([
+ 'data' => [['id' => '2117330256323379666', ...$root['data']]],
+ 'includes' => $root['includes'],
+ 'errors' => [['resource_id' => '2117330256323379668', 'title' => 'Not Found Error']],
+ ])]);
+
+ $observation = app(XPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));
+
+ expect($observation->providerMetadata)->toHaveKey('poll')->not->toHaveKey('thread_polls');
+ $metrics = collect($observation->metrics)->mapWithKeys(fn ($metric) => [$metric->key->value => $metric->value]);
+ expect($metrics->all())->toMatchArray(['impressions' => 200]);
+});
diff --git a/tests/Feature/Analytics/PersistedPostMetricsReadTest.php b/tests/Feature/Analytics/PersistedPostMetricsReadTest.php
index 41b577916..f0012e674 100644
--- a/tests/Feature/Analytics/PersistedPostMetricsReadTest.php
+++ b/tests/Feature/Analytics/PersistedPostMetricsReadTest.php
@@ -256,3 +256,92 @@ test('tiktok post metrics return the saved video url and observation without a p
Http::assertNothingSent();
});
+
+test('post metrics carry the poll result on the publication in REST and MCP', function () {
+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
+ $access = createApiTestToken();
+ $user = $access['user'];
+ $account = SocialAccount::factory()->create(['workspace_id' => $access['workspace']->id, 'platform' => Platform::X]);
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $user->id, 'platform_post_id' => '123']);
+ $poll = [
+ 'options' => [['label' => 'Yes', 'votes' => 1], ['label' => 'No', 'votes' => 2]],
+ 'voting_status' => 'closed',
+ 'end_datetime' => now()->subHour()->toIso8601ZuluString('millisecond'),
+ 'duration_minutes' => 1440,
+ ];
+ $publication = AnalyticsPublication::factory()->withPoll($poll)->create([
+ 'workspace_id' => $access['workspace']->id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'post_id' => $post->id,
+ 'platform' => Platform::X,
+ 'content_type' => PublicationContentType::Text,
+ ]);
+ AnalyticsPublicationDailySnapshot::factory()->create([
+ 'publication_id' => $publication->id,
+ 'date' => now()->subDay()->toDateString(),
+ 'metrics' => ['reactions' => ['value' => 7, 'unit' => 'count', 'availability' => 'available']],
+ ]);
+
+ expect(data_get(app(ReadPublicationAnalytics::class)->forPost($post), 'metrics.publication.poll'))->toEqual($poll);
+
+ $this->withToken($access['plain_token'])
+ ->getJson(route('api.posts.metrics', $post))
+ ->assertOk()
+ ->assertJsonPath('metrics.publication.poll.options.1.votes', 2);
+
+ TryPostServer::actingAs($user)
+ ->tool(GetPostMetricsTool::class, ['post_id' => $post->id])
+ ->assertOk()
+ ->assertStructuredContent(fn (AssertableJson $json) => $json
+ ->where('metrics.publication.poll.options.1.votes', 2)
+ ->etc());
+});
+
+test('post metrics carry the poll results of the post and of its thread replies in REST and MCP', function () {
+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
+ $access = createApiTestToken();
+ $user = $access['user'];
+ $account = SocialAccount::factory()->create(['workspace_id' => $access['workspace']->id, 'platform' => Platform::X]);
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $user->id, 'platform_post_id' => '123']);
+ $poll = [
+ 'options' => [['label' => 'Yes', 'votes' => 1], ['label' => 'No', 'votes' => 2]],
+ 'voting_status' => 'closed',
+ 'end_datetime' => now()->subHour()->toIso8601ZuluString('millisecond'),
+ 'duration_minutes' => 1440,
+ ];
+ $threadPolls = [['reply' => 1, ...$poll, 'options' => [['label' => 'Tabs', 'votes' => 5], ['label' => 'Spaces', 'votes' => 3]]]];
+ $publication = AnalyticsPublication::factory()->create([
+ 'provider_metadata' => ['poll' => $poll, 'thread_polls' => $threadPolls],
+ 'workspace_id' => $access['workspace']->id,
+ 'social_account_id' => $account->id,
+ 'social_account_key' => $account->id,
+ 'post_id' => $post->id,
+ 'platform' => Platform::X,
+ 'content_type' => PublicationContentType::Text,
+ ]);
+ AnalyticsPublicationDailySnapshot::factory()->create([
+ 'publication_id' => $publication->id,
+ 'date' => now()->subDay()->toDateString(),
+ 'metrics' => ['reactions' => ['value' => 7, 'unit' => 'count', 'availability' => 'available']],
+ ]);
+
+ expect(data_get(app(ReadPublicationAnalytics::class)->forPost($post), 'metrics.publication.poll'))->toEqual($poll)
+ ->and(data_get(app(ReadPublicationAnalytics::class)->forPost($post), 'metrics.publication.thread_polls'))->toEqual($threadPolls);
+
+ $this->withToken($access['plain_token'])
+ ->getJson(route('api.posts.metrics', $post))
+ ->assertOk()
+ ->assertJsonPath('metrics.publication.poll.options.1.votes', 2)
+ ->assertJsonPath('metrics.publication.thread_polls.0.reply', 1)
+ ->assertJsonPath('metrics.publication.thread_polls.0.options.0.votes', 5);
+
+ TryPostServer::actingAs($user)
+ ->tool(GetPostMetricsTool::class, ['post_id' => $post->id])
+ ->assertOk()
+ ->assertStructuredContent(fn (AssertableJson $json) => $json
+ ->where('metrics.publication.poll.options.1.votes', 2)
+ ->where('metrics.publication.thread_polls.0.reply', 1)
+ ->where('metrics.publication.thread_polls.0.options.0.votes', 5)
+ ->etc());
+});
diff --git a/tests/Feature/Analytics/PublicationMetricsJobsTest.php b/tests/Feature/Analytics/PublicationMetricsJobsTest.php
index 4232ec09e..f6e5f6e9e 100644
--- a/tests/Feature/Analytics/PublicationMetricsJobsTest.php
+++ b/tests/Feature/Analytics/PublicationMetricsJobsTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Actions\Analytics\QueuePublicationMetricsForPage;
use App\Actions\Analytics\SyncTryPostPublication;
+use App\Actions\Analytics\UpsertAnalyticsPublication;
use App\Dto\Analytics\DiscoveredPublication;
use App\Dto\Analytics\PublicationPage;
use App\Enums\Analytics\PublicationAvailability;
@@ -539,3 +540,117 @@ test('the daily run leaves a fresh post to its first read an hour after publishi
Bus::assertNotDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $fresh->id);
Bus::assertDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $settled->id);
})->with([Platform::X, Platform::Instagram]);
+
+test('collecting x metrics stores the poll on the publication', function () {
+ $date = CarbonImmutable::now('UTC');
+ $publication = metricJobPublication(Platform::X, $date->subDay());
+ $response = fn (int $votes): array => [
+ 'data' => ['public_metrics' => ['impression_count' => 10, 'like_count' => 1]],
+ 'includes' => ['polls' => [[
+ 'duration_minutes' => 1440,
+ 'end_datetime' => $date->addDay()->toIso8601ZuluString('millisecond'),
+ 'voting_status' => 'open',
+ 'options' => [
+ ['position' => 1, 'label' => 'Yes', 'votes' => $votes],
+ ['position' => 2, 'label' => 'No', 'votes' => 2],
+ ],
+ ]]],
+ ];
+ $job = new CollectPublicationMetrics($publication->id, $date->toDateString(), refreshSameDay: true);
+
+ Http::fake(['*' => Http::sequence()
+ ->push($response(1))
+ ->push($response(5))
+ ->push(['data' => ['public_metrics' => ['impression_count' => 12, 'like_count' => 1]]])]);
+ app()->call([$job, 'handle']);
+
+ expect(data_get($publication->refresh()->provider_metadata, 'poll.options'))->toEqual([
+ ['label' => 'Yes', 'votes' => 1],
+ ['label' => 'No', 'votes' => 2],
+ ]);
+
+ app()->call([$job, 'handle']);
+
+ expect(data_get($publication->refresh()->provider_metadata, 'poll.options.0.votes'))->toBe(5);
+
+ app()->call([$job, 'handle']);
+
+ expect(data_get($publication->refresh()->provider_metadata, 'poll.options.0.votes'))->toBe(5);
+});
+
+test('storing an x poll result leaves the publication updated_at alone', function () {
+ $date = CarbonImmutable::now('UTC');
+ $publication = metricJobPublication(Platform::X, $date->subDay());
+ $updatedAt = $publication->refresh()->updated_at;
+ $this->travel(1)->hours();
+
+ Http::fake(['*' => Http::response([
+ 'data' => ['public_metrics' => ['impression_count' => 10, 'like_count' => 1]],
+ 'includes' => ['polls' => [[
+ 'duration_minutes' => 1440,
+ 'end_datetime' => $date->addDay()->toIso8601ZuluString('millisecond'),
+ 'voting_status' => 'open',
+ 'options' => [['position' => 1, 'label' => 'Yes', 'votes' => 1], ['position' => 2, 'label' => 'No', 'votes' => 2]],
+ ]]],
+ ])]);
+ app()->call([new CollectPublicationMetrics($publication->id, $date->toDateString(), refreshSameDay: true), 'handle']);
+
+ expect($publication->refresh()->provider_metadata['poll'])->not->toBeNull()
+ ->and($publication->updated_at->equalTo($updatedAt))->toBeTrue();
+});
+
+test('an x poll published by TryPost keeps its result from the metrics read through a rediscovery', function () {
+ $date = CarbonImmutable::now('UTC');
+ $publication = metricJobPublication(Platform::X, $date->subDay());
+ $publication->forceFill(['origin' => PublicationOrigin::TryPost, 'provider_metadata' => null])->save();
+ $poll = fn (int $votes): array => [
+ 'options' => [['label' => 'Yes', 'votes' => $votes], ['label' => 'No', 'votes' => 2]],
+ 'voting_status' => 'open',
+ 'end_datetime' => $date->addDay()->toIso8601ZuluString('millisecond'),
+ 'duration_minutes' => 1440,
+ ];
+
+ Http::fake(['*' => Http::response([
+ 'data' => ['public_metrics' => ['impression_count' => 10, 'like_count' => 1]],
+ 'includes' => ['polls' => [[
+ 'duration_minutes' => 1440,
+ 'end_datetime' => $date->addDay()->toIso8601ZuluString('millisecond'),
+ 'voting_status' => 'open',
+ 'options' => [['position' => 1, 'label' => 'Yes', 'votes' => 1], ['position' => 2, 'label' => 'No', 'votes' => 2]],
+ ]]],
+ ])]);
+ app()->call([new CollectPublicationMetrics($publication->id, $date->toDateString(), refreshSameDay: true), 'handle']);
+
+ expect($publication->refresh()->provider_metadata)->toEqual(['poll' => $poll(1)]);
+
+ app(UpsertAnalyticsPublication::class)->external($publication->socialAccount, new DiscoveredPublication(
+ providerPostId: $publication->remote_id,
+ publishedAt: $publication->provider_published_at->toImmutable(),
+ contentType: PublicationContentType::Text,
+ providerMetadata: ['poll' => $poll(4)],
+ ));
+
+ expect($publication->refresh()->provider_metadata)->toEqual(['poll' => $poll(4)]);
+});
+
+test('a rediscovery keeps the poll results of the thread replies, which only the metrics read sees, and drops what it no longer reports', function () {
+ $date = CarbonImmutable::now('UTC');
+ $publication = metricJobPublication(Platform::X, $date->subDay());
+ $poll = fn (int $votes): array => [
+ 'options' => [['label' => 'Yes', 'votes' => $votes], ['label' => 'No', 'votes' => 2]],
+ 'voting_status' => 'open',
+ 'end_datetime' => $date->addDay()->toIso8601ZuluString('millisecond'),
+ 'duration_minutes' => 1440,
+ ];
+ $threadPolls = [['reply' => 0, ...$poll(7)]];
+ $publication->forceFill(['origin' => PublicationOrigin::TryPost, 'provider_metadata' => ['poll' => $poll(1), 'thread_polls' => $threadPolls, 'media' => [['type' => 'photo', 'url' => 'https://pbs.twimg.com/media/old.jpg']]]])->save();
+
+ app(UpsertAnalyticsPublication::class)->external($publication->socialAccount, new DiscoveredPublication(
+ providerPostId: $publication->remote_id,
+ publishedAt: $publication->provider_published_at->toImmutable(),
+ contentType: PublicationContentType::Text,
+ providerMetadata: ['poll' => $poll(4)],
+ ));
+
+ expect($publication->refresh()->provider_metadata)->toEqual(['poll' => $poll(4), 'thread_polls' => $threadPolls]);
+});
diff --git a/tests/Feature/Analytics/PublicationReconciliationTest.php b/tests/Feature/Analytics/PublicationReconciliationTest.php
index d2787fb1a..203422f52 100644
--- a/tests/Feature/Analytics/PublicationReconciliationTest.php
+++ b/tests/Feature/Analytics/PublicationReconciliationTest.php
@@ -146,6 +146,26 @@ test('TikTok public video id replaces a post imported from that video with the T
->and(Post::query()->count())->toBe(1);
});
+test('reconciling a remote id keeps the reply poll results the metrics read stored, next to the discovered poll', function () {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create(['platform_post_id' => 'provisional']);
+ $provisional = app(SyncTryPostPublication::class)->handle($post);
+ $threadPolls = [['reply' => 0, 'options' => [['label' => 'Yes', 'votes' => 5]], 'voting_status' => 'open']];
+ $provisional->forceFill(['provider_metadata' => ['thread_polls' => $threadPolls]])->save();
+ $poll = ['options' => [['label' => 'Tabs', 'votes' => 3]], 'voting_status' => 'open'];
+ app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(
+ providerPostId: '987654321',
+ publishedAt: CarbonImmutable::now('UTC')->subDay(),
+ contentType: PublicationContentType::Poll,
+ providerMetadata: ['poll' => $poll],
+ ));
+
+ app(UpsertAnalyticsPublication::class)->reconcileRemoteId($provisional, '987654321');
+
+ expect(AnalyticsPublication::query()->count())->toBe(1)
+ ->and($provisional->fresh()->provider_metadata)->toEqual(['poll' => $poll, 'thread_polls' => $threadPolls]);
+});
+
test('TikTok public id owned by another TryPost post is still refused', function () {
$account = SocialAccount::factory()->create(['platform' => Platform::TikTok]);
$targets = collect(['v_pub_provisional', '123456789'])->map(fn (string $remoteId): Post => Post::factory()->forAccount($account, ContentType::TikTokVideo)->published()->create([
@@ -282,6 +302,7 @@ test('a network that does not report the type keeps the type TryPost published',
})->with([
'TikTok photo' => [Platform::TikTok, ContentType::TikTokPhoto, PublicationContentType::Carousel],
'YouTube Short' => [Platform::YouTube, ContentType::YouTubeShort, PublicationContentType::Short],
+ 'X poll' => [Platform::X, ContentType::XPoll, PublicationContentType::Poll],
]);
test('a network that does not report the type stores its default on a new publication', function () {
diff --git a/tests/Feature/Api/PlatformApiTest.php b/tests/Feature/Api/PlatformApiTest.php
index 10af71de3..d6d5b7538 100644
--- a/tests/Feature/Api/PlatformApiTest.php
+++ b/tests/Feature/Api/PlatformApiTest.php
@@ -59,6 +59,22 @@ it('lists content types per platform', function () {
expect($pinterestTypes->firstWhere('value', 'pinterest_pin')['min_media_count'])->toBe(0);
});
+it('lists the x poll without media capabilities', function () {
+ $response = $this->withToken($this->plainToken)
+ ->getJson(route('api.content-types'))
+ ->assertOk();
+
+ $poll = collect(data_get($response->collect('platforms')->firstWhere('platform', 'x'), 'content_types'))->firstWhere('value', 'x_poll');
+
+ expect($poll)->toMatchArray([
+ 'max_media_count' => 0,
+ 'accepts_gif' => false,
+ 'max_image_bytes' => null,
+ 'max_video_bytes' => null,
+ 'max_video_duration_sec' => null,
+ ]);
+});
+
it('rejects content-types without auth', function () {
$this->getJson(route('api.content-types'))->assertUnauthorized();
});
diff --git a/tests/Feature/Api/PostApiPlatformMetaTest.php b/tests/Feature/Api/PostApiPlatformMetaTest.php
index 9435355c5..a297ecdb1 100644
--- a/tests/Feature/Api/PostApiPlatformMetaTest.php
+++ b/tests/Feature/Api/PostApiPlatformMetaTest.php
@@ -12,7 +12,9 @@ use App\Jobs\PublishPost;
use App\Models\Media;
use App\Models\Post;
use App\Models\SocialAccount;
+use App\Support\Social\XPoll;
use Illuminate\Http\UploadedFile;
+use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
@@ -1400,3 +1402,280 @@ it('refuses music volumes outside 0 to 100, a cover that is not a link and a tra
'cover not a link' => [['cover_url' => 'not a link'], 'meta.audio.cover_url'],
'track id not numeric' => [['id' => 'abc'], 'meta.audio.id'],
]);
+
+it('creates an x poll draft and stores its poll', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Tabs or spaces?',
+ 'status' => PostStatus::Draft->value,
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => ['options' => [' Yes ', '', 'No'], 'duration_minutes' => '60']],
+ ])->assertCreated();
+
+ expect(Post::where('social_account_id', $x->id)->sole()->meta['poll'])
+ ->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => 60]);
+});
+
+it('rejects an x poll with invalid choices or length', function (array $poll, string $error) {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Tabs or spaces?',
+ 'status' => PostStatus::Draft->value,
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => $poll],
+ ])->assertUnprocessable()->assertJsonValidationErrors($error);
+
+ $this->assertDatabaseMissing(Post::class, ['social_account_id' => $x->id]);
+})->with([
+ 'five options' => [['options' => ['a', 'b', 'c', 'd', 'e'], 'duration_minutes' => 60], 'meta.poll.options'],
+ 'option over 25 characters' => [['options' => [Str::repeat('a', 26), 'b'], 'duration_minutes' => 60], 'meta.poll.options.0'],
+ 'duration below 5' => [['options' => ['a', 'b'], 'duration_minutes' => 4], 'meta.poll.duration_minutes'],
+ 'duration above 10080' => [['options' => ['a', 'b'], 'duration_minutes' => 10081], 'meta.poll.duration_minutes'],
+ 'duration not a number' => [['options' => ['a', 'b'], 'duration_minutes' => 'abc'], 'meta.poll.duration_minutes'],
+ 'repeated option ignoring case' => [['options' => ['Yes', ' yes'], 'duration_minutes' => 60], 'meta.poll.options'],
+]);
+
+it('explains what is wrong with an x poll in plain words', function (mixed $poll, string $error, string $message) {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Tabs or spaces?',
+ 'status' => PostStatus::Draft->value,
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => $poll],
+ ])->assertUnprocessable()->assertJsonValidationErrors([$error => $message]);
+})->with([
+ 'choice over 25 characters' => [['options' => [Str::repeat('a', 26), 'b'], 'duration_minutes' => 60], 'meta.poll.options.0', 'Each poll choice can have up to 25 characters. Shorten the longer one.'],
+ 'five options' => [['options' => ['a', 'b', 'c', 'd', 'e'], 'duration_minutes' => 60], 'meta.poll.options', 'A poll can have up to 4 choices. Remove the extra ones.'],
+ 'duration above 10080' => [['options' => ['a', 'b'], 'duration_minutes' => 10081], 'meta.poll.duration_minutes', 'A poll can stay open from 5 minutes to 7 days. Choose a length in that range.'],
+ 'poll that is not an object' => ['Yes or no', 'meta.poll', 'Send the poll with its choices (options) and length (duration_minutes).'],
+ 'choices sent as text' => [['options' => 'Yes, No', 'duration_minutes' => 60], 'meta.poll.options', 'Send the poll choices as a list of text.'],
+ 'a choice that is not text' => [['options' => ['Yes', ['No']], 'duration_minutes' => 60], 'meta.poll.options.1', 'Each poll choice must be text.'],
+]);
+
+it('cannot schedule an incomplete x poll', function (string $content, ?array $poll, string $error) {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => $content,
+ 'status' => PostStatus::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => blank($poll) ? [] : ['poll' => $poll],
+ ])->assertUnprocessable()->assertJsonValidationErrors($error);
+})->with([
+ 'no poll' => ['Question', null, 'meta.poll.options'],
+ 'one blank option' => ['Question', ['options' => ['Yes', ''], 'duration_minutes' => 60], 'meta.poll.options'],
+ 'no duration' => ['Question', ['options' => ['Yes', 'No']], 'meta.poll.duration_minutes'],
+ 'no question' => ['', ['options' => ['Yes', 'No'], 'duration_minutes' => 60], 'content'],
+]);
+
+it('asks for the question of an x poll scheduled without text', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => '',
+ 'status' => PostStatus::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],
+ ])->assertUnprocessable()->assertJsonValidationErrors(['content' => 'Write your poll question in the post text.']);
+});
+
+it('measures x poll choices after blanks and spaces are dropped', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $exactly25 = Str::repeat('a', XPoll::OPTION_MAX_LENGTH);
+
+ $response = $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Pick one',
+ 'status' => PostStatus::Draft->value,
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => ['options' => ['Yes', 'No', 'Maybe', " {$exactly25} ", ''], 'duration_minutes' => 60]],
+ ])->assertCreated();
+
+ expect(data_get(Post::query()->findOrFail($response->json('id'))->meta, 'poll.options'))
+ ->toBe(['Yes', 'No', 'Maybe', $exactly25]);
+});
+
+it('saves an incomplete x poll as a draft', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Question',
+ 'status' => PostStatus::Draft->value,
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => ['options' => ['Yes']]],
+ ])->assertCreated();
+});
+
+it('schedules a complete x poll', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Question',
+ 'status' => PostStatus::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]],
+ ])->assertCreated();
+
+ expect(Post::where('social_account_id', $x->id)->sole()->status)->toBe(PostStatus::Scheduled);
+});
+
+it('does not store a poll on an x post', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Plain post',
+ 'status' => PostStatus::Draft->value,
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPost->value,
+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],
+ ])->assertCreated();
+
+ expect(Post::where('social_account_id', $x->id)->sole()->meta)->not->toHaveKey('poll');
+});
+
+it('drops the stored poll when an x poll becomes an x post', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($x, ContentType::XPoll)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Question',
+ 'status' => PostStatus::Draft,
+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],
+ ]);
+
+ $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
+ 'content_type' => ContentType::XPost->value,
+ ])->assertOk();
+
+ expect($post->fresh()->meta)->not->toHaveKey('poll');
+});
+
+it('refuses media on an x poll', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $upload = Media::factory()->temporaryUpload($this->workspace)->stored()->create();
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Question',
+ 'status' => PostStatus::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],
+ 'media' => [['upload_token' => $upload->upload_token]],
+ ])->assertUnprocessable();
+
+ $this->assertDatabaseMissing(Post::class, ['social_account_id' => $x->id]);
+});
+
+it('refuses to attach media to an x poll', function () {
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->create(['user_id' => $this->user->id, 'status' => PostStatus::Draft]);
+ $upload = Media::factory()->temporaryUpload($this->workspace)->stored()->create();
+ $storedMedia = Media::query()->count();
+ Http::fake();
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store-media', $post), [
+ 'media' => UploadedFile::fake()->image('photo.jpg'),
+ ])->assertUnprocessable()->assertJsonValidationErrors(['media' => __('posts.errors.media_not_accepted')]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.attach-media-from-upload', $post), [
+ 'upload_token' => $upload->upload_token,
+ ])->assertUnprocessable()->assertJsonValidationErrors(['media' => __('posts.errors.media_not_accepted')]);
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.attach-media-from-url', $post), [
+ 'urls' => [['url' => 'https://example.com/photo.png']],
+ ])->assertUnprocessable()->assertJsonValidationErrors(['urls' => __('posts.errors.media_not_accepted')]);
+
+ expect($post->fresh()->media)->toBeEmpty()
+ ->and(Media::query()->count())->toBe($storedMedia);
+ Http::assertNothingSent();
+});
+
+it('still saves a threads ghost post draft with media and attaches media to it, the poll rules being x only', function () {
+ $threads = SocialAccount::factory()->threads()->create(['workspace_id' => $this->workspace->id]);
+ $draft = Media::factory()->temporaryUpload($this->workspace)->stored()->create();
+ $attached = Media::factory()->temporaryUpload($this->workspace)->stored()->create();
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Boo',
+ 'status' => PostStatus::Draft->value,
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsGhostPost->value,
+ 'media' => [['upload_token' => $draft->upload_token]],
+ ])->assertCreated();
+ $post = Post::where('social_account_id', $threads->id)->sole();
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.attach-media-from-upload', $post), [
+ 'upload_token' => $attached->upload_token,
+ ])->assertOk();
+
+ expect($post->fresh()->media)->toHaveCount(2);
+});
+
+it('returns the poll of an x poll it creates and updates', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ $response = $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
+ 'content' => 'Tabs or spaces?',
+ 'status' => PostStatus::Draft->value,
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],
+ ])->assertCreated()
+ ->assertJsonPath('content_type', ContentType::XPoll->value)
+ ->assertJsonPath('meta.poll.options', ['Tabs', 'Spaces'])
+ ->assertJsonPath('meta.poll.duration_minutes', 60);
+
+ $this->withHeaders($this->headers)->putJson(route('api.posts.update', $response->json('id')), [
+ 'meta' => ['poll' => ['duration_minutes' => 4320]],
+ ])->assertOk()
+ ->assertJsonPath('content_type', ContentType::XPoll->value)
+ ->assertJsonPath('meta.poll.options', ['Tabs', 'Spaces'])
+ ->assertJsonPath('meta.poll.duration_minutes', 4320);
+
+ $this->withHeaders($this->headers)->getJson(route('api.posts.show', $response->json('id')))
+ ->assertOk()
+ ->assertJsonPath('meta.poll.duration_minutes', 4320);
+});
+
+it('keeps a scheduled x poll scheduled with its choices when only its length changes', function () {
+ Queue::fake();
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($x, ContentType::XPoll)->scheduled()->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Tabs or spaces?',
+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 1440]],
+ ]);
+
+ $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
+ 'meta' => ['poll' => ['duration_minutes' => 60]],
+ ])->assertOk();
+
+ expect($post->fresh())
+ ->status->toBe(PostStatus::Scheduled)
+ ->content_type->toBe(ContentType::XPoll)
+ ->meta->toEqual(['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]]);
+});
+
+it('still attaches media to a draft without a channel', function () {
+ $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'status' => PostStatus::Draft]);
+ $upload = Media::factory()->temporaryUpload($this->workspace)->stored()->create();
+
+ $this->withHeaders($this->headers)->postJson(route('api.posts.attach-media-from-upload', $post), [
+ 'upload_token' => $upload->upload_token,
+ ])->assertSuccessful();
+
+ expect($post->fresh())->content_type->toBeNull()->media->toHaveCount(1);
+});
diff --git a/tests/Feature/Api/RepurposeApiTest.php b/tests/Feature/Api/RepurposeApiTest.php
index dc3d96244..47b779130 100644
--- a/tests/Feature/Api/RepurposeApiTest.php
+++ b/tests/Feature/Api/RepurposeApiTest.php
@@ -291,6 +291,21 @@ test('a content type from another network is rejected for a destination', functi
->assertJsonValidationErrors('destinations.0.content_type');
});
+test('an x poll is refused as the format a repurposed video publishes as', function () {
+ $x = SocialAccount::factory()->for($this->workspace)->x()->create();
+
+ $this->withHeaders(apiHeaders($this->token))
+ ->postJson(route('api.repurposes.store'), [
+ 'source_social_account_id' => $this->source->id,
+ 'destinations' => [[
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ ]],
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors(['destinations.0.content_type' => __('repurposes.errors.destination_needs_video')]);
+});
+
test('the api refuses a transition the interface would never offer', function () {
$repurpose = Repurpose::factory()->create([
'workspace_id' => $this->workspace->id,
diff --git a/tests/Feature/Mcp/PlatformToolTest.php b/tests/Feature/Mcp/PlatformToolTest.php
index a3c9c11f8..7f8cd77a0 100644
--- a/tests/Feature/Mcp/PlatformToolTest.php
+++ b/tests/Feature/Mcp/PlatformToolTest.php
@@ -105,3 +105,22 @@ test('list content types exposes reel max video durations', function () {
expect($pinterestTypes->firstWhere('value', 'pinterest_carousel')['min_media_count'])->toBe(2);
});
});
+
+test('list content types shows the x poll without media capabilities', function () {
+ TryPostServer::actingAs($this->user)
+ ->tool(ListContentTypesTool::class, [])
+ ->assertOk()
+ ->assertStructuredContent(function (AssertableJson $json) {
+ $json->etc();
+
+ $poll = collect(data_get(collect(data_get($json->toArray(), 'platforms'))->firstWhere('platform', 'x'), 'content_types'))->firstWhere('value', 'x_poll');
+
+ expect($poll)->toMatchArray([
+ 'max_media_count' => 0,
+ 'accepts_gif' => false,
+ 'max_image_bytes' => null,
+ 'max_video_bytes' => null,
+ 'max_video_duration_sec' => null,
+ ]);
+ });
+});
diff --git a/tests/Feature/Mcp/PostPlatformMetaToolTest.php b/tests/Feature/Mcp/PostPlatformMetaToolTest.php
index 43039a3a7..1cba987fb 100644
--- a/tests/Feature/Mcp/PostPlatformMetaToolTest.php
+++ b/tests/Feature/Mcp/PostPlatformMetaToolTest.php
@@ -11,6 +11,7 @@ use App\Enums\TikTok\PrivacyLevel;
use App\Jobs\PublishPost;
use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\AttachMediaFromUploadTool;
+use App\Mcp\Tools\Post\AttachMediaFromUrlTool;
use App\Mcp\Tools\Post\CreatePostTool;
use App\Mcp\Tools\Post\GetPostTool;
use App\Mcp\Tools\Post\PublishPostTool;
@@ -20,6 +21,8 @@ use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
+use App\Support\Social\XPoll;
+use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
@@ -1065,3 +1068,113 @@ test('publish post rejects instagram music on an account not connected through F
->tool(PublishPostTool::class, ['post_id' => $post->id])
->assertHasErrors([__('posts.form.instagram.music.requires_facebook')]);
});
+
+test('an x poll is stored normalized through the create and update tools', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
+ 'content' => 'Tabs or spaces?',
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => ['options' => [' Yes ', '', 'No'], 'duration_minutes' => 60]],
+ ])->assertOk();
+ $post = Post::where('social_account_id', $x->id)->sole();
+
+ expect($post->meta['poll'])->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => 60]);
+
+ TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
+ 'post_id' => $post->id,
+ 'content_type' => ContentType::XPost->value,
+ ])->assertOk();
+
+ expect($post->fresh()->meta)->not->toHaveKey('poll');
+});
+
+test('an x poll with invalid choices is refused by the create tool', function (array $poll, string $message, array $replace) {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
+ 'content' => 'Tabs or spaces?',
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => $poll],
+ ])->assertHasErrors([__($message, $replace)]);
+
+ $this->assertDatabaseMissing('posts', ['social_account_id' => $x->id]);
+})->with([
+ 'five options' => [['options' => ['a', 'b', 'c', 'd', 'e'], 'duration_minutes' => 60], 'posts.form.x.poll.options_max', ['max' => XPoll::MAX_OPTIONS]],
+ 'choice over 25 characters' => [['options' => [Str::repeat('a', 26), 'b'], 'duration_minutes' => 60], 'posts.form.x.poll.choice_max', ['max' => XPoll::OPTION_MAX_LENGTH]],
+ 'repeated option' => [['options' => ['Yes', ' yes'], 'duration_minutes' => 60], 'posts.form.x.poll.options_distinct', []],
+]);
+
+test('an incomplete x poll cannot be scheduled through the create tool', function (?array $poll, string $message) {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+
+ TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
+ 'content' => 'Question',
+ 'status' => PostStatus::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => blank($poll) ? [] : ['poll' => $poll],
+ ])->assertHasErrors([__($message)]);
+})->with([
+ 'no options' => [null, fn (): string => XPoll::optionsRequiredMessage()],
+ 'no duration' => [['options' => ['Yes', 'No']], 'posts.form.x.poll.duration_required'],
+]);
+
+test('publish post refuses a stored x poll without options or duration', function (array $poll, string $message) {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($x, ContentType::XPoll)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Question',
+ 'status' => PostStatus::Draft,
+ 'meta' => ['poll' => $poll],
+ ]);
+
+ TryPostServer::actingAs($this->user)
+ ->tool(PublishPostTool::class, ['post_id' => $post->id])
+ ->assertHasErrors([__($message)]);
+
+ expect($post->fresh()->status)->toBe(PostStatus::Draft);
+})->with([
+ 'no options' => [[], fn (): string => XPoll::optionsRequiredMessage()],
+ 'no duration' => [['options' => ['Yes', 'No']], 'posts.form.x.poll.duration_required'],
+]);
+
+test('the attach media tools refuse media on an x poll', function () {
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->create(['user_id' => $this->user->id, 'status' => PostStatus::Draft]);
+ $upload = Media::factory()->temporaryUpload($this->workspace)->stored()->create();
+ Http::fake();
+
+ TryPostServer::actingAs($this->user)->tool(AttachMediaFromUploadTool::class, [
+ 'post_id' => $post->id,
+ 'upload_token' => $upload->upload_token,
+ ])->assertHasErrors([__('posts.errors.media_not_accepted')]);
+
+ TryPostServer::actingAs($this->user)->tool(AttachMediaFromUrlTool::class, [
+ 'post_id' => $post->id,
+ 'urls' => [['url' => 'https://example.com/photo.png']],
+ ])->assertHasErrors([__('posts.errors.media_not_accepted')]);
+
+ expect($post->fresh()->media)->toBeEmpty();
+ Http::assertNothingSent();
+});
+
+test('the get post tool returns the poll of an x poll', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($x, ContentType::XPoll)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Tabs or spaces?',
+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],
+ ]);
+
+ TryPostServer::actingAs($this->user)->tool(GetPostTool::class, ['post_id' => $post->id])
+ ->assertOk()
+ ->assertStructuredContent(fn (AssertableJson $json) => $json
+ ->where('content_type', ContentType::XPoll->value)
+ ->where('meta.poll.options', ['Tabs', 'Spaces'])
+ ->where('meta.poll.duration_minutes', 60)
+ ->etc());
+});
diff --git a/tests/Feature/Parity/XPollParityTest.php b/tests/Feature/Parity/XPollParityTest.php
new file mode 100644
index 000000000..36c485540
--- /dev/null
+++ b/tests/Feature/Parity/XPollParityTest.php
@@ -0,0 +1,393 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Dto\MediaItem;
+use App\Enums\Post\Status;
+use App\Enums\PostPlatform\ContentType;
+use App\Enums\SocialAccount\Platform;
+use App\Mcp\Servers\TryPostServer;
+use App\Mcp\Tools\Post\PublishPostTool;
+use App\Mcp\Tools\Post\UpdatePostTool;
+use App\Models\Media;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Support\Social\XPoll;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Str;
+use Illuminate\Testing\TestResponse;
+use Laravel\Mcp\Server\Testing\TestResponse as McpTestResponse;
+
+beforeEach(function () {
+ ['user' => $this->user, 'workspace' => $this->workspace, 'token' => $this->token] = parityContext();
+});
+
+function xPollParityPost(ContentType $type = ContentType::XPoll, array $meta = [], array $accountMeta = []): Post
+{
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => test()->workspace->id, 'meta' => $accountMeta]);
+
+ return Post::factory()->forAccount($account, $type)->create([
+ 'user_id' => test()->user->id,
+ 'content' => 'Tabs or spaces?',
+ 'status' => Status::Draft,
+ 'media' => [],
+ 'meta' => $meta,
+ ]);
+}
+
+/**
+ * Sends the same post update through one surface: the web composer, the REST
+ * API or the MCP tool.
+ *
+ * @param array<string, mixed> $changes
+ */
+function xPollParityUpdate(string $surface, Post $post, array $changes): TestResponse|McpTestResponse
+{
+ $payload = [
+ 'content' => $post->content,
+ 'content_type' => $post->content_type->value,
+ 'status' => Status::Draft->value,
+ ...$changes,
+ ];
+
+ return match ($surface) {
+ 'web' => test()->actingAs(test()->user)->putJson(route('app.posts.update', $post), ['media' => [], ...$payload]),
+ 'api' => test()->withHeaders(parityApi(test()->token))->putJson(route('api.posts.update', $post), $payload),
+ 'mcp' => TryPostServer::actingAs(test()->user)->tool(UpdatePostTool::class, ['post_id' => $post->id, ...$payload]),
+ };
+}
+
+test('a valid x poll is stored normalized on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost();
+
+ $response = xPollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [' Yes ', '', 'No'], 'duration_minutes' => 60]]]);
+
+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();
+ expect($post->fresh()->meta['poll'])->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => 60]);
+})->with(['web', 'api', 'mcp']);
+
+test('x poll choices that repeat or number five are refused on the web, api and mcp', function (string $surface, array $options) {
+ $post = xPollParityPost();
+
+ $response = xPollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => $options, 'duration_minutes' => 60]]]);
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors()
+ : $response->assertUnprocessable()->assertJsonValidationErrors('meta.poll.options');
+ expect($post->fresh()->meta)->toBe([]);
+})->with(['web', 'api', 'mcp'])->with([
+ 'repeated option' => [['Yes', ' yes']],
+ 'five options' => [['a', 'b', 'c', 'd', 'e']],
+]);
+
+test('scheduling an x poll without options is refused on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost();
+
+ $response = xPollParityUpdate($surface, $post, [
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ ]);
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors([XPoll::optionsRequiredMessage()])
+ : $response->assertUnprocessable()->assertJsonValidationErrors(['meta.poll.options' => XPoll::optionsRequiredMessage()]);
+ expect($post->fresh()->status)->toBe(Status::Draft);
+})->with(['web', 'api', 'mcp']);
+
+test('switching an x poll to an x post drops the poll on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);
+
+ $response = xPollParityUpdate($surface, $post, ['content_type' => ContentType::XPost->value, 'meta' => []]);
+
+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();
+ expect($post->fresh()->meta)->not->toHaveKey('poll');
+})->with(['web', 'api', 'mcp']);
+
+test('an x poll update keeps the parts it does not send on the web, api and mcp', function (string $surface, array $poll, array $expected) {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 4320]]);
+
+ $response = xPollParityUpdate($surface, $post, ['meta' => ['poll' => $poll]]);
+
+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();
+ expect($post->fresh()->meta['poll'])->toEqual($expected);
+})->with(['web', 'api', 'mcp'])->with([
+ 'options only' => [['options' => ['Tabs', 'Spaces', 'Both']], ['options' => ['Tabs', 'Spaces', 'Both'], 'duration_minutes' => 4320]],
+ 'length only' => [['duration_minutes' => 60], ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 60]],
+ 'fewer options' => [['options' => ['Yes', 'No']], ['options' => ['Yes', 'No'], 'duration_minutes' => 4320]],
+ 'choices that only look alike as numbers' => [['options' => ['1', '01']], ['options' => ['1', '01'], 'duration_minutes' => 4320]],
+]);
+
+test('scheduling an x poll that sends only part of its poll keeps the rest on the web, api and mcp', function (string $surface, array $poll, array $expected) {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 4320]]);
+
+ $response = xPollParityUpdate($surface, $post, [
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'meta' => ['poll' => $poll],
+ ]);
+
+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();
+ expect($post->fresh())
+ ->status->toBe(Status::Scheduled)
+ ->and($post->fresh()->meta['poll'])->toEqual($expected);
+})->with(['web', 'api', 'mcp'])->with([
+ 'length only' => [['duration_minutes' => 60], ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 60]],
+ 'options only' => [['options' => ['Tabs', 'Spaces']], ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 4320]],
+]);
+
+test('scheduling an x poll with media is refused on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);
+ $upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();
+ Http::fake();
+
+ $response = xPollParityUpdate($surface, $post, [
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],
+ ]);
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors([__('posts.errors.media_not_accepted')])
+ : expect($response->assertUnprocessable()->collect('errors')->flatten()->all())->toBe([__('posts.errors.media_not_accepted')]);
+ expect($post->fresh())->status->toBe(Status::Draft)->media->toBeEmpty();
+})->with(['web', 'api', 'mcp']);
+
+test('an x poll draft with media is refused on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);
+ $upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();
+ Http::fake();
+
+ $response = xPollParityUpdate($surface, $post, [
+ 'status' => Status::Draft->value,
+ 'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],
+ ]);
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors([__('posts.errors.media_not_accepted')])
+ : $response->assertUnprocessable()->assertJsonValidationErrors(['media' => __('posts.errors.media_not_accepted')]);
+ expect($post->fresh()->media)->toBeEmpty();
+})->with(['web', 'api', 'mcp']);
+
+test('scheduling an x poll without a question asks only for the question on the web, api and mcp', function (string $surface, string $content) {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);
+
+ $response = xPollParityUpdate($surface, $post, [
+ 'content' => $content,
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ ]);
+
+ if ($surface === 'mcp') {
+ $response->assertHasErrors([__('posts.form.x.poll.question_required')])
+ ->assertDontSee(__('posts.edit.compliance.requires_content_or_media'));
+ } else {
+ $response->assertUnprocessable()
+ ->assertJsonValidationErrors(['content' => __('posts.form.x.poll.question_required')])
+ ->assertDontSee(__('posts.edit.compliance.requires_content_or_media'));
+ }
+ expect($post->fresh()->status)->toBe(Status::Draft);
+})->with(['web', 'api', 'mcp'])->with([
+ 'no text' => [''],
+ 'editor markup without words' => ['<p> </p>'],
+]);
+
+test('a poll on a thread reply is stored normalized on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost(ContentType::XPost);
+
+ $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [
+ ['text' => 'Tabs or spaces?', 'poll' => ['options' => [' Tabs ', '', 'Spaces'], 'duration_minutes' => 60]],
+ ]]]);
+
+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();
+ expect($post->fresh()->meta['thread_replies'])->toEqual([
+ ['text' => 'Tabs or spaces?', 'media' => [], 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],
+ ]);
+})->with(['web', 'api', 'mcp']);
+
+test('repeated choices on a thread reply poll are refused on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost(ContentType::XPost);
+
+ $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [
+ ['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Yes', ' yes'], 'duration_minutes' => 60]],
+ ]]]);
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors([__('posts.form.x.poll.options_distinct')])
+ : $response->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies.0.poll.options' => __('posts.form.x.poll.options_distinct')]);
+ expect($post->fresh()->meta)->toBe([]);
+})->with(['web', 'api', 'mcp']);
+
+test('scheduling a thread reply poll without its question or with one choice is refused on the web, api and mcp', function (string $surface, array $reply, string $field, string $message) {
+ $post = xPollParityPost(ContentType::XPost);
+
+ $response = xPollParityUpdate($surface, $post, [
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'meta' => ['thread_replies' => [$reply]],
+ ]);
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors([__($message)])
+ : $response->assertUnprocessable()->assertJsonValidationErrors([$field => __($message)]);
+ expect($post->fresh()->status)->toBe(Status::Draft);
+})->with(['web', 'api', 'mcp'])->with([
+ 'no question' => [['text' => '', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], 'meta.thread_replies.0', 'posts.form.x.poll.question_required'],
+ 'a question of empty markup' => [['text' => '<p></p>', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], 'meta.thread_replies.0', 'posts.form.x.poll.question_required'],
+ 'no length' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Yes', 'No']]], 'meta.thread_replies.0.poll.duration_minutes', 'posts.form.x.poll.duration_required'],
+ 'one choice' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Yes'], 'duration_minutes' => 60]], 'meta.thread_replies.0.poll.options', fn (): string => XPoll::optionsRequiredMessage()],
+]);
+
+test('a thread reply poll with media is refused even as a draft on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost(ContentType::XPost);
+ $upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();
+ Http::fake();
+
+ $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [
+ [
+ 'text' => 'Tabs or spaces?',
+ 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60],
+ 'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],
+ ],
+ ]]]);
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors([__('posts.errors.media_not_accepted')])
+ : $response->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies.0.media' => __('posts.errors.media_not_accepted')]);
+ expect($post->fresh()->meta)->toBe([]);
+})->with(['web', 'api', 'mcp']);
+
+test('a thread with polls on the post and on its replies is scheduled on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);
+
+ $response = xPollParityUpdate($surface, $post, [
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60], 'thread_replies' => [
+ ['text' => 'And on Fridays?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 120]],
+ ['text' => 'Thanks for voting!'],
+ ]],
+ ]);
+
+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();
+ expect($post->fresh())
+ ->status->toBe(Status::Scheduled)
+ ->and($post->fresh()->meta['thread_replies'][0]['poll'])->toEqual(['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 120]);
+})->with(['web', 'api', 'mcp']);
+
+test('a thread reply poll off x is dropped, never checked, on the web, api and mcp', function (string $surface) {
+ $account = SocialAccount::factory()->create(['workspace_id' => test()->workspace->id, 'platform' => Platform::Bluesky]);
+ $post = Post::factory()->forAccount($account, ContentType::BlueskyPost)->create([
+ 'user_id' => test()->user->id,
+ 'content' => 'Thread',
+ 'status' => Status::Draft,
+ 'media' => [],
+ 'meta' => [],
+ ]);
+ $upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();
+ Http::fake();
+
+ $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [[
+ 'text' => 'Tabs or spaces?',
+ 'poll' => ['options' => ['Tabs'], 'duration_minutes' => 60],
+ 'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],
+ ]]]]);
+
+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();
+ expect($post->fresh()->meta['thread_replies'][0])->not->toHaveKey('poll')
+ ->and($post->fresh()->meta['thread_replies'][0]['media'])->toHaveCount(1);
+})->with(['web', 'api', 'mcp']);
+
+test('an empty poll on a thread reply is no poll on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost(ContentType::XPost);
+ $upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();
+ Http::fake();
+
+ $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [[
+ 'text' => 'Just a photo',
+ 'poll' => [],
+ 'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],
+ ]]]]);
+
+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();
+ expect($post->fresh()->meta['thread_replies'][0])->not->toHaveKey('poll')
+ ->and($post->fresh()->meta['thread_replies'][0]['media'])->toHaveCount(1);
+})->with(['web', 'api', 'mcp']);
+
+test('publishing a stored x poll without a question is refused before it reaches x on mcp', function () {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);
+ $post->update(['content' => '<p></p>']);
+
+ TryPostServer::actingAs(test()->user)
+ ->tool(PublishPostTool::class, ['post_id' => $post->id])
+ ->assertHasErrors([__('posts.form.x.poll.question_required')]);
+
+ expect($post->fresh()->status)->toBe(Status::Draft);
+});
+
+test('a poll question over 280 characters is refused on a long post account on the web, api and mcp, while the same text as a post passes', function (string $surface) {
+ $poll = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], accountMeta: ['x_subscription_type' => 'Premium']);
+ $schedule = ['content' => Str::repeat('a', XPoll::QUESTION_MAX_LENGTH + 1), 'status' => Status::Scheduled->value, 'scheduled_at' => now()->addDay()->toIso8601String()];
+ $message = __('posts.form.content_exceeds_platform', ['platform' => Platform::X->label(), 'limit' => XPoll::QUESTION_MAX_LENGTH, 'over' => 1]);
+
+ $response = xPollParityUpdate($surface, $poll, $schedule);
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors([$message])
+ : expect($response->assertUnprocessable()->collect('errors')->flatten()->all())->toContain($message);
+ expect($poll->fresh()->status)->toBe(Status::Draft);
+
+ $post = xPollParityPost(ContentType::XPost, accountMeta: ['x_subscription_type' => 'Premium']);
+ $passed = xPollParityUpdate($surface, $post, $schedule);
+
+ $surface === 'mcp' ? $passed->assertOk() : $passed->assertSessionHasNoErrors();
+ expect($post->fresh()->status)->toBe(Status::Scheduled);
+})->with(['web', 'api', 'mcp']);
+
+test('an api update that sends only the text measures it against the stored poll type', function () {
+ $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], accountMeta: ['x_subscription_type' => 'Premium']);
+
+ test()->withHeaders(parityApi(test()->token))->putJson(route('api.posts.update', $post), [
+ 'content' => Str::repeat('a', XPoll::QUESTION_MAX_LENGTH + 1),
+ 'status' => Status::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ ])->assertUnprocessable();
+
+ expect($post->fresh()->status)->toBe(Status::Draft);
+});
+
+test('a thread reply poll question over 280 characters is refused on a long post account on the web, api and mcp, while the same reply without a poll passes', function (string $surface) {
+ $post = xPollParityPost(ContentType::XPost, accountMeta: ['x_subscription_type' => 'Premium']);
+ $question = Str::repeat('a', XPoll::QUESTION_MAX_LENGTH + 1);
+ $schedule = fn (array $reply): array => ['status' => Status::Scheduled->value, 'scheduled_at' => now()->addDay()->toIso8601String(), 'meta' => ['thread_replies' => [$reply]]];
+ $message = __('posts.form.thread.reply_too_long', ['limit' => XPoll::QUESTION_MAX_LENGTH, 'over' => 1]);
+
+ $response = xPollParityUpdate($surface, $post, $schedule(['text' => $question, 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]));
+
+ $surface === 'mcp'
+ ? $response->assertHasErrors([$message])
+ : $response->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies.0' => $message]);
+ expect($post->fresh()->status)->toBe(Status::Draft);
+
+ $passed = xPollParityUpdate($surface, $post, $schedule(['text' => $question]));
+
+ $surface === 'mcp' ? $passed->assertOk() : $passed->assertSessionHasNoErrors();
+ expect($post->fresh()->status)->toBe(Status::Scheduled);
+})->with(['web', 'api', 'mcp']);
+
+test('a choice is measured as x counts it, an emoji like a penguin counting two, on the web, api and mcp', function (string $surface) {
+ $post = xPollParityPost();
+ $tooLong = '🐧 '.Str::repeat('a', 23);
+ $fits = '🐧 '.Str::repeat('a', 22);
+ $message = __('posts.form.x.poll.choice_max', ['max' => XPoll::OPTION_MAX_LENGTH]);
+
+ $refused = xPollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [$tooLong, 'No'], 'duration_minutes' => 60]]]);
+
+ $surface === 'mcp'
+ ? $refused->assertHasErrors([$message])
+ : $refused->assertUnprocessable()->assertJsonValidationErrors(['meta.poll.options.0' => $message]);
+
+ $accepted = xPollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [$fits, 'No'], 'duration_minutes' => 60]]]);
+
+ $surface === 'mcp' ? $accepted->assertOk() : $accepted->assertSessionHasNoErrors();
+ expect($post->fresh()->meta['poll']['options'])->toBe([$fits, 'No']);
+})->with(['web', 'api', 'mcp']);
diff --git a/tests/Feature/Posts/ImportExternalPostsTest.php b/tests/Feature/Posts/ImportExternalPostsTest.php
index 015e42a50..18e98ca5b 100644
--- a/tests/Feature/Posts/ImportExternalPostsTest.php
+++ b/tests/Feature/Posts/ImportExternalPostsTest.php
@@ -21,6 +21,7 @@ use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Analytics\Collectors\Publications\FacebookPublicationCollector;
use App\Support\Social\ThreadProgress;
+use App\Support\Social\XPoll;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
@@ -799,3 +800,65 @@ test('a caption with a less-than sign links to its own publication', function ()
expect(Post::query()->imported()->count())->toBe(0)
->and($tryPost->fresh()->platform_post_id)->toBe('media-1');
});
+
+test('imports an x poll made on x as a poll', function () {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ externalPublication($account, [
+ 'remote_id' => 'x-poll-1',
+ 'excerpt' => 'Should we refund?',
+ 'content_type' => PublicationContentType::Poll,
+ 'provider_metadata' => ['poll' => [
+ 'options' => [['label' => '✅ Refund', 'votes' => 3], ['label' => '❌ No refund', 'votes' => 1]],
+ 'voting_status' => 'open',
+ 'end_datetime' => now()->addHour()->toIso8601ZuluString(),
+ 'duration_minutes' => 1440,
+ ]],
+ ]);
+ externalPublication($account, ['remote_id' => 'x-plain-1', 'excerpt' => 'Plain', 'content_type' => PublicationContentType::Text]);
+
+ ImportExternalPosts::execute($account);
+
+ $poll = Post::query()->imported()->where('platform_post_id', 'x-poll-1')->sole();
+ $plain = Post::query()->imported()->where('platform_post_id', 'x-plain-1')->sole();
+
+ expect($poll->content_type)->toBe(ContentType::XPoll)
+ ->and($poll->meta)->toEqual(['poll' => ['options' => ['✅ Refund', '❌ No refund'], 'duration_minutes' => 1440]])
+ ->and($plain->content_type)->toBe(ContentType::XPost)
+ ->and($plain->meta)->toBe([]);
+});
+
+test('an imported x poll without a length gets the default one', function () {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ externalPublication($account, [
+ 'remote_id' => 'x-poll-3',
+ 'excerpt' => 'Tabs or spaces?',
+ 'content_type' => PublicationContentType::Poll,
+ 'provider_metadata' => ['poll' => [
+ 'options' => [['label' => 'Tabs', 'votes' => 0], ['label' => 'Spaces', 'votes' => 0]],
+ 'voting_status' => 'open',
+ 'end_datetime' => null,
+ 'duration_minutes' => null,
+ ]],
+ ]);
+
+ ImportExternalPosts::execute($account);
+
+ expect(Post::query()->imported()->where('platform_post_id', 'x-poll-3')->sole()->meta)
+ ->toEqual(['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => XPoll::DEFAULT_DURATION]]);
+});
+
+test('a poll published through trypost is linked, not imported again', function () {
+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);
+ $tryPost = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create(['platform_post_id' => 'x-poll-2']);
+ $publication = externalPublication($account, [
+ 'remote_id' => 'x-poll-2',
+ 'content_type' => PublicationContentType::Poll,
+ 'provider_metadata' => ['poll' => ['options' => [['label' => 'Yes', 'votes' => 3], ['label' => 'No', 'votes' => 1]], 'voting_status' => 'open', 'duration_minutes' => 1440]],
+ ]);
+ $count = Post::query()->count();
+
+ expect(ImportExternalPosts::execute($account))->toBe([])
+ ->and(Post::query()->count())->toBe($count)
+ ->and(Post::query()->where('content_type', ContentType::XPoll)->sole()->id)->toBe($tryPost->id)
+ ->and($publication->fresh()->post_id)->toBe($tryPost->id);
+});
diff --git a/tests/Feature/Posts/PostApprovalActionsTest.php b/tests/Feature/Posts/PostApprovalActionsTest.php
index 734cfca17..36de18385 100644
--- a/tests/Feature/Posts/PostApprovalActionsTest.php
+++ b/tests/Feature/Posts/PostApprovalActionsTest.php
@@ -356,3 +356,40 @@ test('approving a pending edit whose slot vanished places it in the first free s
expect(approvalActionsSlot($edited))->toBe('Wed 09:00')
->and($edited->schedule_mode)->toBe(ScheduleMode::Queue);
});
+
+test('approving an x poll request schedules it as a poll with its choices', function (array $timing) {
+ $x = SocialAccount::factory()->x()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'timezone' => 'America/Sao_Paulo',
+ 'posting_schedule' => PostingSchedule::empty()->withTime(1, '09:00'),
+ ]);
+ $poll = ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60];
+ $request = CreatePosts::execute($this->workspace, $this->requester, [
+ 'status' => 'scheduled',
+ 'content' => 'Tabs or spaces?',
+ 'media' => [],
+ 'destinations' => [[
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPoll->value,
+ 'meta' => ['poll' => $poll],
+ ]],
+ ...$timing,
+ ])->sole();
+
+ expect($request->status)->toBe(PostStatus::PendingApproval)
+ ->and($request->content_type)->toBe(ContentType::XPoll)
+ ->and($request->meta['poll'])->toEqual($poll);
+
+ $this->actingAs($this->owner)
+ ->put(route('app.posts.approve', $request))
+ ->assertSessionHasNoErrors();
+
+ expect($request->refresh())
+ ->status->toBe(PostStatus::Scheduled)
+ ->scheduled_at->not->toBeNull()
+ ->content_type->toBe(ContentType::XPoll)
+ ->meta->toEqual(['poll' => $poll]);
+})->with([
+ 'custom time' => [fn () => ['queue' => null, 'scheduled_at' => now()->addDays(2)->toIso8601String()]],
+ 'queue' => [['queue' => 'next']],
+]);
diff --git a/tests/Feature/Posts/PostRecurrenceTest.php b/tests/Feature/Posts/PostRecurrenceTest.php
index 29801b9a5..d4a3ba186 100644
--- a/tests/Feature/Posts/PostRecurrenceTest.php
+++ b/tests/Feature/Posts/PostRecurrenceTest.php
@@ -688,3 +688,23 @@ test('an author who left the workspace hands the next occurrence to the workspac
expect(nextOccurrence($post)->user_id)->toBe($this->user->id);
});
+
+test('the next occurrence of a recurring x poll keeps its poll', function () {
+ $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id, 'timezone' => 'UTC']);
+ $poll = ['options' => ['Tabs', 'Spaces', 'Both'], 'duration_minutes' => 60];
+ $post = recurringPost($x, $this->user, [
+ 'content_type' => ContentType::XPoll,
+ 'content' => 'Tabs or spaces?',
+ 'scheduled_at' => now()->subMinute(),
+ 'recurrence_interval' => 1,
+ 'recurrence_frequency' => RecurrenceFrequency::Day,
+ 'recurrence_remaining' => 2,
+ 'meta' => ['poll' => $poll],
+ ]);
+
+ publishRecurringPost($post);
+
+ expect(nextOccurrence($post))
+ ->content_type->toBe(ContentType::XPoll)
+ ->meta->toEqual(['poll' => $poll]);
+});
diff --git a/tests/Feature/Posts/XLongPostTest.php b/tests/Feature/Posts/XLongPostTest.php
index b81e79802..9421b74ce 100644
--- a/tests/Feature/Posts/XLongPostTest.php
+++ b/tests/Feature/Posts/XLongPostTest.php
@@ -4,6 +4,8 @@ declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
use App\Exceptions\Social\ContentLimitException;
+use App\Mcp\Servers\TryPostServer;
+use App\Mcp\Tools\Post\PreviewPostTool;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
@@ -13,6 +15,8 @@ use App\Services\Social\XPublisher;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
+use Illuminate\Support\Str;
+use Illuminate\Testing\Fluent\AssertableJson;
beforeEach(function () {
$this->user = User::factory()->create();
@@ -110,3 +114,54 @@ test('the post content cap counts the text a reader sees, not the editor markup'
'markup over the cap, text under it' => [str_repeat('<p>abcd</p>', 4000), true],
'text over the cap' => [str_repeat('a', 25001), false],
]);
+
+test('a poll question is capped at 280 characters even with long posts', function (ContentType $type, bool $passes) {
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id, 'meta' => ['x_subscription_type' => 'Premium']]);
+ $validator = Validator::make(
+ ['content' => Str::repeat('a', 281)],
+ ['content' => [new ContentFitsPlatformLimits(collect([$account]), [[]], [$type->value])]],
+ );
+
+ expect($validator->passes())->toBe($passes);
+})->with([
+ 'poll' => [ContentType::XPoll, false],
+ 'post' => [ContentType::XPost, true],
+]);
+
+test('the publisher refuses a 281-character poll question', function () {
+ $account = SocialAccount::factory()->x()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'meta' => ['x_subscription_type' => 'Premium'],
+ 'token_expires_at' => now()->addHours(2),
+ ]);
+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->create([
+ 'user_id' => $this->user->id,
+ 'content' => Str::repeat('a', 281),
+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]],
+ ]);
+ Http::fake();
+
+ expect(fn () => (new XPublisher)->publish($post))->toThrow(ContentLimitException::class);
+ Http::assertNothingSent();
+});
+
+test('the api and mcp previews report the limit of the post type on a long post account', function (ContentType $type, int $limit) {
+ $token = createApiTestToken();
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $token['workspace']->id, 'meta' => ['x_subscription_type' => 'Premium']]);
+ $post = Post::factory()->forAccount($account, $type)->create([
+ 'user_id' => $token['user']->id,
+ 'content' => 'Tabs or spaces?',
+ 'meta' => $type === ContentType::XPoll ? ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]] : [],
+ ]);
+
+ $this->withToken($token['plain_token'])->getJson(route('api.posts.preview', $post))
+ ->assertOk()
+ ->assertJsonPath('max_content_length', $limit);
+
+ TryPostServer::actingAs($token['user'])->tool(PreviewPostTool::class, ['post_id' => $post->id])
+ ->assertOk()
+ ->assertStructuredContent(fn (AssertableJson $json) => $json->where('max_content_length', $limit)->etc());
+})->with([
+ 'poll' => [ContentType::XPoll, 280],
+ 'post' => [ContentType::XPost, 25000],
+]);
diff --git a/tests/Feature/Repurpose/CaptionAdapterTest.php b/tests/Feature/Repurpose/CaptionAdapterTest.php
index 52fec256f..970bec501 100644
--- a/tests/Feature/Repurpose/CaptionAdapterTest.php
+++ b/tests/Feature/Repurpose/CaptionAdapterTest.php
@@ -22,11 +22,11 @@ test('a caption that does not fit is truncated at a word boundary when ai is una
$workspace = Workspace::factory()->create();
$caption = str_repeat('palavra ', 2000);
- expect(Platform::TikTok->contentOverflow($caption))->toBeGreaterThan(0);
+ expect(mb_strlen($caption))->toBeGreaterThan(Platform::TikTok->maxContentLength());
$result = app(CaptionAdapter::class)->adapt($workspace, null, $caption, Platform::TikTok);
- expect(Platform::TikTok->contentOverflow($result))->toBe(0)
+ expect(mb_strlen($result))->toBeLessThanOrEqual(Platform::TikTok->maxContentLength())
->and($result)->not->toEndWith('palavr')
->and($result)->toEndWith('palavra');
});
@@ -37,7 +37,7 @@ test('truncation respects the tightest limit we support', function () {
$result = app(CaptionAdapter::class)->adapt($workspace, null, $caption, Platform::YouTube);
- expect(Platform::YouTube->contentOverflow($result))->toBe(0)
+ expect(mb_strlen($result))->toBeLessThanOrEqual(Platform::YouTube->maxContentLength())
->and($result)->toStartWith('A really long YouTube Short caption');
});
@@ -63,7 +63,7 @@ test('a shortened caption that still overflows falls back to truncation', functi
$result = app(CaptionAdapter::class)->adapt($workspace, $user, str_repeat('palavra ', 2000), Platform::YouTube);
- expect(Platform::YouTube->contentOverflow($result))->toBe(0)
+ expect(mb_strlen($result))->toBeLessThanOrEqual(Platform::YouTube->maxContentLength())
->and($result)->toStartWith('palavra');
});
@@ -76,7 +76,7 @@ test('truncation targets the text the publisher sends, not the raw caption', fun
$result = app(CaptionAdapter::class)->adapt($workspace, null, $caption, Platform::X);
$sent = app(ContentSanitizer::class)->displayText($result, Platform::X);
- expect(Platform::X->contentOverflow($sent))->toBe(0)
+ expect(mb_strlen($sent))->toBeLessThanOrEqual(Platform::X->maxContentLength())
->and(mb_strlen($sent))->toBeGreaterThan(200);
});
@@ -86,7 +86,7 @@ test('a caption keeps almost the whole allowance when nothing rewrites it', func
$result = app(CaptionAdapter::class)->adapt($workspace, null, $caption, Platform::TikTok);
- expect(Platform::TikTok->contentOverflow($result))->toBe(0)
+ expect(mb_strlen($result))->toBeLessThanOrEqual(Platform::TikTok->maxContentLength())
->and(mb_strlen($result))->toBeGreaterThan(Platform::TikTok->maxContentLength() - 10);
});
@@ -96,7 +96,7 @@ test('truncation keeps the line breaks the caption was written with', function (
$result = app(CaptionAdapter::class)->adapt($workspace, null, $caption, Platform::TikTok);
- expect(Platform::TikTok->contentOverflow($result))->toBe(0)
+ expect(mb_strlen($result))->toBeLessThanOrEqual(Platform::TikTok->maxContentLength())
->and($result)->toStartWith("Linha um\nLinha dois\n\n");
});
@@ -106,7 +106,7 @@ test('a caption with no word boundary is cut hard rather than emptied', function
$result = app(CaptionAdapter::class)->adapt($workspace, null, str_repeat('a', 500), Platform::YouTube);
expect($result)->not->toBe('')
- ->and(Platform::YouTube->contentOverflow($result))->toBe(0);
+ ->and(mb_strlen($result))->toBeLessThanOrEqual(Platform::YouTube->maxContentLength());
});
test('the shortener prompt carries no brand context', function () {
@@ -130,7 +130,7 @@ test('a self-hosted install with no ai configured still gets a caption that fits
$result = app(CaptionAdapter::class)->adapt($workspace, $user, str_repeat('palavra ', 300), Platform::YouTube);
expect($result)->not->toBe('')
- ->and(Platform::YouTube->contentOverflow($result))->toBe(0);
+ ->and(mb_strlen($result))->toBeLessThanOrEqual(Platform::YouTube->maxContentLength());
});
test('a single word longer than the limit is cut mid-word rather than emptied', function () {
@@ -141,7 +141,7 @@ test('a single word longer than the limit is cut mid-word rather than emptied',
expect($adapted)->not->toBe('')
->and(mb_strlen($adapted))->toBeLessThan(6000)
- ->and(Platform::YouTube->contentOverflow($adapted))->toBe(0);
+ ->and(mb_strlen($adapted))->toBeLessThanOrEqual(Platform::YouTube->maxContentLength());
});
test('a caption of one long word without spaces terminates instead of looping', function () {
@@ -149,7 +149,7 @@ test('a caption of one long word without spaces terminates instead of looping',
$adapted = app(CaptionAdapter::class)->adapt($workspace, null, str_repeat('x', 500), Platform::X);
- expect(Platform::X->contentOverflow($adapted))->toBe(0)
+ expect(mb_strlen($adapted))->toBeLessThanOrEqual(Platform::X->maxContentLength())
->and($adapted)->not->toBe('');
});
@@ -160,7 +160,7 @@ test('newlines and repeated spaces survive truncation', function () {
$adapted = app(CaptionAdapter::class)->adapt($workspace, null, $caption, Platform::X);
expect($adapted)->toStartWith("First line\n\nSecond line with gaps")
- ->and(Platform::X->contentOverflow($adapted))->toBe(0);
+ ->and(mb_strlen($adapted))->toBeLessThanOrEqual(Platform::X->maxContentLength());
});
test('two networks sharing a character limit ask the shortener once, not twice', function () {
diff --git a/tests/Feature/Repurpose/ProcessItemTest.php b/tests/Feature/Repurpose/ProcessItemTest.php
index b5023f835..96f65ff51 100644
--- a/tests/Feature/Repurpose/ProcessItemTest.php
+++ b/tests/Feature/Repurpose/ProcessItemTest.php
@@ -144,6 +144,26 @@ test('destination meta is carried onto the post', function () {
expect($tiktokPost->meta)->toEqual(['privacy_level' => PrivacyLevel::PublicToEveryone->value]);
});
+test('a destination stored with null meta creates its post with empty meta', function () {
+ Bus::fake([PublishPost::class]);
+ fakeVideoDownload();
+
+ $item = repurposeWithTwoDestinations();
+ $destinations = $item->repurpose->destinations;
+ data_set($destinations, '1.meta', null);
+ $item->repurpose->update(['destinations' => $destinations]);
+
+ processItem($item->fresh());
+
+ $youtubePost = Post::query()
+ ->where('repurpose_item_id', $item->id)
+ ->where('platform', Platform::YouTube)
+ ->sole();
+
+ expect($item->fresh()->status)->toBe(ItemStatus::Published)
+ ->and($youtubePost->meta)->toBe([]);
+});
+
test('a caption over a destination limit is shortened for that post only', function () {
Bus::fake([PublishPost::class]);
fakeVideoDownload();
@@ -158,8 +178,8 @@ test('a caption over a destination limit is shortened for that post only', funct
->get()
->mapWithKeys(fn (Post $post) => [$post->platform->value => $post->content]);
- expect(Platform::TikTok->contentOverflow($captions[Platform::TikTok->value]))->toBe(0)
- ->and(Platform::YouTube->contentOverflow($captions[Platform::YouTube->value]))->toBe(0)
+ expect(mb_strlen($captions[Platform::TikTok->value]))->toBeLessThanOrEqual(Platform::TikTok->maxContentLength())
+ ->and(mb_strlen($captions[Platform::YouTube->value]))->toBeLessThanOrEqual(Platform::YouTube->maxContentLength())
->and(mb_strlen($captions[Platform::YouTube->value]))
->toBeGreaterThan(mb_strlen($captions[Platform::TikTok->value]));
});
@@ -212,7 +232,7 @@ test('a mastodon caption leaves room for the content warning', function () {
$caption = repurposedCaption($item);
expect(mb_strlen($caption))->toBeGreaterThan(300)
- ->and($account->contentOverflow($caption, Platform::Mastodon->reservedLength(['spoiler_text' => $warning])))->toBe(0);
+ ->and(mb_strlen($caption) + Platform::Mastodon->reservedLength(['spoiler_text' => $warning]))->toBeLessThanOrEqual($account->maxContentLength());
});
test('a discord destination stores the channel name from the cached list, not the one it was saved with', function () {
diff --git a/tests/Feature/Services/Social/ContentSanitizerTest.php b/tests/Feature/Services/Social/ContentSanitizerTest.php
index cc2777b61..435c5db12 100644
--- a/tests/Feature/Services/Social/ContentSanitizerTest.php
+++ b/tests/Feature/Services/Social/ContentSanitizerTest.php
@@ -330,8 +330,8 @@ test('it measures a platform limit against the rendered text, not the markup', f
$content = implode(' & ', array_fill(0, 900, 'a'));
expect($sanitizer->displayText($content, Platform::Telegram))->toBe($content)
- ->and(Platform::Telegram->contentOverflow($sanitizer->displayText($content, Platform::Telegram)))
- ->toBe(0);
+ ->and(mb_strlen($sanitizer->displayText($content, Platform::Telegram)))
+ ->toBeLessThanOrEqual(Platform::Telegram->maxContentLength());
});
test('it counts the defused form for x because those characters are visible', function () {
diff --git a/tests/Feature/Services/Social/XPublisherTest.php b/tests/Feature/Services/Social/XPublisherTest.php
index 6fb09c0d5..c70542d9e 100644
--- a/tests/Feature/Services/Social/XPublisherTest.php
+++ b/tests/Feature/Services/Social/XPublisherTest.php
@@ -3,12 +3,14 @@
declare(strict_types=1);
use App\Enums\Post\PublishStatus;
+use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ContentLimitException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\XPublishException;
use App\Exceptions\TokenExpiredException;
+use App\Jobs\PublishPost;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Post;
use App\Models\SocialAccount;
@@ -17,11 +19,14 @@ use App\Models\Workspace;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\XPublisher;
use App\Support\Social\PublishCheckpoint;
+use App\Support\Social\XPoll;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
+use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Sleep;
+use Illuminate\Support\Str;
/**
* Official X upload STATUS: GET /2/media/upload?media_id=...&command=STATUS
@@ -1925,3 +1930,215 @@ test('x publisher fails on a v1-shaped upload response without data.id', functio
'simple upload' => ['image/jpeg', 'https://example.com/media/2026-01/photo.jpg', '/2/media/upload'],
'chunked initialize' => ['video/mp4', 'https://example.com/media/2026-01/clip.mp4', '/2/media/upload/initialize'],
]);
+
+function xPollMeta(array $overrides = []): array
+{
+ return ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440, ...$overrides]];
+}
+
+test('x publisher publishes an x poll with its choices and length', function () {
+ $this->post->update(['content' => 'Pick one', 'content_type' => ContentType::XPoll, 'meta' => xPollMeta()]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);
+
+ $this->publisher->publish($this->post->fresh());
+
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Pick one', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]);
+});
+
+test('x publisher publishes an x post whose text is 0', function () {
+ $this->post->update(['content' => '0']);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);
+
+ $this->publisher->publish($this->post->fresh());
+
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => '0']);
+});
+
+test('x publisher sends no poll for an x post carrying a stale poll', function () {
+ $this->post->update(['meta' => xPollMeta()]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);
+
+ $this->publisher->publish($this->post->fresh());
+
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Hello from X!']);
+});
+
+test('an x poll root starts a thread whose replies carry no poll', function () {
+ $this->post->update(['content_type' => ContentType::XPoll, 'meta' => [...xPollMeta(), 'thread_replies' => ['Second']]]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::sequence()
+ ->push(['data' => ['id' => '100']], 201)
+ ->push(['data' => ['id' => '101']], 201)]);
+
+ $this->publisher->publish($this->post->fresh());
+
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Second', 'reply' => ['in_reply_to_tweet_id' => '100']]);
+ Http::assertSentCount(2);
+});
+
+test('a retry after the x poll went live does not post it again', function () {
+ $this->post->update(['content_type' => ContentType::XPoll, 'meta' => [...xPollMeta(), 'thread_replies' => ['Second']]]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::sequence()
+ ->push(['data' => ['id' => '100']], 201)
+ ->push(['title' => 'Forbidden', 'detail' => 'Not allowed', 'status' => 403], 403)
+ ->push(['data' => ['id' => '101']], 201)]);
+
+ rescue(fn () => $this->publisher->publish($this->post->fresh()), report: false);
+ $result = (new XPublisher)->publish($this->post->fresh());
+
+ expect($result['id'])->toBe('100');
+ Http::assertSentCount(3);
+ expect(Http::recorded(fn (Request $request): bool => Arr::has($request->data(), 'poll')))->toHaveCount(1);
+});
+
+test('x publisher refuses to publish an x poll with media', function () {
+ $this->post->update([
+ 'content_type' => ContentType::XPoll,
+ 'meta' => xPollMeta(),
+ 'media' => [['id' => 'm1', 'path' => 'media/a.jpg', 'url' => 'https://example.com/media/a.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'a.jpg']],
+ ]);
+ Http::fake();
+
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
+ ->toThrow(fn (XPublishException $exception) => expect($exception->getMessage())->toBe(__('posts.errors.media_not_accepted'))
+ ->and($exception->category)->toBe(ErrorCategory::ContentPolicy));
+ Http::assertNothingSent();
+});
+
+test('x publisher refuses to publish an x poll without two choices', function () {
+ $this->post->update(['content_type' => ContentType::XPoll, 'meta' => xPollMeta(['options' => ['Yes', ' ']])]);
+ Http::fake();
+
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
+ ->toThrow(fn (XPublishException $exception) => expect($exception->getMessage())->toBe(XPoll::optionsRequiredMessage())
+ ->and($exception->category)->toBe(ErrorCategory::ContentPolicy));
+ Http::assertNothingSent();
+});
+
+test('x publisher asks for the question of an x poll without text', function () {
+ $this->post->update(['content' => '', 'content_type' => ContentType::XPoll, 'meta' => xPollMeta()]);
+ Http::fake();
+
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
+ ->toThrow(fn (XPublishException $exception) => expect($exception->getMessage())->toBe(__('posts.form.x.poll.question_required'))
+ ->and($exception->category)->toBe(ErrorCategory::ContentPolicy));
+ Http::assertNothingSent();
+});
+
+test('x publisher refuses to publish an x poll without a length', function () {
+ $this->post->update(['content_type' => ContentType::XPoll, 'meta' => ['poll' => ['options' => ['Yes', 'No']]]]);
+ Http::fake();
+
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
+ ->toThrow(fn (XPublishException $exception) => expect($exception->getMessage())->toBe(__('posts.form.x.poll.duration_required'))
+ ->and($exception->category)->toBe(ErrorCategory::ContentPolicy));
+ Http::assertNothingSent();
+});
+
+test('publishing a scheduled x poll sends its poll and ends published', function () {
+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));
+ $this->post->update([
+ 'content' => 'Pick one',
+ 'content_type' => ContentType::XPoll,
+ 'status' => PostStatus::Scheduled,
+ 'scheduled_at' => now()->subMinute(),
+ 'meta' => xPollMeta(['duration_minutes' => 60]),
+ ]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);
+
+ (new PublishPost($this->post->fresh()))->handle();
+
+ Http::assertSent(fn (Request $request): bool => data_get($request->data(), 'poll') === ['options' => ['Yes', 'No'], 'duration_minutes' => 60]);
+ expect($this->post->fresh())
+ ->status->toBe(PostStatus::Published)
+ ->publish_status->toBe(PublishStatus::Published)
+ ->platform_post_id->toBe('100');
+});
+
+test('x publisher discloses an ai-generated x poll', function () {
+ $this->post->update(['content' => 'Pick one', 'content_type' => ContentType::XPoll, 'meta' => [...xPollMeta(), 'is_ai_generated' => true]]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);
+
+ $this->publisher->publish($this->post->fresh());
+
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Pick one', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440], 'made_with_ai' => true]);
+});
+
+test('a thread reply poll is sent on its reply with its choices and length', function () {
+ $this->post->update(['meta' => ['thread_replies' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]]]]]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::sequence()
+ ->push(['data' => ['id' => '100']], 201)
+ ->push(['data' => ['id' => '101']], 201)]);
+
+ $result = $this->publisher->publish($this->post->fresh());
+
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Hello from X!']);
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60], 'reply' => ['in_reply_to_tweet_id' => '100']]);
+ expect($result['thread_reply_ids'])->toBe(['101']);
+});
+
+test('a poll on the post and polls on its replies are each sent on their own tweet', function () {
+ $this->post->update(['content' => 'Pick one', 'content_type' => ContentType::XPoll, 'meta' => [...xPollMeta(), 'thread_replies' => [
+ ['text' => 'And on Fridays?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 120]],
+ ['text' => 'Thanks for voting!'],
+ ]]]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::sequence()
+ ->push(['data' => ['id' => '100']], 201)
+ ->push(['data' => ['id' => '101']], 201)
+ ->push(['data' => ['id' => '102']], 201)]);
+
+ $this->publisher->publish($this->post->fresh());
+
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Pick one', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]);
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'And on Fridays?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 120], 'reply' => ['in_reply_to_tweet_id' => '100']]);
+ Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Thanks for voting!', 'reply' => ['in_reply_to_tweet_id' => '101']]);
+});
+
+test('a retry after a thread reply poll went live does not post it again', function () {
+ $this->post->update(['meta' => ['thread_replies' => [
+ ['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],
+ ['text' => 'Last one'],
+ ]]]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::sequence()
+ ->push(['data' => ['id' => '100']], 201)
+ ->push(['data' => ['id' => '101']], 201)
+ ->push(['title' => 'Forbidden', 'detail' => 'Not allowed', 'status' => 403], 403)
+ ->push(['data' => ['id' => '102']], 201)]);
+
+ rescue(fn () => $this->publisher->publish($this->post->fresh()), report: false);
+ $result = (new XPublisher)->publish($this->post->fresh());
+
+ expect($result['thread_reply_ids'])->toBe(['101', '102']);
+ expect(Http::recorded(fn (Request $request): bool => Arr::has($request->data(), 'poll')))->toHaveCount(1);
+});
+
+test('x publisher refuses a thread reply poll without its question before posting anything', function () {
+ $this->post->update(['meta' => ['thread_replies' => [['text' => '', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]]]]]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);
+
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
+ ->toThrow(ContentLimitException::class, __('posts.form.x.poll.question_required'));
+ Http::assertNothingSent();
+});
+
+test('x publisher refuses a reply poll question over 280 characters on a long post account before posting anything', function () {
+ $this->socialAccount->update(['meta' => ['x_subscription_type' => 'Premium']]);
+ $this->post->update(['content' => 'Pick one', 'meta' => ['thread_replies' => [
+ ['text' => Str::repeat('a', XPoll::QUESTION_MAX_LENGTH + 1), 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],
+ ]]]);
+ Http::fake();
+
+ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(ContentLimitException::class);
+ Http::assertNothingSent();
+});
+
+test('x publisher refuses a poll with repeated choices before calling x', function (array $meta) {
+ $this->post->update(['content' => 'Pick one', ...$meta]);
+ Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);
+
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
+ ->toThrow(Exception::class, __('posts.form.x.poll.options_distinct'));
+ Http::assertNothingSent();
+})->with([
+ 'on the post' => [['content_type' => ContentType::XPoll, 'meta' => ['poll' => ['options' => ['Yes', 'yes'], 'duration_minutes' => 60]]]],
+ 'on a reply' => [['meta' => ['thread_replies' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Tabs', 'tabs'], 'duration_minutes' => 60]]]]]],
+]);
diff --git a/tests/Feature/SocialAccount/XSubscriptionTest.php b/tests/Feature/SocialAccount/XSubscriptionTest.php
index 1ab6eb4a9..bed9c37da 100644
--- a/tests/Feature/SocialAccount/XSubscriptionTest.php
+++ b/tests/Feature/SocialAccount/XSubscriptionTest.php
@@ -28,8 +28,7 @@ test('verifying an x account stores its subscription tier', function () {
test('the content limit follows the x tier', function (array $meta, int $limit) {
$account = SocialAccount::factory()->x()->create(['meta' => $meta]);
- expect($account->maxContentLength())->toBe($limit)
- ->and($account->contentOverflow(str_repeat('a', 300)))->toBe(max(0, 300 - $limit));
+ expect($account->maxContentLength())->toBe($limit);
})->with([
'no tier stored' => [[], 280],
'free' => [['x_subscription_type' => 'None', 'x_verified_type' => 'none'], 280],
diff --git a/tests/Feature/ThreadRepliesPreviewTest.php b/tests/Feature/ThreadRepliesPreviewTest.php
index a80211641..4d9d619bc 100644
--- a/tests/Feature/ThreadRepliesPreviewTest.php
+++ b/tests/Feature/ThreadRepliesPreviewTest.php
@@ -2,6 +2,7 @@
declare(strict_types=1);
+use App\Enums\PostPlatform\ContentType;
use App\Models\Post;
use App\Services\Post\PostPreviewer;
@@ -27,3 +28,25 @@ test('networks that cannot chain get no thread preview', function () {
expect(app(PostPreviewer::class)->forPost($post->fresh()))->not->toHaveKey('thread_replies');
});
+
+test('an x preview shows the poll of the post and of each reply that has one', function () {
+ $post = Post::factory()->x()->create([
+ 'content' => 'Pick one',
+ 'content_type' => ContentType::XPoll,
+ 'meta' => [
+ 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60],
+ 'thread_replies' => [
+ ['text' => 'And on Fridays?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 120]],
+ ['text' => 'Thanks!'],
+ ],
+ ],
+ ]);
+
+ $preview = app(PostPreviewer::class)->forPost($post->fresh());
+
+ expect($preview['poll'])->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => 60])
+ ->and($preview['thread_replies'])->toEqual([
+ ['text' => 'And on Fridays?', 'media' => [], 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 120]],
+ ['text' => 'Thanks!', 'media' => []],
+ ]);
+});
diff --git a/tests/Unit/Enums/ContentTypeTest.php b/tests/Unit/Enums/ContentTypeTest.php
index 8d07b1f78..60f209fa2 100644
--- a/tests/Unit/Enums/ContentTypeTest.php
+++ b/tests/Unit/Enums/ContentTypeTest.php
@@ -13,6 +13,7 @@ test('content type has correct labels', function () {
expect(ContentType::LinkedInPost->label())->toBe('Post');
expect(ContentType::YouTubeShort->label())->toBe('Short');
expect(ContentType::XPost->label())->toBe('Post');
+ expect(ContentType::XPoll->label())->toBe('Poll');
expect(ContentType::TikTokVideo->label())->toBe('Video');
expect(ContentType::PinterestPin->label())->toBe('Pin');
expect(ContentType::PinterestVideoPin->label())->toBe('Video Pin');
@@ -104,6 +105,7 @@ test('content type maps to correct platform', function () {
expect(ContentType::TikTokVideo->platform())->toBe(Platform::TikTok);
expect(ContentType::YouTubeShort->platform())->toBe(Platform::YouTube);
expect(ContentType::XPost->platform())->toBe(Platform::X);
+ expect(ContentType::XPoll->platform())->toBe(Platform::X);
expect(ContentType::ThreadsPost->platform())->toBe(Platform::Threads);
expect(ContentType::PinterestPin->platform())->toBe(Platform::Pinterest);
expect(ContentType::BlueskyPost->platform())->toBe(Platform::Bluesky);
@@ -130,6 +132,7 @@ test('content type has correct max media count', function () {
expect(ContentType::InstagramReel->maxMediaCount())->toBe(1);
expect(ContentType::LinkedInPost->maxMediaCount())->toBe(10);
expect(ContentType::XPost->maxMediaCount())->toBe(4);
+ expect(ContentType::XPoll->maxMediaCount())->toBe(0);
expect(ContentType::PinterestCarousel->maxMediaCount())->toBe(5);
expect(ContentType::BlueskyPost->maxMediaCount())->toBe(4);
});
@@ -141,6 +144,7 @@ test('content type supports video correctly', function () {
expect(ContentType::YouTubeShort->supportsVideo())->toBeTrue();
expect(ContentType::LinkedInPost->supportsVideo())->toBeTrue();
expect(ContentType::PinterestPin->supportsVideo())->toBeFalse();
+ expect(ContentType::XPoll->supportsVideo())->toBeFalse();
});
test('content type supports image correctly', function () {
@@ -153,6 +157,7 @@ test('content type supports image correctly', function () {
expect(ContentType::FacebookStory->autoFitsImage())->toBeTrue();
expect(ContentType::TikTokVideo->supportsImage())->toBeFalse();
expect(ContentType::YouTubeShort->supportsImage())->toBeFalse();
+ expect(ContentType::XPoll->supportsImage())->toBeFalse();
});
test('content type supports mixed media correctly', function () {
@@ -504,3 +509,24 @@ test('video aspect ratio bounds are the ranges each network documents as accepte
'x' => [ContentType::XPost, null],
'bluesky' => [ContentType::BlueskyPost, null],
]);
+
+test('a post type that takes no media advertises no media capability', function (ContentType $type) {
+ expect($type->maxMediaCount())->toBe(0)
+ ->and($type->acceptsGif())->toBeFalse()
+ ->and($type->maxImageBytes())->toBeNull()
+ ->and($type->maxVideoBytes())->toBeNull()
+ ->and($type->maxDocumentBytes())->toBeNull()
+ ->and($type->maxVideoDurationSec())->toBeNull()
+ ->and($type->preferredImageDimensions())->toBe(ContentType::ThreadsGhostPost->preferredImageDimensions());
+})->with([
+ 'x poll' => [ContentType::XPoll],
+ 'threads ghost post' => [ContentType::ThreadsGhostPost],
+]);
+
+test('a post type is compatible with the platforms it can go to', function () {
+ expect(ContentType::InstagramReel->isCompatibleWith(Platform::Instagram))->toBeTrue()
+ ->and(ContentType::InstagramReel->isCompatibleWith(Platform::InstagramFacebook))->toBeTrue()
+ ->and(ContentType::InstagramReel->isCompatibleWith(Platform::Facebook))->toBeFalse()
+ ->and(ContentType::XPoll->isCompatibleWith(Platform::X))->toBeTrue()
+ ->and(ContentType::XPoll->isCompatibleWith(Platform::Bluesky))->toBeFalse();
+});
diff --git a/tests/Unit/Enums/PlatformTest.php b/tests/Unit/Enums/PlatformTest.php
index 6f89da0fc..223e21eed 100644
--- a/tests/Unit/Enums/PlatformTest.php
+++ b/tests/Unit/Enums/PlatformTest.php
@@ -418,6 +418,18 @@ test('tiktok publish config privacy options come from the privacy level enum', f
expect(Platform::TikTok->publishConfig()['privacyLevelOptions'])->toBe(PrivacyLevel::values());
});
+test('x publish config serves the poll limits', function () {
+ expect(Platform::X->publishConfig())->toBe(['poll' => [
+ 'minOptions' => 2,
+ 'maxOptions' => 4,
+ 'optionMaxLength' => 25,
+ 'minDuration' => 5,
+ 'maxDuration' => 10080,
+ 'defaultDuration' => 1440,
+ 'questionMaxLength' => 280,
+ ]]);
+});
+
test('youtube publish config exposes only the fixed categories and the default', function () {
$config = Platform::YouTube->publishConfig();
diff --git a/tests/Unit/Enums/PostPlatform/ContentTypeFromPublicationTest.php b/tests/Unit/Enums/PostPlatform/ContentTypeFromPublicationTest.php
index 9e49dbbee..d6c5a55bf 100644
--- a/tests/Unit/Enums/PostPlatform/ContentTypeFromPublicationTest.php
+++ b/tests/Unit/Enums/PostPlatform/ContentTypeFromPublicationTest.php
@@ -22,6 +22,7 @@ function specializedPublicationTypes(): array
'tiktok carousel' => [Platform::TikTok, PublicationContentType::Carousel, ContentType::TikTokPhoto],
'pinterest video' => [Platform::Pinterest, PublicationContentType::Video, ContentType::PinterestVideoPin],
'pinterest carousel' => [Platform::Pinterest, PublicationContentType::Carousel, ContentType::PinterestCarousel],
+ 'x poll' => [Platform::X, PublicationContentType::Poll, ContentType::XPoll],
];
}
diff --git a/tests/Unit/HelpersParityTest.php b/tests/Unit/HelpersParityTest.php
new file mode 100644
index 000000000..3fa062c24
--- /dev/null
+++ b/tests/Unit/HelpersParityTest.php
@@ -0,0 +1,62 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Support\Number;
+use Illuminate\Support\Str;
+use Symfony\Component\Process\ExecutableFinder;
+use Symfony\Component\Process\Process;
+
+/**
+ * `resources/js/lib/helpers.ts` mirrors Laravel's helpers (`blank()`, `filled()`,
+ * `transform()`, `Number::clamp()`, `isEmpty()` on a string or a collection) and PHP's `is_string()` / `is_int()` /
+ * `is_float()`, so a check reads the same on the front end. Both sides answer
+ * for the same corpus of JSON values (null, blank and filled strings, numbers
+ * and booleans, empty and filled arrays and objects), and every answer must
+ * match.
+ */
+test('the typescript helpers agree with laravel on every corpus entry', function () {
+ $corpusPath = base_path('tests/fixtures/helpers-corpus.json');
+ $corpus = json_decode(file_get_contents($corpusPath), true, flags: JSON_THROW_ON_ERROR);
+
+ $node = (new ExecutableFinder)->find('node');
+
+ if ($node === null) {
+ $this->markTestSkipped('node is unavailable');
+ }
+
+ $process = (new Process([
+ $node,
+ base_path('tests/fixtures/helpers-harness.ts'),
+ resource_path('js/lib/helpers.ts'),
+ $corpusPath,
+ ]))->mustRun();
+
+ $fromPhp = array_map(fn (mixed $value): array => [
+ 'blank' => blank($value),
+ 'filled' => filled($value),
+ 'isString' => is_string($value),
+ 'isNumber' => is_int($value) || is_float($value),
+ 'transform' => transform($value, fn (): string => 'changed', 'fallback'),
+ ], $corpus);
+
+ $fromTypeScript = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);
+ $empties = array_map(
+ fn (string|array $value): bool => is_string($value) ? Str::of($value)->isEmpty() : collect($value)->isEmpty(),
+ ['', ' ', 'a', '0', [], [null], ['']],
+ );
+ $clamped = array_map(
+ fn (array $range): int|float => Number::clamp(...$range),
+ [[5, 1, 10], [-3, 1, 10], [42, 1, 10], [1, 1, 10], [10, 1, 10], [2.5, 0, 1]],
+ );
+
+ $labels = array_map(
+ fn (int $index, mixed $value): string => "{$index}: ".json_encode($value, JSON_THROW_ON_ERROR),
+ array_keys($corpus),
+ $corpus,
+ );
+
+ expect(array_combine($labels, data_get($fromTypeScript, 'values')))->toEqual(array_combine($labels, $fromPhp))
+ ->and(data_get($fromTypeScript, 'clamped'))->toEqual($clamped)
+ ->and(data_get($fromTypeScript, 'empties'))->toEqual($empties);
+});
diff --git a/tests/Unit/PostPlatformMetaRulesTest.php b/tests/Unit/PostPlatformMetaRulesTest.php
index d2ae6e72e..4bb609813 100644
--- a/tests/Unit/PostPlatformMetaRulesTest.php
+++ b/tests/Unit/PostPlatformMetaRulesTest.php
@@ -8,9 +8,10 @@ use App\Enums\SocialAccount\Platform;
use App\Enums\TikTok\PrivacyLevel;
use App\Rules\ContentFitsPlatformLimits;
use App\Support\PostPlatformMetaRules;
+use App\Support\Social\XPoll;
use Illuminate\Support\Facades\Validator;
-test('custom meta messages cover pinterest, instagram collaborators and google business', function () {
+test('custom meta messages cover pinterest, instagram collaborators, google business and x polls', function () {
expect(PostPlatformMetaRules::messages())->toBe([
'meta.link.url' => __('posts.form.pinterest.link_invalid'),
'meta.link.max' => __('posts.form.pinterest.link_max'),
@@ -19,6 +20,16 @@ test('custom meta messages cover pinterest, instagram collaborators and google b
'meta.collaborators.*.regex' => __('posts.form.instagram.collaborators.invalid'),
'meta.event.end_date.after_or_equal' => __('posts.form.google_business.event_end_date_before_start'),
'meta.event.title.max' => __('posts.form.google_business.title_max'),
+ 'meta.poll.array' => __('posts.form.x.poll.poll_object'),
+ 'meta.poll.options.array' => __('posts.form.x.poll.options_list'),
+ 'meta.poll.options.*.string' => __('posts.form.x.poll.choice_text'),
+ 'meta.poll.duration_minutes.integer' => XPoll::durationRangeMessage(),
+ 'meta.poll.duration_minutes.between' => XPoll::durationRangeMessage(),
+ 'meta.thread_replies.*.poll.array' => __('posts.form.x.poll.poll_object'),
+ 'meta.thread_replies.*.poll.options.array' => __('posts.form.x.poll.options_list'),
+ 'meta.thread_replies.*.poll.options.*.string' => __('posts.form.x.poll.choice_text'),
+ 'meta.thread_replies.*.poll.duration_minutes.integer' => XPoll::durationRangeMessage(),
+ 'meta.thread_replies.*.poll.duration_minutes.between' => XPoll::durationRangeMessage(),
]);
});
diff --git a/tests/Unit/ThreadRepliesTest.php b/tests/Unit/ThreadRepliesTest.php
index cb9c9cc7f..0f3fe531c 100644
--- a/tests/Unit/ThreadRepliesTest.php
+++ b/tests/Unit/ThreadRepliesTest.php
@@ -47,6 +47,15 @@ test('resume keeps the longest matching prefix', function () {
->and(ThreadProgress::resumable(null, ['h0']))->toBe([]);
});
+test('a segment without a poll keeps the checkpoint hash it had before polls, and a poll changes it', function () {
+ $poll = ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60];
+
+ expect(ThreadProgress::hash('two', ['m1']))->toBe(sha1((string) json_encode(['two', ['m1']])))
+ ->and(ThreadProgress::hash('two', ['m1'], null))->toBe(ThreadProgress::hash('two', ['m1']))
+ ->and(ThreadProgress::hash('two', ['m1'], $poll))->toBe(sha1((string) json_encode(['two', ['m1'], $poll])))
+ ->and(ThreadProgress::hash('two', ['m1'], $poll))->not->toBe(ThreadProgress::hash('two', ['m1']));
+});
+
test('thread_replies has a rule so validated() keeps it', function () {
expect(PostPlatformMetaRules::rules())->toHaveKeys(['meta.thread_replies', 'meta.thread_replies.*'])
->and(ThreadReplies::supports(Platform::X))->toBeTrue()
diff --git a/tests/fixtures/helpers-corpus.json b/tests/fixtures/helpers-corpus.json
new file mode 100644
index 000000000..95e78297a
--- /dev/null
+++ b/tests/fixtures/helpers-corpus.json
@@ -0,0 +1 @@
+[null, "", " ", " \t\n", "a", " a ", "0", 0, 1, -1, 0.5, true, false, [], [null], [0], [""], {}, {"a": null}, {"a": 1}]
diff --git a/tests/fixtures/helpers-harness.ts b/tests/fixtures/helpers-harness.ts
new file mode 100644
index 000000000..8e32f2217
--- /dev/null
+++ b/tests/fixtures/helpers-harness.ts
@@ -0,0 +1,28 @@
+/**
+ * Runs the helpers of `resources/js/lib/helpers.ts` over a corpus of JSON values
+ * (and `clamp()` over a few ranges) and prints the answers as JSON, so
+ * `HelpersParityTest.php` can diff them against Laravel's and PHP's own.
+ *
+ * Node strips type annotations, so the source is loaded as-is.
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const [helpersFile, corpusFile] = process.argv.slice(2);
+
+const { blank, filled, isEmpty, isString, isNumber, transform, clamp } = await import(pathToFileURL(path.resolve(helpersFile)).href);
+
+const values = (JSON.parse(fs.readFileSync(corpusFile, 'utf8')) as unknown[]).map((value) => ({
+ blank: blank(value),
+ filled: filled(value),
+ isString: isString(value),
+ isNumber: isNumber(value),
+ transform: transform(value, () => 'changed', 'fallback'),
+}));
+
+const clamped = [[5, 1, 10], [-3, 1, 10], [42, 1, 10], [1, 1, 10], [10, 1, 10], [2.5, 0, 1]].map(([value, min, max]) => clamp(value, min, max));
+
+const empties = ['', ' ', 'a', '0', [], [null], ['']].map((value) => isEmpty(value));
+
+console.log(JSON.stringify({ values, clamped, empties }));
diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.php
index f801a3bd0..dcf36431a 100644
--- a/tests/fixtures/single-line-copy.php
+++ b/tests/fixtures/single-line-copy.php
@@ -116,6 +116,7 @@ return [
'posts.content_types.instagram_story.label' => 8,
'posts.content_types.threads_ghost_post.label' => 17,
'posts.content_types.threads_post.label' => 6,
+ 'posts.content_types.x_poll.label' => 11,
'posts.content_types.youtube_short.label' => 9,
'posts.edit.tabs.preview' => 19,
'posts.form.ai_generated.label' => 17,
@@ -146,6 +147,15 @@ return [
'posts.form.thread.start' => 17,
'posts.form.threads.topic' => 9,
'posts.form.tiktok.privacy_level' => 13,
+ 'posts.form.x.poll.add_choice' => 18,
+ 'posts.form.x.poll.choice' => 10,
+ 'posts.form.x.poll.choice_optional' => 26,
+ 'posts.form.x.poll.choices' => 10,
+ 'posts.form.x.poll.days' => 6,
+ 'posts.form.x.poll.hours' => 7,
+ 'posts.form.x.poll.length' => 12,
+ 'posts.form.x.poll.minutes' => 7,
+ 'posts.form.x.poll.remove' => 21,
'posts.form.youtube.embeddable' => 23,
'posts.form.youtube.made_for_kids' => 14,
'posts.form.youtube.notify_subscribers' => 26,
@@ -157,6 +167,9 @@ return [
'posts.publish.actions.queue_setup.not_now' => 11,
'posts.publish.actions.share_link' => 29,
'posts.publish.in_google_review' => 28,
+ 'posts.publish.no_time' => 13,
+ 'posts.publish.pending_slot.next' => 14,
+ 'posts.publish.pending_slot.top' => 12,
'settings.api_keys.description' => 42,
'settings.members.access.admin_description' => 41,
'settings.members.access.needs_approval' => 25,