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 {
VisAxis,
VisAxisSelectors,
VisLine,
VisLineSelectors,
VisScatter,
VisScatterSelectors,
VisXYContainer,
} from '@unovis/vue';
import { computed, ref, useTemplateRef } from 'vue';
import LineEndLabel from '@/components/analytics/workspace/charts/LineEndLabel.vue';
import {
formatCountTick,
socialAccountChartConfig,
} from '@/components/analytics/workspace/charts/socialAccountChart';
import {
ChartContainer,
ChartCrosshair,
ChartTooltip,
ChartTooltipContent,
componentToString,
numericTick,
} from '@/components/ui/chart';
import { useChartAppContext } from '@/composables/analytics/useChartAppContext';
import { useBelowBreakpoint } from '@/composables/useBreakpoint';
import { useCanHover } from '@/composables/useCanHover';
import date from '@/date';
import { accountColor } from '@/lib/analyticsColors';
import { spreadLabels } from '@/lib/labelLayout';
import { formatNumberCompact } from '@/lib/utils';
import type {
FollowerAccount,
WorkspaceAnalyticsReport,
} from '@/types/analytics';
type ChartPoint = {
date: string;
index: number;
[key: string]: string | number | undefined;
};
const props = defineProps<{
accounts: FollowerAccount[];
series: WorkspaceAnalyticsReport['followers']['series'];
colors: Record<string, string>;
}>();
const chartData = computed<ChartPoint[]>(() => {
const lastKnown: (number | undefined)[] = [];
return props.series.map((point, index) => {
const values: ChartPoint = { date: point.date, index };
props.accounts.forEach((account, accountIndex) => {
lastKnown[accountIndex] =
point.accounts[account.social_account_key] ??
lastKnown[accountIndex];
values[`account_${accountIndex}`] = lastKnown[accountIndex];
});
return values;
});
});
const chartConfig = computed(() =>
socialAccountChartConfig(props.accounts, props.colors),
);
const xAccessor = (point: ChartPoint): number => point.index;
const valueAccessor =
(index: number) =>
(point: ChartPoint): number | undefined => {
const value = point[`account_${index}`];
return typeof value === 'number' ? value : undefined;
};
/** One accessor per channel, kept while the channels stay, so unovis never sees a new line to redraw. */
const valueAccessors = computed(() =>
props.accounts.map((_, index) => valueAccessor(index)),
);
const formatDate = numericTick((tick): string => {
const day = chartData.value[Math.round(tick)]?.date;
if (!day) {
return '';
}
return date.formatMonthDay(day);
});
const appContext = useChartAppContext();
const tooltipTemplate = computed(() =>
componentToString(
chartConfig.value,
ChartTooltipContent,
{ labelFormatter: formatDate },
appContext,
),
);
const lineColor = (index: number): string =>
props.colors[props.accounts[index]?.social_account_key ?? ''] ??
accountColor(index);
/** Room on the right for each line's avatar and latest number; narrower on a phone. */
const belowSm = useBelowBreakpoint('sm');
const RAIL_WIDTH = { phone: 92, wide: 112 };
const railWidth = computed((): number => {
if (belowSm.value) {
return RAIL_WIDTH.phone;
}
return RAIL_WIDTH.wide;
});
/** Room over the plot for the top line-end label, and under it for the dates. */
const PLOT_PADDING = { top: 16, bottom: 8 };
const chartPadding = computed(() => ({
top: PLOT_PADDING.top,
right: railWidth.value,
bottom: PLOT_PADDING.bottom,
left: 0,
}));
/** From the end of a line to its label, where a leader runs when the label had to move. */
const LEADER_LENGTH = 32;
/** Where a leader starts after the line's end, how far it stops short of the avatar, and the offset from which a label gets one. */
const LEADER = { inset: 4, tip: 2, from: 1 };
/** The tallest a label is; labels closer than this are spread apart. */
const LABEL_HEIGHT = 24;
type LineEnd = {
account: FollowerAccount;
index: number;
value: string;
/** Where the line ends and where its label sits, in the frame's pixels. */
lineY: number;
labelY: number;
};
const frame = useTemplateRef<HTMLDivElement>('frame');
const lineEnds = ref<LineEnd[]>([]);
const lineEndX = ref(0);
/** The line whose label the pointer is on; the others fade. */
const focusedLine = ref<number | null>(null);
const canHover = useCanHover();
/** Fades the other lines while a label is pointed at; a tap on a touch screen never leaves, so it fades nothing. */
const focusLine = (index: number): void => {
if (!canHover.value) {
return;
}
focusedLine.value = index;
};
const clearFocus = (): void => {
focusedLine.value = null;
};
/** Whether a line fades while another channel's label is pointed at. */
const isDimmed = (index: number): boolean =>
focusedLine.value !== null && focusedLine.value !== index;
/** The attributes unovis sets on a component's elements, by selector. */
type ChartAttributes = Record<string, Record<string, string>>;
const lineAttributes = (index: number): ChartAttributes => ({
[VisLineSelectors.line]: { 'data-dimmed': String(isDimmed(index)) },
});
const pointAttributes = (index: number): ChartAttributes => ({
[VisScatterSelectors.point]: { 'data-dimmed': String(isDimmed(index)) },
});
const valueTickAttributes = {
[VisAxisSelectors.tick]: {
'data-value-tick': (tick: number): string => String(tick),
},
};
/** Each channel's latest known count, the value its line ends on. */
const latestValue = (index: number): number | undefined => {
const latest = chartData.value[chartData.value.length - 1];
if (!latest) {
return undefined;
}
return valueAccessor(index)(latest);
};
/** Maps a count to its height in the frame, read off two of the value axis' ticks. */
const valueToY = (
svg: SVGSVGElement,
top: number,
): ((value: number) => number) | null => {
const ticks = [...svg.querySelectorAll<SVGGElement>('g[data-value-tick]')]
.map((tick) => ({
value: Number(tick.getAttribute('data-value-tick')),
y: tick.getCTM()?.f,
}))
.filter((tick): tick is { value: number; y: number } => tick.y !== undefined);
const [low, high] = [ticks[0], ticks[ticks.length - 1]];
if (!low || !high || low.value === high.value) {
return null;
}
return (value) => top + low.y + ((value - low.value) * (high.y - low.y)) / (high.value - low.value);
};
const placeLineEnds = (svg: SVGSVGElement): void => {
const box = frame.value?.getBoundingClientRect();
if (!box) {
return;
}
const svgBox = svg.getBoundingClientRect();
const top = svgBox.top - box.top;
const toY = valueToY(svg, top);
if (!toY) {
lineEnds.value = [];
return;
}
lineEndX.value = svgBox.left - box.left + svgBox.width - railWidth.value;
const ends = props.accounts.flatMap((account, index) => {
const value = latestValue(index);
if (value === undefined) {
return [];
}
return [{ account, index, value: formatNumberCompact(value), lineY: toY(value), labelY: 0 }];
});
const labels = spreadLabels(
ends.map((end) => end.lineY),
{ gap: LABEL_HEIGHT, top, bottom: Math.min(toY(0), top + svgBox.height) },
);
const placed = ends.map((end, position) => ({ ...end, labelY: labels[position] }));
if (!sameLineEnds(placed, lineEnds.value)) {
lineEnds.value = placed;
}
};
/** Whether two placements put the same labels in the same places, so an unchanged render does not redraw every line. */
const sameLineEnds = (next: LineEnd[], current: LineEnd[]): boolean =>
next.length === current.length &&
next.every(
(end, position) =>
end.index === current[position].index &&
end.value === current[position].value &&
end.lineY === current[position].lineY &&
end.labelY === current[position].labelY,
);
/** A leader's three points: out from the line's end, along it, then up or down to its label. */
const leaderPoints = (end: LineEnd): string => {
const start = lineEndX.value + LEADER.inset;
const bend = lineEndX.value + LEADER_LENGTH / 2;
const tip = lineEndX.value + LEADER_LENGTH - LEADER.tip;
return `${start},${end.lineY} ${bend},${end.lineY} ${tip},${end.labelY}`;
};
/** A leader only where a label had to move away from its line. */
const movedEnds = computed(() =>
lineEnds.value.filter((end) => Math.abs(end.labelY - end.lineY) > LEADER.from),
);
const crosshairColor = (_point: ChartPoint, index: number): string =>
lineColor(Math.floor(index / 2));
</script>
<template>
<div
ref="frame"
class="relative"
role="img"
:aria-label="$t('analytics.dashboard.followers_line_description')"
>
<ChartContainer
:config="chartConfig"
cursor
class="h-72 w-full sm:h-80 [&_[data-dimmed=true]]:opacity-20 [&_[data-dimmed]]:transition-opacity"
data-testid="followers-unovis-chart"
>
<VisXYContainer
:data="chartData"
:padding="chartPadding"
:on-render-complete="placeLineEnds"
>
<template
v-for="(account, index) in accounts"
:key="account.social_account_key"
>
<VisLine
:x="xAccessor"
:y="valueAccessors[index]"
:color="lineColor(index)"
:line-width="2"
curve-type="monotoneX"
:attributes="lineAttributes(index)"
/>
<VisScatter
:x="xAccessor"
:y="valueAccessors[index]"
:color="lineColor(index)"
:size="4"
:attributes="pointAttributes(index)"
/>
</template>
<VisAxis
type="x"
:tick-format="formatDate"
:num-ticks="Math.min(chartData.length, 6)"
:grid-line="false"
:domain-line="false"
:tick-line="false"
/>
<VisAxis
type="y"
:tick-format="formatCountTick"
:num-ticks="5"
:grid-line="true"
:domain-line="false"
:tick-line="false"
:duration="0"
:attributes="valueTickAttributes"
/>
<ChartCrosshair
:template="tooltipTemplate"
:color="crosshairColor"
:circleRadius="5"
strokeColor="var(--card)"
:strokeWidth="2"
/>
<ChartTooltip />
</VisXYContainer>
</ChartContainer>
<svg
class="pointer-events-none absolute inset-0 size-full overflow-visible"
aria-hidden="true"
>
<polyline
v-for="end in movedEnds"
:key="end.account.social_account_key"
:points="leaderPoints(end)"
fill="none"
:stroke="lineColor(end.index)"
stroke-width="1.5"
stroke-linejoin="round"
class="transition-opacity data-[dimmed=true]:opacity-20"
:data-dimmed="isDimmed(end.index)"
/>
</svg>
<div
v-for="end in lineEnds"
:key="end.account.social_account_key"
class="absolute z-10 -translate-y-1/2"
:style="{ left: `${lineEndX + LEADER_LENGTH}px`, top: `${end.labelY}px` }"
data-testid="followers-line-end"
:data-account="end.account.social_account_key"
@mouseenter="focusLine(end.index)"
@mouseleave="clearFocus"
>
<LineEndLabel :account="end.account" :value="end.value" />
</div>
</div>
</template>