feat: add labels and hashtags to posts

- Add many-to-many relationship between posts and workspace labels
- Add label selector in post edit page with autosave
- Display labels in posts list
- Add hashtags modal with search for appending hashtags to post content
- Fix sidebar active state for posts edit page
- Fix AvatarImage null src warning in SocialAccountsGrid
- Fix new post state by using Inertia::location for full page reload
- Hide close button on CommandDialog by default
This commit is contained in:
Paulo Castellano 2026-01-26 15:18:35 -03:00
parent 6fc9defb89
commit c0886737c4
15 changed files with 423 additions and 18 deletions

View file

@ -30,7 +30,7 @@ public function index(Request $request, ?string $status = null): Response|Redire
$query = $workspace->posts()
->with(['postPlatforms' => function ($query) {
$query->where('enabled', true)->with('socialAccount');
}, 'user']);
}, 'user', 'labels']);
// Apply status filter if provided
if ($status) {
@ -97,7 +97,7 @@ public function calendar(Request $request): Response|RedirectResponse
]);
}
public function store(Request $request): RedirectResponse
public function store(Request $request): RedirectResponse|\Symfony\Component\HttpFoundation\Response
{
$workspace = $request->user()->currentWorkspace;
@ -141,7 +141,7 @@ public function store(Request $request): RedirectResponse
]);
}
return redirect()->route('posts.edit', $post);
return Inertia::location(route('posts.edit', $post));
}
public function edit(Request $request, Post $post): Response|RedirectResponse
@ -158,8 +158,10 @@ public function edit(Request $request, Post $post): Response|RedirectResponse
abort(404);
}
$post->load(['postPlatforms.socialAccount', 'postPlatforms.media']);
$post->load(['postPlatforms.socialAccount', 'postPlatforms.media', 'labels']);
$socialAccounts = $workspace->socialAccounts;
$labels = $workspace->labels;
$hashtags = $workspace->hashtags;
$platformConfigs = $socialAccounts->mapWithKeys(function ($account) {
$platform = $account->platform;
@ -191,6 +193,8 @@ public function edit(Request $request, Post $post): Response|RedirectResponse
'socialAccounts' => $socialAccounts,
'platformConfigs' => $platformConfigs,
'pinterestBoards' => $pinterestBoards,
'labels' => $labels,
'hashtags' => $hashtags,
]);
}
@ -228,6 +232,11 @@ public function update(UpdatePostRequest $request, Post $post): RedirectResponse
'scheduled_at' => $scheduledAt,
]);
// Sync labels
if ($request->has('label_ids')) {
$post->labels()->sync($request->input('label_ids', []));
}
// Get selected platform IDs
$selectedPlatformIds = collect($request->input('platforms', []))->pluck('id')->toArray();

View file

@ -19,6 +19,8 @@ public function rules(): array
'platforms' => ['sometimes', 'array'],
'platforms.*.id' => ['required', 'uuid', 'exists:post_platforms,id'],
'platforms.*.content' => ['nullable', 'string', 'max:5000'],
'label_ids' => ['sometimes', 'array'],
'label_ids.*' => ['uuid', 'exists:workspace_labels,id'],
];
}

View file

@ -8,6 +8,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Post extends Model
@ -49,6 +50,11 @@ public function postPlatforms(): HasMany
return $this->hasMany(PostPlatform::class);
}
public function labels(): BelongsToMany
{
return $this->belongsToMany(WorkspaceLabel::class);
}
public function scopeScheduled(Builder $query): Builder
{
return $query->where('status', PostStatus::Scheduled);

View file

@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class WorkspaceLabel extends Model
@ -23,4 +24,9 @@ public function workspace(): BelongsTo
{
return $this->belongsTo(Workspace::class);
}
public function posts(): BelongsToMany
{
return $this->belongsToMany(Post::class);
}
}

