ReviewOS

also looking at this

stacks/postline

UI polish, real queue + scheduling, Bluesky threads, live analytics, blog target

#8
Merged glennmichael123 wants to merge feat/ui-polish into main
54 files +2036 -589

Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.

app/Actions/Postline/BlogListAction.tsadded+22-0
Changes to app/Actions/Postline/BlogListAction.ts
@@ -0,0 +1,22 @@
1import { Action } from '@stacksjs/actions'
2import { response } from '@stacksjs/router'
3import { blog } from '../../Services/Social/BlogService'
4
5export default new Action({
6 name: 'Postline Blog List',
7 description: 'List published blog posts.',
8 method: 'GET',
9
10 async handle() {
11 try {
12 const items = await blog.list()
13 return response.json({ ok: true, data: { items } })
14 }
15 catch (error) {
16 return response.json({
17 ok: false,
18 error: error instanceof Error ? error.message : String(error),
19 }, { status: 500 })
20 }
21 },
22})
app/Actions/Postline/ProvidersStatusAction.tsmodified+2-0
Changes to app/Actions/Postline/ProvidersStatusAction.ts
@@ -1,5 +1,6 @@
11import { Action } from '@stacksjs/actions'
22import { response } from '@stacksjs/router'
3import { blog } from '../../Services/Social/BlogService'
34import { bluesky } from '../../Services/Social/BlueskyService'
45import { instagram } from '../../Services/Social/InstagramService'
56import { linkedin } from '../../Services/Social/LinkedInService'
@@ -17,6 +18,7 @@ export default new Action({
1718 linkedin.status(),
1819 instagram.status(),
1920 threads.status(),
21 blog.status(),
2022 ])
2123
2224 return response.json({ ok: true, data: { providers } })
app/Models/BlogPost.tsadded+65-0
Changes to app/Models/BlogPost.ts
@@ -0,0 +1,65 @@
1import { defineModel } from '@stacksjs/orm'
2import { schema } from '@stacksjs/validation'
3
4export default defineModel({
5 name: 'BlogPost',
6 table: 'blog_posts',
7 primaryKey: 'id',
8 autoIncrement: true,
9
10 indexes: [
11 { name: 'blog_posts_status_published_at_index', columns: ['status', 'published_at'] },
12 ],
13
14 traits: {
15 useUuid: true,
16 useTimestamps: true,
17 useApi: {
18 uri: 'blog-posts',
19 routes: ['index', 'show'],
20 },
21 },
22
23 belongsTo: ['Post', 'Account'],
24
25 attributes: {
26 title: {
27 required: true,
28 fillable: true,
29 validation: { rule: schema.string().required().max(200) },
30 factory: faker => faker.lorem.sentence({ min: 3, max: 8 }),
31 },
32 slug: {
33 required: true,
34 fillable: true,
35 unique: true,
36 validation: { rule: schema.string().required().max(220) },
37 factory: faker => faker.lorem.slug(),
38 },
39 body: {
40 required: true,
41 fillable: true,
42 validation: { rule: schema.string().required().min(1) },
43 factory: faker => faker.lorem.paragraphs({ min: 2, max: 5 }),
44 },
45 excerpt: {
46 required: false,
47 fillable: true,
48 validation: { rule: schema.string().max(500).optional() },
49 factory: faker => faker.lorem.sentences(2),
50 },
51 status: {
52 required: true,
53 fillable: true,
54 default: 'draft',
55 validation: { rule: schema.enum(['draft', 'published', 'archived']).required() },
56 factory: () => 'published',
57 },
58 publishedAt: {
59 required: false,
60 fillable: true,
61 validation: { rule: schema.timestamp().optional() },
62 factory: faker => faker.date.recent({ days: 30 }).toISOString().slice(0, 19).replace('T', ' '),
63 },
64 },
65} as const)
app/Models/PostTarget.tsmodified+1-1
Changes to app/Models/PostTarget.ts
@@ -27,7 +27,7 @@ export default defineModel({
2727 provider: {
2828 required: true,
2929 fillable: true,
30 validation: { rule: schema.enum(['bluesky', 'twitter', 'mastodon', 'facebook', 'instagram', 'tiktok', 'linkedin']).required() },
30 validation: { rule: schema.enum(['bluesky', 'twitter', 'mastodon', 'facebook', 'instagram', 'tiktok', 'linkedin', 'threads', 'blog']).required() },
3131 factory: faker => faker.helpers.arrayElement(['bluesky', 'twitter', 'mastodon']),
3232 },
3333 status: {
app/Services/Social/BlogService.tsadded+162-0
Changes to app/Services/Social/BlogService.ts
@@ -0,0 +1,162 @@
1import type { CrosspostTargetResult, PublishContent } from '../../Support/Social/types'
2import { mkdir } from 'node:fs/promises'
3import { join } from 'node:path'
4import process from 'node:process'
5import { db } from '@stacksjs/database'
6import { ensureAccount, now, uuid } from './support'
7
8const database = db as any
9
10// The framework's BunPress blog renders markdown from content/blog/*.md at
11// /blog/<slug> — publishing a file there makes the post immediately live.
12const CONTENT_DIR = join(process.cwd(), 'content/blog')
13
14/** Postline's own blog has no external character ceiling worth enforcing. */
15const BLOG_CHARACTER_LIMIT = 10000
16
17function slugify(value: string): string {
18 return value
19 .toLowerCase()
20 .normalize('NFKD')
21 .replace(/[̀-ͯ]/g, '')
22 .replace(/[^a-z0-9\s-]/g, '')
23 .trim()
24 .replace(/[\s-]+/g, '-')
25 .slice(0, 80)
26 .replace(/^-+|-+$/g, '') || 'post'
27}
28
29async function uniqueSlug(base: string): Promise<string> {
30 let candidate = base
31 for (let attempt = 2; attempt < 50; attempt++) {
32 const existing = await database
33 .selectFrom('blog_posts')
34 .select(['id'])
35 .where('slug', '=', candidate)
36 .executeTakeFirst()
37 if (!existing) return candidate
38 candidate = `${base}-${attempt}`
39 }
40 return `${base}-${uuid().slice(0, 8)}`
41}
42
43/**
44 * The blog is "just another crosspost target": publishing writes a
45 * `blog_posts` row instead of calling an external API. The first line of
46 * the text becomes the title, the rest the body.
47 */
48export class BlogService {
49 async status(): Promise<{ provider: 'blog', handle: string, canPublish: boolean, characterLimit: number, configured: boolean }> {
50 return {
51 provider: 'blog',
52 handle: 'Postline Blog',
53 canPublish: true,
54 characterLimit: BLOG_CHARACTER_LIMIT,
55 configured: true,
56 }
57 }
58
59 async publishToPost(
60 post: { id: number, body: string },
61 _content?: PublishContent,
62 ): Promise<CrosspostTargetResult> {
63 const targetUuid = uuid()
64 const createdAt = now()
65
66 await database.insertInto('post_targets').values({
67 uuid: targetUuid,
68 provider: 'blog',
69 status: 'publishing',
70 post_id: post.id,
71 created_at: createdAt,
72 updated_at: createdAt,
73 }).execute()
74
75 const target = await database
76 .selectFrom('post_targets')
77 .selectAll()
78 .where('uuid', '=', targetUuid)
79 .executeTakeFirstOrThrow()
80
81 try {
82 const lines = post.body.split('\n').map(line => line.trim())
83 const title = (lines.find(Boolean) || 'Untitled post').slice(0, 200)
84 const body = post.body.trim()
85 const slug = await uniqueSlug(slugify(title))
86 const accountId = await ensureAccount()
87 const publishedAt = now()
88
89 // Body minus the title line — the blog theme already renders the title.
90 const firstContentIndex = post.body.split('\n').findIndex(line => line.trim())
91 const markdownBody = post.body.split('\n').slice(firstContentIndex + 1).join('\n').trim() || body
92
93 await mkdir(CONTENT_DIR, { recursive: true })
94 await Bun.write(join(CONTENT_DIR, `${slug}.md`), [
95 '---',
96 `title: ${JSON.stringify(title)}`,
97 `date: ${publishedAt.slice(0, 10)}`,
98 'author: Postline',
99 '---',
100 '',
101 markdownBody,
102 '',
103 ].join('\n'))
104
105 await database.insertInto('blog_posts').values({
106 uuid: uuid(),
107 title,
108 slug,
109 body,
110 excerpt: body.slice(0, 280),
111 status: 'published',
112 published_at: publishedAt,
113 post_id: post.id,
114 account_id: accountId,
115 created_at: publishedAt,
116 updated_at: publishedAt,
117 }).execute()
118
119 const url = `/blog/${slug}`
120 await database.updateTable('post_targets').set({
121 status: 'published',
122 remote_uri: url,
123 failure_reason: null,
124 updated_at: publishedAt,
125 }).where('id', '=', target.id).execute()
126
127 return { provider: 'blog', ok: true, url, uri: url, targetId: Number(target.id) }
128 }
129 catch (error) {
130 const message = error instanceof Error ? error.message : String(error)
131 await database.updateTable('post_targets').set({
132 status: 'failed',
133 failure_reason: message.slice(0, 1000),
134 updated_at: now(),
135 }).where('id', '=', target.id).execute()
136
137 return { provider: 'blog', ok: false, error: message, targetId: Number(target.id) }
138 }
139 }
140
141 /** Published blog posts, newest first. */
142 async list(limit = 50): Promise<Array<{ id: number, title: string, slug: string, excerpt: string | null, body: string, publishedAt: string | null }>> {
143 const rows = await database
144 .selectFrom('blog_posts')
145 .selectAll()
146 .where('status', '=', 'published')
147 .orderBy('published_at', 'desc')
148 .limit(limit)
149 .execute()
150
151 return rows.map((row: any) => ({
152 id: Number(row.id),
153 title: String(row.title),
154 slug: String(row.slug),
155 excerpt: row.excerpt || null,
156 body: String(row.body),
157 publishedAt: row.published_at || null,
158 }))
159 }
160}
161
162export const blog = new BlogService()
app/Services/Social/CrosspostService.tsmodified+2-0
Changes to app/Services/Social/CrosspostService.ts
@@ -1,6 +1,7 @@
11import type { CrosspostTargetResult, PublishContent, SocialProvider } from '../../Support/Social/types'
22import { db } from '@stacksjs/database'
33import { env } from '@stacksjs/env'
4import { blog } from './BlogService'
45import { bluesky } from './BlueskyService'
56import { instagram } from './InstagramService'
67import { linkedin } from './LinkedInService'
@@ -19,6 +20,7 @@ const publishers: Partial<Record<SocialProvider, ProviderPublisher>> = {
1920 linkedin,
2021 instagram,
2122 threads,
23 blog,
2224}
2325
2426export function crosspostProviders(): SocialProvider[] {
app/Support/Social/types.tsmodified+1-0
Changes to app/Support/Social/types.ts
@@ -7,6 +7,7 @@ export type SocialProvider =
77 | 'tiktok'
88 | 'linkedin'
99 | 'threads'
10 | 'blog'
1011
1112export interface SocialIdentityCredentials {
1213 handle: string
components/PostlineSidebar.stxmodified+16-1
Changes to components/PostlineSidebar.stx
@@ -44,6 +44,13 @@ const settingsActive = currentPath === '/settings' || currentPath.startsWith('/s
4444 <span>{{ link.label }}</span>
4545 </a>
4646 @endforeach
47 <a
48 href="/blog"
49 class="inline-flex gap-1.5 items-center shrink-0 px-3 py-1.5 font-medium text-xs text-zinc-600 whitespace-nowrap hover:bg-white/60 rounded-full transition-colors"
50 >
51 <span class="h-4 w-4 i-hugeicons-quill-write-02" aria-hidden="true"></span>
52 <span>Blog</span>
53 </a>
4754 <a
4855 href="/settings"
4956 data-stx-link
@@ -100,6 +107,14 @@ const settingsActive = currentPath === '/settings' || currentPath.startsWith('/s
100107 <span class="grid place-items-center px-1.5 h-5 min-w-5 text-[11px] text-zinc-500 bg-white/72 rounded-full shadow-sm" data-sidebar-expanded>{{ link.shortcut }}</span>
101108 </a>
102109 @endforeach
110 <a
111 href="/blog"
112 class="flex gap-3 items-center px-3 py-1.5 w-full text-[13.5px] text-left text-zinc-700 focus-visible:bg-white/38 hover:bg-white/38 rounded-[14px] focus-visible:outline-none transition-colors"
113 >
114 <span class="h-[18px] w-[18px] text-zinc-600 i-hugeicons-quill-write-02" aria-hidden="true"></span>
115 <span class="flex-1 font-medium truncate" data-sidebar-expanded>Blog</span>
116 <span class="grid place-items-center px-1.5 h-5 min-w-5 text-[11px] text-zinc-500 bg-white/72 rounded-full shadow-sm" data-sidebar-expanded>6</span>
117 </a>
103118 </nav>
104119
105120 <a
@@ -113,7 +128,7 @@ const settingsActive = currentPath === '/settings' || currentPath.startsWith('/s
113128 >
114129 <span class="h-[18px] w-[18px] i-hugeicons-settings-02 {⁠{ settingsActive ? 'text-zinc-900' : 'text-zinc-600' }}" aria-hidden="true"></span>
115130 <span class="flex-1 font-medium" data-sidebar-expanded>Settings</span>
116 <span class="grid place-items-center px-1.5 h-5 min-w-5 text-[11px] text-zinc-500 bg-white/72 rounded-full shadow-sm" data-sidebar-expanded>6</span>
131 <span class="grid place-items-center px-1.5 h-5 min-w-5 text-[11px] text-zinc-500 bg-white/72 rounded-full shadow-sm" data-sidebar-expanded>7</span>
117132 </a>
118133 </aside>
119134 </div>
database/migrations/0000000028-add-threads-blog-to-post_targets-provider.sqladded+23-0
Changes to database/migrations/0000000028-add-threads-blog-to-post_targets-provider.sql
@@ -0,0 +1,23 @@
1-- The provider CHECK constraint predates the Threads driver and the blog
2-- target, so inserts for either provider fail. SQLite can't alter a CHECK
3-- in place — rebuild the table with the widened constraint.
4CREATE TABLE IF NOT EXISTS "post_targets_new" (
5 "id" INTEGER PRIMARY KEY AUTOINCREMENT,
6 "provider" TEXT CHECK ("provider" IN ('bluesky', 'twitter', 'mastodon', 'facebook', 'instagram', 'tiktok', 'linkedin', 'threads', 'blog')),
7 "status" TEXT CHECK ("status" IN ('draft', 'scheduled', 'publishing', 'published', 'failed', 'skipped')) default 'draft',
8 "scheduled_at" TEXT,
9 "remote_uri" TEXT,
10 "remote_cid" TEXT,
11 "failure_reason" TEXT,
12 "metrics" TEXT,
13 "post_id" INTEGER,
14 "social_driver_id" INTEGER,
15 "social_identity_id" INTEGER,
16 "created_at" TEXT not null default CURRENT_TIMESTAMP,
17 "updated_at" TEXT,
18 "uuid" TEXT
19);
20INSERT INTO "post_targets_new" SELECT * FROM "post_targets";
21DROP TABLE "post_targets";
22ALTER TABLE "post_targets_new" RENAME TO "post_targets";
23CREATE INDEX IF NOT EXISTS "post_targets_provider_status_index" ON "post_targets" ("provider", "status");
database/migrations/0000000029-create-blog_posts-table.sqladded+15-0
Changes to database/migrations/0000000029-create-blog_posts-table.sql
@@ -0,0 +1,15 @@
1CREATE TABLE IF NOT EXISTS "blog_posts" (
2 "id" INTEGER PRIMARY KEY AUTOINCREMENT,
3 "title" TEXT not null,
4 "slug" TEXT not null UNIQUE,
5 "body" TEXT not null,
6 "excerpt" TEXT,
7 "status" TEXT CHECK ("status" IN ('draft', 'published', 'archived')) default 'draft',
8 "published_at" TEXT,
9 "post_id" INTEGER,
10 "account_id" INTEGER,
11 "created_at" TEXT not null default CURRENT_TIMESTAMP,
12 "updated_at" TEXT,
13 "uuid" TEXT
14);
15CREATE INDEX IF NOT EXISTS "blog_posts_status_published_at_index" ON "blog_posts" ("status", "published_at");
resources/assets/scripts/postline-social.tsmodified+1-0
Changes to resources/assets/scripts/postline-social.ts
@@ -37,6 +37,7 @@ const PROVIDER_LABELS: Record<string, string> = {
3737 instagram: 'Instagram',
3838 threads: 'Threads',
3939 tiktok: 'TikTok',
40 blog: 'Blog',
4041}
4142
4243export function providerLabel(provider: string): string {
resources/views/layouts/postline.stxmodified+1-1
Changes to resources/views/layouts/postline.stx
@@ -316,7 +316,7 @@
316316
317317 // Number keys 1-6 jump between pages (the sidebar shows the badges).
318318 const bindKeyboardShortcuts = () => {
319 const routes = { 1: '/', 2: '/queue', 3: '/timeline', 4: '/analytics', 5: '/accounts', 6: '/settings' }
319 const routes = { 1: '/', 2: '/queue', 3: '/timeline', 4: '/analytics', 5: '/accounts', 6: '/blog', 7: '/settings' }
320320 document.addEventListener('keydown', (event) => {
321321 if (event.metaKey || event.ctrlKey || event.altKey) return
322322 const target = event.target
resources/views/queue.stxmodified+5-3
Changes to resources/views/queue.stx
@@ -79,8 +79,10 @@
7979 return date.toLocaleString(undefined, { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })
8080 }
8181
82 const bskyUrl = (uri) => {
83 const match = String(uri || '').match(/^at:\/\/([^/]+)\/app\.bsky\.feed\.post\/(.+)$/)
82 const liveUrlFor = (uri) => {
83 const value = String(uri || '')
84 if (value.startsWith('/')) return value
85 const match = value.match(/^at:\/\/([^/]+)\/app\.bsky\.feed\.post\/(.+)$/)
8486 return match ? `https://bsky.app/profile/${encodeURIComponent(match[1])}/post/${encodeURIComponent(match[2])}` : null
8587 }
8688
@@ -93,7 +95,7 @@
9395 const channels = item.providers.map(target => providerLabel(target.provider)).join(', ') || '—'
9496 const failure = item.providers.find(target => target.failureReason)?.failureReason
9597 const liveUri = item.providers.find(target => target.remoteUri)?.remoteUri
96 const liveUrl = bskyUrl(liveUri)
98 const liveUrl = liveUrlFor(liveUri)
9799 const actionable = ['draft', 'scheduled', 'failed'].includes(item.status)
98100
99101 return `
routes/api.tsmodified+1-0
Changes to routes/api.ts
@@ -49,6 +49,7 @@ route.group({ prefix: '/postline' }, () => {
4949 route.get('/providers', 'Actions/Postline/ProvidersStatusAction').skipCsrf()
5050 route.post('/publish', 'Actions/Postline/CrosspostPublishAction').skipCsrf()
5151 route.get('/analytics', 'Actions/Postline/AnalyticsAction').skipCsrf()
52 route.get('/blog', 'Actions/Postline/BlogListAction').skipCsrf()
5253 route.get('/queue', 'Actions/Postline/QueueListAction').skipCsrf()
5354 route.post('/queue', 'Actions/Postline/QueueSaveAction').skipCsrf()
5455 route.post('/queue/delete', 'Actions/Postline/QueueDeleteAction').skipCsrf()