Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
<script setup lang="ts">
import { Head, router } from '@inertiajs/vue3';
import {
IconCheck,
IconLayoutSidebarRightCollapse,
IconLayoutSidebarRightExpand,
IconPlus,
} from '@tabler/icons-vue';
import {
useEventListener,
useSwipe,
type UseSwipeDirection,
} from '@vueuse/core';
import {
computed,
onMounted,
onUnmounted,
provide,
ref,
useTemplateRef,
watch,
} from 'vue';
import { destroy as destroyPost } from '@/actions/App/Http/Controllers/App/PostController';
import AppHeaderActions from '@/components/AppHeaderActions.vue';
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';
import LabelFilter from '@/components/labels/LabelFilter.vue';
import PostChannelFilter from '@/components/posts/PostChannelFilter.vue';
import ScheduleViewSwitch from '@/components/posts/ScheduleViewSwitch.vue';
import CalendarCustomTimeDialog from '@/components/publish/CalendarCustomTimeDialog.vue';
import CalendarDragAnnouncer from '@/components/publish/CalendarDragAnnouncer.vue';
import CalendarMonthGrid from '@/components/publish/CalendarMonthGrid.vue';
import CalendarPeriodPicker from '@/components/publish/CalendarPeriodPicker.vue';
import CalendarTimeGrid from '@/components/publish/CalendarTimeGrid.vue';
import CalendarUndatedPanel from '@/components/publish/CalendarUndatedPanel.vue';
import PublishFilterMenu from '@/components/publish/PublishFilterMenu.vue';
import PublishHeader from '@/components/publish/PublishHeader.vue';
import { Button } from '@/components/ui/button';
import { useCalendarAnnouncer } from '@/composables/calendar/useCalendarAnnouncer';
import {
calendarDragKey,
DRAG_HINT_ID,
useCalendarDrag,
} from '@/composables/calendar/useCalendarDrag';
import { usePublishFilters } from '@/composables/publish/usePublishFilters';
import { useAtLeastBreakpoint } from '@/composables/useBreakpoint';
import { useCollapseWhenTruncated } from '@/composables/useCollapseWhenTruncated';
import { openPostComposer } from '@/composables/useGlobalPostComposer';
import {
deletePostCardKey,
postCardLabelsKey,
} from '@/composables/usePostCardActions';
import { useShowPostingSlots } from '@/composables/useShowPostingSlots';
import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';
import date from '@/date';
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 { grid, settings } from '@/routes/app/channels';
import type { TimezoneOption } from '@/types/posting-schedule';
import type {
CalendarPost,
CalendarSlot,
CalendarStatus,
CalendarView,
PostCard,
PostCardLabel,
PublishChannel,
PublishScope,
PublishSocialAccount,
ScrollUndatedDrafts,
} from '@/types/publish';
interface Props {
scope: PublishScope;
channel: PublishChannel | null;
posts: Record<string, CalendarPost[]>;
currentDay: string;
currentWeekStart: string;
currentMonth: string;
view: CalendarView;
displayTimezone: string;
timezones: TimezoneOption[];
labels: PostCardLabel[];
filters: {
labels: string[];
untagged: boolean;
channels: string[];
status: CalendarStatus;
};
filterAccounts: PublishSocialAccount[];
undatedDrafts?: ScrollUndatedDrafts;
slots?: Record<string, CalendarSlot[]>;
}
const props = defineProps<Props>();
const { canCreatePost, canManageAccounts, requiresApproval } =
useWorkspaceAbilities();
const { showSlots, setShowSlots } = useShowPostingSlots();
const VIEWS: readonly CalendarView[] = ['days', 'week', 'month'];
const DAYS_SPAN = 3;
const RELOAD_PROPS = [
'posts',
'currentDay',
'currentWeekStart',
'currentMonth',
'view',
'displayTimezone',
'filters',
];
/**
* The props a reload of this page asks for. The posting slots are an optional
* prop, so they are only asked for (and built) while the viewer shows them.
*/
const reloadProps = (): string[] =>
showSlots.value ? [...RELOAD_PROPS, 'slots'] : RELOAD_PROPS;
const deleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
const customTimeDialog = ref<InstanceType<
typeof CalendarCustomTimeDialog
> | null>(null);
provide(deletePostCardKey, (post: PostCard) => {
deleteModal.value?.open({ url: destroyPost.url(post.id) });
});
provide(
postCardLabelsKey,
computed(() => props.labels),
);
const now = ref(dayjs());
let clock: ReturnType<typeof setInterval> | undefined;
let cancelSlotsReload = (): void => {};
onUnmounted(() => {
clearInterval(clock);
cancelSlotsReload();
});
const {
timezone,
setTimezone,
selectedLabelIds,
selectedUntagged,
selectedChannelIds,
filterQuery,
calendarUrlFor,
listHref,
boardHref,
} = usePublishFilters(props, { reloadProps });
const confirmCustomTime = (from: string, to: string): Promise<boolean> =>
customTimeDialog.value?.confirm(from, to, timezone.value) ??
Promise.resolve(false);
const { announcement, describeInstant, hooks } =
useCalendarAnnouncer(timezone);
const CALENDAR_VIEWS: CalendarView[] = ['days', 'week', 'month'];
const calendarDrag = useCalendarDrag({
timezone,
canCreatePost,
requiresApproval,
reloadProps: () => [...reloadProps(), 'undatedDrafts'],
isCalendarPath: (pathname) =>
CALENDAR_VIEWS.some(
(view) =>
new URL(calendarUrl(view), window.location.origin).pathname ===
pathname,
),
confirmCustomTime,
describeInstant,
...hooks,
});
provide(calendarDragKey, calendarDrag);
const { movingPostIds } = calendarDrag;
const isRescheduling = computed(() => movingPostIds.value.length > 0);
const undatedDraftList = computed(() => props.undatedDrafts?.data ?? null);
const selectedStatus = ref<CalendarStatus>(props.filters.status ?? 'all');
const undatedOpen = ref(props.undatedDrafts !== undefined);
const calendarUrl = (
view: CalendarView,
dateQuery: Record<string, string> = {},
): string => {
const query = {
...dateQuery,
...filterQuery(),
status:
selectedStatus.value !== 'all' ? selectedStatus.value : undefined,
undated: undatedOpen.value ? '1' : undefined,
slots: showSlots.value ? '1' : undefined,
};
return calendarUrlFor(view, query);
};
const visit = (url: string): void => {
router.get(
url,
{},
{ preserveState: true, preserveScroll: true, only: reloadProps() },
);
};
const reload = (
only: string[],
reset: string[] = [],
preserveUrl = false,
): void => {
router.get(
calendarUrl(props.view, currentDateQuery()),
{},
{
preserveState: true,
preserveScroll: true,
preserveUrl,
replace: true,
only,
reset,
},
);
};
watch(
[selectedLabelIds, selectedUntagged, selectedChannelIds, selectedStatus],
() => reload([...reloadProps(), 'undatedDrafts'], ['undatedDrafts']),
{ deep: true },
);
const toggleUndated = (): void => {
undatedOpen.value = !undatedOpen.value;
reload(['undatedDrafts'], ['undatedDrafts']);
};
/** On a phone the undated drafts open from the filter menu, which closes first. */
const openUndatedFromMenu = (close: () => void): void => {
close();
toggleUndated();
};
const closeUndated = (): void => {
if (undatedOpen.value) {
toggleUndated();
}
};
const toggleSlots = (value: boolean): void => {
setShowSlots(value);
if (value) {
reload(['slots']);
return;
}
reload(['displayTimezone']);
};
/**
* A full visit back to the calendar (after saving or deleting a post) brings no
* posting times unless its URL asks for them, so they are loaded again.
*/
watch(
() => props.slots,
(slots) => {
if (showSlots.value && slots === undefined) {
reload(['slots'], [], true);
}
},
);
onMounted(() => {
clock = setInterval(() => {
now.value = dayjs();
}, 60_000);
if (showSlots.value && props.slots === undefined) {
cancelSlotsReload = afterPageInHistory(() =>
reload(['slots'], [], true),
);
}
});
/**
* Every date on this screen goes through here: `dayjs.locale()` is global and
* not reactive, so a computed built on a bare `dayjs()` keeps the previous
* language's month and day names after a switch.
*/
const localized = (value?: dayjs.ConfigType) =>
dayjs(value).locale(activeLocale.value.toLowerCase());
const todayKey = computed(() =>
now.value.tz(timezone.value).format('YYYY-MM-DD'),
);
const isDesktop = useAtLeastBreakpoint('md');
const toolbar = useTemplateRef<HTMLElement>('toolbar');
const periodPicker =
useTemplateRef<InstanceType<typeof CalendarPeriodPicker>>('periodPicker');
const { collapsed: filtersCollapsed, expand: showAllFilters } =
useCollapseWhenTruncated(
toolbar,
() => periodPicker.value?.missingTitleWidth() ?? 0,
);
const compactFilters = computed(
() => !isDesktop.value || filtersCollapsed.value,
);
const periodStart = computed(() =>
localized(props.view === 'days' ? props.currentDay : props.currentWeekStart),
);
const periodLength = computed(() => (props.view === 'days' ? DAYS_SPAN : 7));
const monthDate = computed(() => localized(props.currentMonth));
const periodDays = computed(() =>
Array.from({ length: periodLength.value }, (_, index) =>
periodStart.value.add(index, 'day'),
),
);
const weekHeaderTitle = computed(() => {
const start = periodStart.value;
const end = periodStart.value.add(periodLength.value - 1, 'day');
if (start.isSame(end, 'month')) {
return `${start.format('D')}–${end.format('D MMMM YYYY')}`;
}
if (start.isSame(end, 'year')) {
return `${start.format('D MMM')} – ${end.format('D MMMM YYYY')}`;
}
return `${start.format('ll')} – ${end.format('ll')}`;
});
const calendarWeeks = computed(() => {
const start = monthDate.value.startOf('month').startOf('week');
const end = monthDate.value.endOf('month').endOf('week');
const weeks: dayjs.Dayjs[][] = [];
let current = start;
while (!current.isAfter(end, 'day')) {
if (current.day() === start.day()) {
weeks.push([]);
}
weeks[weeks.length - 1].push(current);
current = current.add(1, 'day');
}
return weeks;
});
const headerTitle = computed(() =>
props.view === 'month'
? monthDate.value.format('MMMM YYYY')
: weekHeaderTitle.value,
);
watch(headerTitle, showAllFilters);
const currentDateQuery = (
view: CalendarView = props.view,
): Record<string, string> =>
view === 'month'
? { month: props.currentMonth }
: view === 'days'
? { day: props.currentDay }
: { week: props.currentWeekStart };
const navigate = (direction: number): void => {
if (props.view === 'month') {
visit(
calendarUrl('month', {
month: monthDate.value
.add(direction, 'month')
.format('YYYY-MM-DD'),
}),
);
} else {
const start = periodStart.value
.add(direction * periodLength.value, 'day')
.format('YYYY-MM-DD');
visit(
calendarUrl(
props.view,
props.view === 'days' ? { day: start } : { week: start },
),
);
}
};
const switchView = (view: CalendarView): void => visit(calendarUrl(view));
const visibleSlots = computed<Record<string, CalendarSlot[]>>(() =>
showSlots.value ? (props.slots ?? {}) : {},
);
const slotChannels = computed<Record<string, PublishSocialAccount>>(() =>
Object.fromEntries(
(props.channel ? [props.channel] : props.filterAccounts).map(
(account) => [account.id, account],
),
),
);
const composerAccounts = (): string[] =>
props.channel ? [props.channel.id] : [];
const newPost = (): void =>
openPostComposer({ socialAccountIds: composerAccounts() });
const composeAt = (utcIso: string): void =>
openPostComposer({
date: date.formatUtcForDateTimeLocalInput(utcIso),
socialAccountIds: composerAccounts(),
});
const expandedDays = ref<string[]>([]);
const mobileTitle = computed(() => {
if (props.view === 'month') {
return monthDate.value.format('MMMM YYYY');
}
const start = periodStart.value;
const end = periodStart.value.add(periodLength.value - 1, 'day');
if (start.isSame(end, 'month')) {
return start.format('MMMM YYYY');
}
if (start.isSame(end, 'year')) {
return `${start.format('MMM')} – ${end.format('MMM YYYY')}`;
}
return `${start.format('MMM YYYY')} – ${end.format('MMM YYYY')}`;
});
const dayKeys = computed(() =>
(props.view === 'month' ? calendarWeeks.value.flat() : periodDays.value).map(
calendarDayKey,
),
);
const periodDayKeys = computed(() =>
props.view === 'month'
? dayKeys.value.filter((key) =>
key.startsWith(monthDate.value.format('YYYY-MM')),
)
: dayKeys.value,
);
const defaultDayKey = (): string =>
periodDayKeys.value.includes(todayKey.value)
? todayKey.value
: periodDayKeys.value[0];
const selectedDayKey = ref(defaultDayKey());
const pendingDayKey = ref<string | null>(null);
watch(dayKeys, (keys, previousKeys) => {
const pending = pendingDayKey.value;
pendingDayKey.value = null;
if (pending && keys.includes(pending)) {
selectedDayKey.value = pending;
return;
}
if (keys.includes(selectedDayKey.value)) {
return;
}
const offset = previousKeys.indexOf(selectedDayKey.value);
selectedDayKey.value =
props.view === 'week' &&
previousKeys.length === 7 &&
offset >= 0 &&
!keys.includes(todayKey.value)
? keys[offset]
: defaultDayKey();
});
const isRtl = (): boolean => document.documentElement.dir === 'rtl';
const swipeStep = (direction: UseSwipeDirection): number => {
if (direction !== 'left' && direction !== 'right') {
return 0;
}
return (direction === 'left') !== isRtl() ? 1 : -1;
};
const periodSwipeTarget = ref<HTMLElement | null>(null);
/**
* A touch that dragged a post is not a period swipe, even when it moved sideways.
*/
let touchDraggedPost = false;
useEventListener(
periodSwipeTarget,
'touchstart',
() => {
touchDraggedPost = false;
},
{ passive: true },
);
watch(calendarDrag.draggingPostId, (postId) => {
if (postId !== null) {
touchDraggedPost = true;
}
});
useSwipe(periodSwipeTarget, {
threshold: 48,
onSwipeEnd: (_event, direction) => {
if (touchDraggedPost) {
return;
}
const step = swipeStep(direction);
if (step !== 0) {
navigate(step);
}
},
});
const goToToday = (): void => {
if (periodDayKeys.value.includes(todayKey.value)) {
selectedDayKey.value = todayKey.value;
} else {
pendingDayKey.value = todayKey.value;
}
visit(calendarUrl(props.view));
};
const goToDay = (key: string): void => {
if (periodDayKeys.value.includes(key)) {
selectedDayKey.value = key;
return;
}
const day = localized(key);
pendingDayKey.value = key;
visit(
calendarUrl(
props.view,
{
month: { month: day.startOf('month').format('YYYY-MM-DD') },
days: { day: key },
week: { week: day.startOf('week').format('YYYY-MM-DD') },
}[props.view],
),
);
};
</script>
<template>
<Head :title="$t('calendar.title')" />
<AppLayout full-width>
<template #header>
<PublishHeader :channel="channel" />
</template>
<template #header-actions>
<div class="flex items-center gap-2">
<Button
v-if="canCreatePost"
variant="outline"
class="max-sm:w-8 max-sm:px-0"
:aria-label="$t('calendar.new_post')"
data-testid="calendar-new-post"
@click="newPost"
>
<IconPlus class="size-4" />
<span class="max-sm:sr-only">{{
$t('calendar.new_post')
}}</span>
</Button>
</div>
</template>
<div class="flex min-h-0 flex-1 flex-col">
<div
class="mx-4 mt-2 flex h-12 shrink-0 items-center justify-between gap-2 md:mx-8"
ref="toolbar"
data-testid="calendar-toolbar"
>
<CalendarPeriodPicker
ref="periodPicker"
:view="view"
:views="VIEWS"
:title="isDesktop ? headerTitle : mobileTitle"
:selected-day-key="selectedDayKey"
@navigate="navigate"
@today="goToToday"
@change-view="switchView"
@pick-day="goToDay"
/>
<div
class="flex shrink-0 items-center gap-2 md:ms-auto md:gap-0"
data-testid="calendar-filters"
>
<PostChannelFilter
v-if="scope === 'all' && filterAccounts.length"
v-model="selectedChannelIds"
:channels="filterAccounts"
sheet-below-sm
/>
<div class="shrink-0 max-md:hidden">
<LabelFilter
v-model="selectedLabelIds"
v-model:untagged="selectedUntagged"
:labels="labels"
/>
</div>
<PublishFilterMenu
v-model:status="selectedStatus"
:timezone="timezone"
test-id="calendar"
:compact="compactFilters"
:timezones="timezones"
:show-slots="showSlots"
:manage-slots-href="
channel && canManageAccounts
? settings.url(channel.id)
: null
"
@update:timezone="setTimezone"
@update:show-slots="toggleSlots"
>
<template
v-if="!isDesktop"
#compact-items="{ close }"
>
<button
type="button"
:aria-pressed="undatedOpen"
class="menu-row"
data-testid="calendar-no-date-menu"
@click="openUndatedFromMenu(close)"
>
{{ $t('calendar.undated.title') }}
<IconCheck
v-if="undatedOpen"
class="ms-auto size-4"
/>
</button>
</template>
</PublishFilterMenu>
<AppHeaderActions :on-phones="!channel">
<ScheduleViewSwitch
active-view="calendar"
:list-href="listHref"
:calendar-href="
calendarUrl(isDesktop ? 'month' : 'days')
"
:board-href="boardHref"
:grid-href="
channel?.has_grid
? grid.url(channel.id)
: undefined
"
/>
</AppHeaderActions>
<Button
variant="ghost"
class="shrink-0 max-xl:size-8 max-xl:px-0 max-md:hidden"
:class="{ 'bg-accent': undatedOpen }"
:aria-pressed="undatedOpen"
data-testid="calendar-no-date"
@click="toggleUndated"
>
<IconLayoutSidebarRightCollapse
v-if="undatedOpen"
class="size-4 text-muted-foreground"
data-testid="calendar-no-date-icon-open"
/>
<IconLayoutSidebarRightExpand
v-else
class="size-4 text-muted-foreground"
data-testid="calendar-no-date-icon-closed"
/>
<span class="max-xl:sr-only">{{
$t('calendar.no_date')
}}</span>
</Button>
</div>
</div>
<div class="mx-4 flex min-h-0 flex-1 gap-4 md:mx-8">
<div
ref="periodSwipeTarget"
class="mb-4 flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-xl border border-border-strong md:mb-6"
:class="{ 'max-md:hidden': undatedOpen }"
:aria-busy="isRescheduling || undefined"
data-testid="calendar-grid"
>
<CalendarTimeGrid
v-if="view !== 'month'"
:days="periodDays"
:posts="posts"
:slots="visibleSlots"
:channels="slotChannels"
:timezone="timezone"
:now="now"
:can-create-post="canCreatePost"
@compose="composeAt"
/>
<CalendarMonthGrid
v-else
v-model:expanded-days="expandedDays"
:weeks="calendarWeeks"
:month="monthDate"
:posts="posts"
:slots="visibleSlots"
:channels="slotChannels"
:timezone="timezone"
:now="now"
:can-create-post="canCreatePost"
:is-desktop="isDesktop"
@compose="composeAt"
/>
</div>
<Transition
enter-active-class="transition-[width,margin,opacity] duration-200 ease-out motion-reduce:transition-none"
leave-active-class="transition-[width,margin,opacity] duration-200 ease-out motion-reduce:transition-none"
enter-from-class="opacity-0 md:-ms-4! md:w-0!"
leave-to-class="opacity-0 md:-ms-4! md:w-0!"
>
<div
v-if="undatedOpen"
class="flex min-h-0 shrink-0 overflow-hidden max-md:w-full md:w-[360px]"
data-testid="calendar-undated-slide"
>
<CalendarUndatedPanel
:drafts="undatedDraftList"
@close="closeUndated"
/>
</div>
</Transition>
</div>
</div>
</AppLayout>
<CalendarCustomTimeDialog ref="customTimeDialog" />
<CalendarDragAnnouncer :text="announcement" />
<span :id="DRAG_HINT_ID" hidden data-testid="calendar-drag-hint">{{
$t('calendar.reschedule.drag_hint')
}}</span>
<ConfirmDeleteModal
ref="deleteModal"
:title="$t('posts.edit.delete_modal.title')"
:description="$t('posts.edit.delete_modal.description')"
:action="$t('posts.edit.delete_modal.action')"
:cancel="$t('posts.edit.delete_modal.cancel')"
/>
</template>