View file

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('post_workspace_label', function (Blueprint $table) {
$table->foreignUuid('post_id')->constrained()->cascadeOnDelete();
$table->foreignUuid('workspace_label_id')->constrained()->cascadeOnDelete();
$table->primary(['post_id', 'workspace_label_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('post_workspace_label');
}
};

View file

@ -56,6 +56,7 @@
'view_title' => 'View Post',
'manage_platforms' => 'Manage platforms',
'sync' => 'Sync',
'labels' => 'Labels',
'schedule' => 'Schedule',
'publish' => 'Publish',
'saving' => 'Saving...',
@ -99,6 +100,11 @@
'description' => 'Choose which platforms to publish this post to.',
],
'hashtags_modal' => [
'search' => 'Search hashtags...',
'no_results' => 'No hashtags found.',
],
'validation' => [
'select_board' => 'Select a board',
'images_not_supported' => 'Images not supported',

View file

@ -56,6 +56,7 @@
'view_title' => 'Visualizar Post',
'manage_platforms' => 'Gerenciar plataformas',
'sync' => 'Sincronizar',
'labels' => 'Etiquetas',
'schedule' => 'Agendar',
'publish' => 'Publicar',
'saving' => 'Salvando...',
@ -99,6 +100,11 @@
'description' => 'Escolha em quais plataformas publicar este post.',
],
'hashtags_modal' => [
'search' => 'Buscar hashtags...',
'no_results' => 'Nenhuma hashtag encontrada.',
],
'validation' => [
'select_board' => 'Selecione uma pasta',
'images_not_supported' => 'Imagens não suportadas',

View file

@ -194,6 +194,10 @@ function createWorkspace() {
}
function isActive(href: string): boolean {
// For /posts, also match /posts/{id}/edit
if (href === '/posts') {
return page.url === '/posts' || page.url.startsWith('/posts/') && page.url.includes('/edit');
}
// Exact match or match with query string
return page.url === href || page.url.startsWith(href + '?');
}

View file

@ -183,7 +183,7 @@ const isDisconnected = (account: SocialAccount | null): boolean => {
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<Avatar class="h-8 w-8">
<AvatarImage :src="platform.account.avatar_url" />
<AvatarImage v-if="platform.account.avatar_url" :src="platform.account.avatar_url" />
<AvatarFallback class="text-xs">
{{ platform.account.display_name?.charAt(0) }}
</AvatarFallback>

View file

@ -0,0 +1,67 @@
<script setup lang="ts">
import { ref } from 'vue';
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command';
interface Hashtag {
id: string;
name: string;
hashtags: string;
}
defineProps<{
hashtags: Hashtag[];
}>();
const emit = defineEmits<{
(e: 'select', hashtag: Hashtag): void;
}>();
const isOpen = ref(false);
const handleSelect = (hashtag: Hashtag) => {
emit('select', hashtag);
isOpen.value = false;
};
const open = () => {
isOpen.value = true;
};
const close = () => {
isOpen.value = false;
};
defineExpose({
open,
close,
});
</script>
<template>
<CommandDialog v-model:open="isOpen">
<CommandInput :placeholder="$t('posts.edit.hashtags_modal.search')" />
<CommandList>
<CommandEmpty>
{{ $t('posts.edit.hashtags_modal.no_results') }}
</CommandEmpty>
<CommandGroup>
<CommandItem v-for="hashtag in hashtags" :key="hashtag.id" :value="hashtag.name"
class="flex flex-col items-start gap-1 py-3" @select="handleSelect(hashtag)">
<div class="font-medium text-sm">
{{ hashtag.name }}
</div>
<p class="text-xs line-clamp-2 w-full">
{{ hashtag.hashtags }}
</p>
</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
</template>

View file

@ -7,9 +7,11 @@ import Command from "./Command.vue"
const props = withDefaults(defineProps<DialogRootProps & {
title?: string
description?: string
showCloseButton?: boolean
}>(), {
title: "Command Palette",
description: "Search for a command to run...",
showCloseButton: false,
})
const emits = defineEmits<DialogRootEmits>()
@ -18,7 +20,7 @@ const forwarded = useForwardPropsEmits(props, emits)
<template>
<Dialog v-slot="slotProps" v-bind="forwarded">
<DialogContent class="overflow-hidden p-0 ">
<DialogContent class="overflow-hidden p-0" :show-close-button="showCloseButton">
<DialogHeader class="sr-only">
<DialogTitle>{{ title }}</DialogTitle>
<DialogDescription>{{ description }}</DialogDescription>

View file

@ -12,10 +12,15 @@ const currentUrlReactive = computed(
export function useActiveUrl() {
function urlIsActive(
urlToCheck: NonNullable<InertiaLinkProps['href']>,
currentUrl?: string,
options?: { prefix?: boolean },
) {
const urlToCompare = currentUrl ?? currentUrlReactive.value;
return toUrl(urlToCheck) === urlToCompare;
const targetUrl = toUrl(urlToCheck);
if (options?.prefix) {
return currentUrlReactive.value.startsWith(targetUrl);
}
return targetUrl === currentUrlReactive.value;
}
return {

View file

@ -22,6 +22,8 @@ import {
IconCircleCheck,
IconExternalLink,
IconLoader2,
IconTag,
IconHash,
} from '@tabler/icons-vue';
import { trans } from 'laravel-vue-i18n';
import { computed, onUnmounted, ref, watch, type Component } from 'vue';
@ -31,6 +33,7 @@ import { computed, onUnmounted, ref, watch, type Component } from 'vue';
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';
import DatePicker from '@/components/DatePicker.vue';
import PhoneMockup from '@/components/PhoneMockup.vue';
import HashtagsModal from '@/components/posts/HashtagsModal.vue';
import PostForm from '@/components/posts/PostForm.vue';
import { PlatformPreview } from '@/components/posts/previews';
import { Alert, AlertDescription } from '@/components/ui/alert';
@ -46,6 +49,7 @@ import {
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
Dialog,
DialogContent,
@ -54,6 +58,7 @@ import {
DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Switch } from '@/components/ui/switch';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { useMediaManager, type MediaItem } from '@/composables/useMediaManager';
@ -93,6 +98,18 @@ interface PinterestBoard {
name: string;
}
interface WorkspaceLabel {
id: string;
name: string;
color: string;
}
interface WorkspaceHashtag {
id: string;
name: string;
hashtags: string;
}
interface ContentTypeOption {
value: string;
label: string;
@ -106,6 +123,7 @@ interface Post {
scheduled_at: string | null;
published_at: string | null;
post_platforms: PostPlatform[];
labels: WorkspaceLabel[];
}
interface PlatformConfig {
@ -127,6 +145,8 @@ interface Props {
socialAccounts: SocialAccount[];
platformConfigs: Record<string, PlatformConfig>;
pinterestBoards: PinterestBoard[];
labels: WorkspaceLabel[];
hashtags: WorkspaceHashtag[];
}
const props = defineProps<Props>();
@ -202,7 +222,9 @@ const isAnyUploading = computed(() => Object.values(isUploading.value).some(v =>
const isSubmitting = ref(false);
const isSaving = ref(false);
const showSaved = ref(false);
const selectedLabelIds = ref<string[]>(post.value.labels?.map(l => l.id) || []);
const deleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
const hashtagsModal = ref<InstanceType<typeof HashtagsModal> | null>(null);
const showEnableSyncDialog = ref(false);
const showDisableSyncDialog = ref(false);
const showPlatformsDialog = ref(false);
@ -367,13 +389,13 @@ const getSubmitData = () => {
meta: platformMeta.value[pp.id] || {},
}));
return { platforms, scheduled_at: scheduledDateTime.value || null };
return { platforms, scheduled_at: scheduledDateTime.value || null, label_ids: selectedLabelIds.value };
};
const save = () => {
if (isSubmitting.value || isReadOnly.value || isSaving.value) return;
const { platforms, scheduled_at } = getSubmitData();
const { platforms, scheduled_at, label_ids } = getSubmitData();
isSaving.value = true;
showSaved.value = false;
@ -383,6 +405,7 @@ const save = () => {
synced: synced.value,
scheduled_at,
platforms,
label_ids,
}, {
preserveScroll: true,
onFinish: () => {
@ -409,7 +432,7 @@ const triggerAutosave = () => {
};
// Watch other form data for autosave
watch([selectedPlatformIds, synced, scheduledDateTime], triggerAutosave, { deep: true });
watch([selectedPlatformIds, synced, scheduledDateTime, selectedLabelIds], triggerAutosave, { deep: true });
// Cleanup on unmount
onUnmounted(() => {
@ -607,7 +630,7 @@ const submit = (status: string = 'scheduled') => {
// Cancel any pending autosave
debouncedSave.cancel();
const { platforms, scheduled_at } = getSubmitData();
const { platforms, scheduled_at, label_ids } = getSubmitData();
isSubmitting.value = true;
@ -616,6 +639,7 @@ const submit = (status: string = 'scheduled') => {
synced: synced.value,
scheduled_at,
platforms,
label_ids,
}, {
onFinish: () => {
isSubmitting.value = false;
@ -630,6 +654,29 @@ const deletePost = () => {
redirect: 'posts.index',
});
};
const toggleLabel = (labelId: string) => {
const index = selectedLabelIds.value.indexOf(labelId);
if (index === -1) {
selectedLabelIds.value.push(labelId);
} else {
selectedLabelIds.value.splice(index, 1);
}
};
const selectedLabels = computed(() => {
return props.labels.filter(l => selectedLabelIds.value.includes(l.id));
});
const appendHashtags = (hashtag: WorkspaceHashtag) => {
if (isReadOnly.value || !activePlatform.value) return;
const currentContent = getContent(activePlatform.value.id);
const separator = currentContent.trim() ? '\n\n' : '';
const newContent = currentContent + separator + hashtag.hashtags;
setContent(activePlatform.value.id, newContent);
};
</script>
<template>
@ -712,6 +759,35 @@ const deletePost = () => {
<!-- Schedule & Actions (only in edit mode) -->
<div v-if="!isReadOnly" class="flex items-center gap-3">
<!-- Labels Selector -->
<Popover v-if="labels.length > 0">
<PopoverTrigger asChild>
<Button type="button" variant="outline" size="sm" class="gap-2">
<IconTag class="h-4 w-4" />
<span v-if="selectedLabels.length === 0">{{ $t('posts.edit.labels') }}</span>
<span v-else>{{ selectedLabels.length }}</span>
</Button>
</PopoverTrigger>
<PopoverContent class="w-56 p-2" align="end">
<div>
<div v-for="label in labels" :key="label.id"
class="flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted cursor-pointer"
@click="toggleLabel(label.id)">
<Checkbox :model-value="selectedLabelIds.includes(label.id)" />
<span class="h-3 w-3 rounded-full shrink-0"
:style="{ backgroundColor: label.color }" />
<span class="text-sm truncate">{{ label.name }}</span>
</div>
</div>
</PopoverContent>
</Popover>
<!-- Hashtags Selector -->
<Button v-if="hashtags.length > 0" type="button" variant="outline" size="icon-sm"
@click="hashtagsModal?.open()">
<IconHash class="h-4 w-4" />
</Button>
<!-- DateTime Picker -->
<div class="flex items-center gap-2">
<DatePicker name="scheduled_datetime" v-model="scheduledDateTime" :show-time="true" />
@ -898,6 +974,8 @@ const deletePost = () => {
:description="$t('posts.edit.delete_modal.description')" :action="$t('posts.edit.delete_modal.action')"
:cancel="$t('posts.edit.delete_modal.cancel')" />
<HashtagsModal ref="hashtagsModal" :hashtags="hashtags" @select="appendHashtags" />
<!-- Enable Sync Confirmation Dialog -->
<AlertDialog :open="showEnableSyncDialog" @update:open="showEnableSyncDialog = $event">
<AlertDialogContent>

View file

@ -38,6 +38,12 @@ interface User {
name: string;
}
interface Label {
id: string;
name: string;
color: string;
}
interface Post {
id: string;
status: string;
@ -45,6 +51,7 @@ interface Post {
published_at: string | null;
post_platforms: PostPlatform[];
user: User;
labels: Label[];
}
interface ScrollPosts {
@ -198,11 +205,23 @@ const handleDelete = (post: Post) => {
<Card v-for="post in posts.data" :key="post.id" class="flex flex-col py-0">
<CardContent class="p-4 flex-1 flex flex-col">
<div class="flex items-center justify-between gap-2 mb-3">
<Badge :class="getStatusConfig(post.status).color">
<component :is="getStatusConfig(post.status).icon" class="mr-1 h-3 w-3" />
{{ getStatusConfig(post.status).label }}
</Badge>
<span class="text-xs text-muted-foreground">
<div class="flex items-center gap-2 flex-wrap">
<Badge :class="getStatusConfig(post.status).color">
<component :is="getStatusConfig(post.status).icon" class="mr-1 h-3 w-3" />
{{ getStatusConfig(post.status).label }}
</Badge>
<div v-if="post.labels?.length" class="flex items-center gap-1">
<span v-for="label in post.labels.slice(0, 2)" :key="label.id"
class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium"
:style="{ backgroundColor: label.color + '20', color: label.color }">
{{ label.name }}
</span>
<span v-if="post.labels.length > 2" class="text-xs text-muted-foreground">
+{{ post.labels.length - 2 }}
</span>
</div>
</div>
<span class="text-xs text-muted-foreground shrink-0">
{{ formatDateTime(post.scheduled_at) }}
</span>
</div>

View file

@ -9,6 +9,7 @@
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
beforeEach(function () {
$this->user = User::factory()->create(['setup' => Setup::Completed]);
@ -293,3 +294,169 @@
$response->assertNotFound();
});
// Label tests
test('edit post includes workspace labels', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
]);
$label = WorkspaceLabel::factory()->create([
'workspace_id' => $this->workspace->id,
'name' => 'Marketing',
'color' => '#FF0000',
]);
$response = $this->actingAs($this->user)->get(route('posts.edit', $post));
$response->assertOk();
$response->assertInertia(fn ($page) => $page
->component('posts/Edit')
->has('labels', 1)
->where('labels.0.name', 'Marketing')
);
});
test('update post can attach labels', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
$postPlatform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
]);
$label = WorkspaceLabel::factory()->create([
'workspace_id' => $this->workspace->id,
]);
$response = $this->actingAs($this->user)->put(route('posts.update', $post), [
'status' => 'draft',
'platforms' => [
[
'id' => $postPlatform->id,
'content' => 'Test content',
'content_type' => ContentType::LinkedInPost->value,
],
],
'label_ids' => [$label->id],
]);
$response->assertRedirect();
$post->refresh();
expect($post->labels)->toHaveCount(1);
expect($post->labels->first()->id)->toBe($label->id);
});
test('update post can detach labels', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
$postPlatform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
]);
$label = WorkspaceLabel::factory()->create([
'workspace_id' => $this->workspace->id,
]);
$post->labels()->attach($label);
$response = $this->actingAs($this->user)->put(route('posts.update', $post), [
'status' => 'draft',
'platforms' => [
[
'id' => $postPlatform->id,
'content' => 'Test content',
'content_type' => ContentType::LinkedInPost->value,
],
],
'label_ids' => [],
]);
$response->assertRedirect();
$post->refresh();
expect($post->labels)->toHaveCount(0);
});
test('update post can sync multiple labels', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
$postPlatform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
]);
$label1 = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
$label2 = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
$label3 = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
// Attach initial label
$post->labels()->attach($label1);
// Update with different labels
$response = $this->actingAs($this->user)->put(route('posts.update', $post), [
'status' => 'draft',
'platforms' => [
[
'id' => $postPlatform->id,
'content' => 'Test content',
'content_type' => ContentType::LinkedInPost->value,
],
],
'label_ids' => [$label2->id, $label3->id],
]);
$response->assertRedirect();
$post->refresh();
expect($post->labels)->toHaveCount(2);
expect($post->labels->pluck('id')->toArray())->toEqualCanonicalizing([$label2->id, $label3->id]);
});
test('update post validates label_ids exist', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
$postPlatform = PostPlatform::factory()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
]);
$response = $this->actingAs($this->user)->put(route('posts.update', $post), [
'status' => 'draft',
'platforms' => [
[
'id' => $postPlatform->id,
'content' => 'Test content',
'content_type' => ContentType::LinkedInPost->value,
],
],
'label_ids' => ['non-existent-uuid'],
]);
$response->assertSessionHasErrors('label_ids.0');
});