feat: add thread drafts, shareable permalinks & Twitter card previews
Thread builder now persists drafts to disk (JSON files in /data/files/threads/), supports shareable permalink URLs with OG/Twitter meta tags, and generates AI preview images via fal.ai for social card previews. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
763567baea
commit
997ccc0bef
|
|
@ -5,6 +5,8 @@
|
||||||
* Supports ActivityPub, RSS, and manual link sharing.
|
* Supports ActivityPub, RSS, and manual link sharing.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
import { mkdir, readdir, readFile, writeFile, unlink } from "node:fs/promises";
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { renderShell, renderExternalAppShell, escapeHtml } from "../../server/shell";
|
import { renderShell, renderExternalAppShell, escapeHtml } from "../../server/shell";
|
||||||
import { getModuleInfoList } from "../../shared/module";
|
import { getModuleInfoList } from "../../shared/module";
|
||||||
|
|
@ -14,6 +16,71 @@ import { MYCOFI_CAMPAIGN, PLATFORM_ICONS, PLATFORM_COLORS } from "./campaign-dat
|
||||||
|
|
||||||
const routes = new Hono();
|
const routes = new Hono();
|
||||||
|
|
||||||
|
// ── Thread storage helpers ──
|
||||||
|
const THREADS_BASE = resolve(process.env.FILES_DIR || "./data/files", "threads");
|
||||||
|
|
||||||
|
interface ThreadData {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
handle: string;
|
||||||
|
title: string;
|
||||||
|
tweets: string[];
|
||||||
|
imageUrl?: string;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateThreadId(): string {
|
||||||
|
const random = Math.random().toString(36).substring(2, 8);
|
||||||
|
return `t-${Date.now()}-${random}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureThreadsDir(): Promise<string> {
|
||||||
|
await mkdir(THREADS_BASE, { recursive: true });
|
||||||
|
return THREADS_BASE;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadThread(id: string): Promise<ThreadData | null> {
|
||||||
|
try {
|
||||||
|
const dir = await ensureThreadsDir();
|
||||||
|
const raw = await readFile(resolve(dir, `${id}.json`), "utf-8");
|
||||||
|
return JSON.parse(raw);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveThread(data: ThreadData): Promise<void> {
|
||||||
|
const dir = await ensureThreadsDir();
|
||||||
|
await writeFile(resolve(dir, `${data.id}.json`), JSON.stringify(data, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteThreadFile(id: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const dir = await ensureThreadsDir();
|
||||||
|
await unlink(resolve(dir, `${id}.json`));
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listThreads(): Promise<Array<{ id: string; title: string; tweetCount: number; updatedAt: number }>> {
|
||||||
|
const dir = await ensureThreadsDir();
|
||||||
|
const files = await readdir(dir);
|
||||||
|
const threads: Array<{ id: string; title: string; tweetCount: number; updatedAt: number }> = [];
|
||||||
|
for (const f of files) {
|
||||||
|
if (!f.endsWith(".json")) continue;
|
||||||
|
try {
|
||||||
|
const raw = await readFile(resolve(dir, f), "utf-8");
|
||||||
|
const data: ThreadData = JSON.parse(raw);
|
||||||
|
threads.push({ id: data.id, title: data.title, tweetCount: data.tweets.length, updatedAt: data.updatedAt });
|
||||||
|
} catch { /* skip corrupt files */ }
|
||||||
|
}
|
||||||
|
threads.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||||
|
return threads;
|
||||||
|
}
|
||||||
|
|
||||||
// ── API: Health ──
|
// ── API: Health ──
|
||||||
routes.get("/api/health", (c) => {
|
routes.get("/api/health", (c) => {
|
||||||
return c.json({ ok: true, module: "rsocials" });
|
return c.json({ ok: true, module: "rsocials" });
|
||||||
|
|
@ -94,6 +161,130 @@ routes.get("/api/campaigns", (c) => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── API: Thread CRUD ──
|
||||||
|
routes.get("/api/threads", async (c) => {
|
||||||
|
const threads = await listThreads();
|
||||||
|
return c.json({ threads });
|
||||||
|
});
|
||||||
|
|
||||||
|
routes.post("/api/threads", async (c) => {
|
||||||
|
const { name, handle, title, tweets } = await c.req.json();
|
||||||
|
if (!tweets?.length) return c.json({ error: "tweets required" }, 400);
|
||||||
|
|
||||||
|
const id = generateThreadId();
|
||||||
|
const now = Date.now();
|
||||||
|
const thread: ThreadData = {
|
||||||
|
id,
|
||||||
|
name: name || "Your Name",
|
||||||
|
handle: handle || "@yourhandle",
|
||||||
|
title: title || (tweets[0] || "").substring(0, 60),
|
||||||
|
tweets,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
await saveThread(thread);
|
||||||
|
return c.json({ id });
|
||||||
|
});
|
||||||
|
|
||||||
|
routes.get("/api/threads/:id", async (c) => {
|
||||||
|
const id = c.req.param("id");
|
||||||
|
if (!id || id.includes("..") || id.includes("/")) return c.json({ error: "Invalid ID" }, 400);
|
||||||
|
const thread = await loadThread(id);
|
||||||
|
if (!thread) return c.json({ error: "Thread not found" }, 404);
|
||||||
|
return c.json(thread);
|
||||||
|
});
|
||||||
|
|
||||||
|
routes.put("/api/threads/:id", async (c) => {
|
||||||
|
const id = c.req.param("id");
|
||||||
|
if (!id || id.includes("..") || id.includes("/")) return c.json({ error: "Invalid ID" }, 400);
|
||||||
|
const existing = await loadThread(id);
|
||||||
|
if (!existing) return c.json({ error: "Thread not found" }, 404);
|
||||||
|
|
||||||
|
const { name, handle, title, tweets } = await c.req.json();
|
||||||
|
if (name !== undefined) existing.name = name;
|
||||||
|
if (handle !== undefined) existing.handle = handle;
|
||||||
|
if (title !== undefined) existing.title = title;
|
||||||
|
if (tweets?.length) existing.tweets = tweets;
|
||||||
|
existing.updatedAt = Date.now();
|
||||||
|
|
||||||
|
await saveThread(existing);
|
||||||
|
return c.json({ id });
|
||||||
|
});
|
||||||
|
|
||||||
|
routes.delete("/api/threads/:id", async (c) => {
|
||||||
|
const id = c.req.param("id");
|
||||||
|
if (!id || id.includes("..") || id.includes("/")) return c.json({ error: "Invalid ID" }, 400);
|
||||||
|
|
||||||
|
// Try to delete associated preview image
|
||||||
|
const thread = await loadThread(id);
|
||||||
|
if (thread?.imageUrl) {
|
||||||
|
const filename = thread.imageUrl.split("/").pop();
|
||||||
|
if (filename) {
|
||||||
|
const genDir = resolve(process.env.FILES_DIR || "./data/files", "generated");
|
||||||
|
try { await unlink(resolve(genDir, filename)); } catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = await deleteThreadFile(id);
|
||||||
|
if (!ok) return c.json({ error: "Thread not found" }, 404);
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
routes.post("/api/threads/:id/image", async (c) => {
|
||||||
|
const id = c.req.param("id");
|
||||||
|
if (!id || id.includes("..") || id.includes("/")) return c.json({ error: "Invalid ID" }, 400);
|
||||||
|
|
||||||
|
const thread = await loadThread(id);
|
||||||
|
if (!thread) return c.json({ error: "Thread not found" }, 404);
|
||||||
|
|
||||||
|
const FAL_KEY = process.env.FAL_KEY || "";
|
||||||
|
if (!FAL_KEY) return c.json({ error: "FAL_KEY not configured" }, 503);
|
||||||
|
|
||||||
|
// Build prompt from first 2-3 tweets
|
||||||
|
const summary = thread.tweets.slice(0, 3).join(" ").substring(0, 200);
|
||||||
|
const prompt = `Social media thread preview card about: ${summary}. Dark themed, modern, minimal style with abstract shapes.`;
|
||||||
|
|
||||||
|
const falRes = await fetch("https://fal.run/fal-ai/flux-pro/v1.1", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Key ${FAL_KEY}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
prompt,
|
||||||
|
image_size: "landscape_4_3",
|
||||||
|
num_images: 1,
|
||||||
|
safety_tolerance: "2",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!falRes.ok) {
|
||||||
|
console.error("[thread-image] fal.ai error:", await falRes.text());
|
||||||
|
return c.json({ error: "Image generation failed" }, 502);
|
||||||
|
}
|
||||||
|
|
||||||
|
const falData = await falRes.json() as { images?: { url: string }[]; output?: { url: string } };
|
||||||
|
const cdnUrl = falData.images?.[0]?.url || falData.output?.url;
|
||||||
|
if (!cdnUrl) return c.json({ error: "No image returned" }, 502);
|
||||||
|
|
||||||
|
// Download and save locally
|
||||||
|
const imgRes = await fetch(cdnUrl);
|
||||||
|
if (!imgRes.ok) return c.json({ error: "Failed to download image" }, 502);
|
||||||
|
|
||||||
|
const imgBuffer = await imgRes.arrayBuffer();
|
||||||
|
const genDir = resolve(process.env.FILES_DIR || "./data/files", "generated");
|
||||||
|
await mkdir(genDir, { recursive: true });
|
||||||
|
const filename = `thread-${id}.png`;
|
||||||
|
await writeFile(resolve(genDir, filename), Buffer.from(imgBuffer));
|
||||||
|
|
||||||
|
const imageUrl = `/data/files/generated/${filename}`;
|
||||||
|
thread.imageUrl = imageUrl;
|
||||||
|
thread.updatedAt = Date.now();
|
||||||
|
await saveThread(thread);
|
||||||
|
|
||||||
|
return c.json({ imageUrl });
|
||||||
|
});
|
||||||
|
|
||||||
// ── Demo feed data (server-rendered, no API calls) ──
|
// ── Demo feed data (server-rendered, no API calls) ──
|
||||||
const DEMO_FEED = [
|
const DEMO_FEED = [
|
||||||
{
|
{
|
||||||
|
|
@ -399,13 +590,17 @@ routes.get("/campaign", (c) => {
|
||||||
// ── Thread Builder ──
|
// ── Thread Builder ──
|
||||||
const THREAD_CSS = `
|
const THREAD_CSS = `
|
||||||
.thread-page { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; max-width: 1100px; margin: 0 auto; padding: 2rem 1rem; min-height: 80vh; }
|
.thread-page { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; max-width: 1100px; margin: 0 auto; padding: 2rem 1rem; min-height: 80vh; }
|
||||||
.thread-page__header { grid-column: 1 / -1; display: flex; align-items: center; justify-content: space-between; }
|
.thread-page__header { grid-column: 1 / -1; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 0.5rem; }
|
||||||
.thread-page__header h1 { margin: 0; font-size: 1.5rem; color: #f1f5f9; background: linear-gradient(135deg, #7dd3fc, #c4b5fd); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
.thread-page__header h1 { margin: 0; font-size: 1.5rem; color: #f1f5f9; background: linear-gradient(135deg, #7dd3fc, #c4b5fd); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
||||||
|
.thread-page__actions { display: flex; gap: 0.5rem; flex-wrap: wrap; }
|
||||||
.thread-btn { padding: 0.5rem 1rem; border-radius: 8px; border: none; font-size: 0.85rem; font-weight: 600; cursor: pointer; transition: all 0.15s; }
|
.thread-btn { padding: 0.5rem 1rem; border-radius: 8px; border: none; font-size: 0.85rem; font-weight: 600; cursor: pointer; transition: all 0.15s; }
|
||||||
.thread-btn--primary { background: #6366f1; color: white; }
|
.thread-btn--primary { background: #6366f1; color: white; }
|
||||||
.thread-btn--primary:hover { background: #818cf8; }
|
.thread-btn--primary:hover { background: #818cf8; }
|
||||||
.thread-btn--outline { background: transparent; color: #94a3b8; border: 1px solid #334155; }
|
.thread-btn--outline { background: transparent; color: #94a3b8; border: 1px solid #334155; }
|
||||||
.thread-btn--outline:hover { border-color: #6366f1; color: #c4b5fd; }
|
.thread-btn--outline:hover { border-color: #6366f1; color: #c4b5fd; }
|
||||||
|
.thread-btn--success { background: #10b981; color: white; }
|
||||||
|
.thread-btn--success:hover { background: #34d399; }
|
||||||
|
.thread-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||||
.thread-compose { position: sticky; top: 1rem; align-self: start; display: flex; flex-direction: column; gap: 1rem; }
|
.thread-compose { position: sticky; top: 1rem; align-self: start; display: flex; flex-direction: column; gap: 1rem; }
|
||||||
.thread-compose__textarea {
|
.thread-compose__textarea {
|
||||||
width: 100%; min-height: 320px; background: #1e293b; color: #e2e8f0; border: 1px solid #334155;
|
width: 100%; min-height: 320px; background: #1e293b; color: #e2e8f0; border: 1px solid #334155;
|
||||||
|
|
@ -421,6 +616,49 @@ const THREAD_CSS = `
|
||||||
}
|
}
|
||||||
.thread-compose__input:focus { outline: none; border-color: #6366f1; }
|
.thread-compose__input:focus { outline: none; border-color: #6366f1; }
|
||||||
.thread-compose__input::placeholder { color: #475569; }
|
.thread-compose__input::placeholder { color: #475569; }
|
||||||
|
.thread-compose__title {
|
||||||
|
width: 100%; background: #1e293b; color: #e2e8f0; border: 1px solid #334155;
|
||||||
|
border-radius: 8px; padding: 0.5rem 0.75rem; font-size: 0.85rem; box-sizing: border-box;
|
||||||
|
}
|
||||||
|
.thread-compose__title:focus { outline: none; border-color: #6366f1; }
|
||||||
|
.thread-compose__title::placeholder { color: #475569; }
|
||||||
|
.thread-drafts { grid-column: 1 / -1; }
|
||||||
|
.thread-drafts__toggle { cursor: pointer; user-select: none; }
|
||||||
|
.thread-drafts__list {
|
||||||
|
display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 0.5rem;
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
.thread-drafts__list[hidden] { display: none; }
|
||||||
|
.thread-drafts__empty { color: #475569; font-size: 0.8rem; padding: 0.5rem 0; }
|
||||||
|
.thread-draft-item {
|
||||||
|
display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem 0.75rem;
|
||||||
|
background: #1e293b; border: 1px solid #334155; border-radius: 8px;
|
||||||
|
transition: border-color 0.15s; cursor: pointer;
|
||||||
|
}
|
||||||
|
.thread-draft-item:hover { border-color: #6366f1; }
|
||||||
|
.thread-draft-item--active { border-color: #6366f1; background: rgba(99,102,241,0.1); }
|
||||||
|
.thread-draft-item__info { flex: 1; min-width: 0; }
|
||||||
|
.thread-draft-item__info strong { display: block; font-size: 0.8rem; color: #e2e8f0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.thread-draft-item__info span { font-size: 0.7rem; color: #64748b; }
|
||||||
|
.thread-draft-item__delete {
|
||||||
|
background: none; border: none; color: #64748b; font-size: 1.2rem; cursor: pointer;
|
||||||
|
padding: 0 4px; line-height: 1; flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.thread-draft-item__delete:hover { color: #ef4444; }
|
||||||
|
.thread-image-section { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; }
|
||||||
|
.thread-image-preview { border-radius: 8px; overflow: hidden; border: 1px solid #334155; }
|
||||||
|
.thread-image-preview[hidden] { display: none; }
|
||||||
|
.thread-image-preview img { display: block; max-width: 200px; height: auto; }
|
||||||
|
.thread-share-link {
|
||||||
|
display: flex; align-items: center; gap: 0.5rem; padding: 0.4rem 0.75rem;
|
||||||
|
background: rgba(99,102,241,0.1); border: 1px solid #6366f1; border-radius: 8px;
|
||||||
|
font-size: 0.8rem; color: #c4b5fd;
|
||||||
|
}
|
||||||
|
.thread-share-link code { font-size: 0.75rem; color: #7dd3fc; }
|
||||||
|
.thread-share-link button {
|
||||||
|
background: none; border: none; color: #94a3b8; cursor: pointer; font-size: 0.75rem; padding: 2px 6px;
|
||||||
|
}
|
||||||
|
.thread-share-link button:hover { color: #e2e8f0; }
|
||||||
.thread-preview { display: flex; flex-direction: column; gap: 0; }
|
.thread-preview { display: flex; flex-direction: column; gap: 0; }
|
||||||
.thread-preview__empty { color: #475569; text-align: center; padding: 3rem 1rem; font-size: 0.9rem; }
|
.thread-preview__empty { color: #475569; text-align: center; padding: 3rem 1rem; font-size: 0.9rem; }
|
||||||
.tweet-card {
|
.tweet-card {
|
||||||
|
|
@ -458,30 +696,66 @@ const THREAD_CSS = `
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
function renderThreadBuilderPage(space: string): string {
|
function renderThreadBuilderPage(space: string, threadData?: ThreadData | null): string {
|
||||||
|
const dataScript = threadData
|
||||||
|
? `<script>window.__THREAD_DATA__ = ${JSON.stringify(threadData).replace(/</g, "\\u003c")};</script>`
|
||||||
|
: "";
|
||||||
|
const basePath = `/${space}/rsocials/`;
|
||||||
|
|
||||||
return `
|
return `
|
||||||
|
${dataScript}
|
||||||
|
<script>window.__BASE_PATH__ = ${JSON.stringify(basePath)};</script>
|
||||||
<div class="thread-page">
|
<div class="thread-page">
|
||||||
<div class="thread-page__header">
|
<div class="thread-page__header">
|
||||||
<h1>Thread Builder</h1>
|
<h1>Thread Builder</h1>
|
||||||
<button class="thread-btn thread-btn--primary" id="thread-copy">Copy Thread</button>
|
<div class="thread-page__actions">
|
||||||
|
<button class="thread-btn thread-btn--primary" id="thread-save">Save Draft</button>
|
||||||
|
<button class="thread-btn thread-btn--success" id="thread-share">Share</button>
|
||||||
|
<button class="thread-btn thread-btn--outline" id="thread-copy">Copy Thread</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="thread-drafts">
|
||||||
|
<button class="thread-btn thread-btn--outline thread-drafts__toggle" id="toggle-drafts">Saved Drafts ▾</button>
|
||||||
|
<div class="thread-drafts__list" id="drafts-list" hidden></div>
|
||||||
|
</div>
|
||||||
|
<div id="share-link-area"></div>
|
||||||
<div class="thread-compose">
|
<div class="thread-compose">
|
||||||
<textarea class="thread-compose__textarea" id="thread-input" placeholder="Write your tweets here, separated by ---\n\nExample:\nFirst tweet goes here\n---\nSecond tweet\n---\nThird tweet"></textarea>
|
<textarea class="thread-compose__textarea" id="thread-input" placeholder="Write your tweets here, separated by ---\n\nExample:\nFirst tweet goes here\n---\nSecond tweet\n---\nThird tweet"></textarea>
|
||||||
<div class="thread-compose__fields">
|
<div class="thread-compose__fields">
|
||||||
<input class="thread-compose__input" id="thread-name" placeholder="Display name" value="Your Name">
|
<input class="thread-compose__input" id="thread-name" placeholder="Display name" value="Your Name">
|
||||||
<input class="thread-compose__input" id="thread-handle" placeholder="@handle" value="@yourhandle">
|
<input class="thread-compose__input" id="thread-handle" placeholder="@handle" value="@yourhandle">
|
||||||
</div>
|
</div>
|
||||||
|
<input class="thread-compose__title" id="thread-title" placeholder="Thread title (defaults to first tweet)">
|
||||||
|
<div class="thread-image-section">
|
||||||
|
<button class="thread-btn thread-btn--outline" id="gen-image-btn">Generate Preview Image</button>
|
||||||
|
<div class="thread-image-preview" id="thread-image-preview" hidden>
|
||||||
|
<img id="thread-image-thumb" alt="Preview">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="thread-preview" id="thread-preview">
|
<div class="thread-preview" id="thread-preview">
|
||||||
<div class="thread-preview__empty">Your tweet thread preview will appear here</div>
|
<div class="thread-preview__empty">Your tweet thread preview will appear here</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script type="module">
|
<script type="module">
|
||||||
|
const base = window.__BASE_PATH__ || './';
|
||||||
|
let currentThreadId = null;
|
||||||
|
let autoSaveTimer = null;
|
||||||
|
|
||||||
const textarea = document.getElementById('thread-input');
|
const textarea = document.getElementById('thread-input');
|
||||||
const preview = document.getElementById('thread-preview');
|
const preview = document.getElementById('thread-preview');
|
||||||
const nameInput = document.getElementById('thread-name');
|
const nameInput = document.getElementById('thread-name');
|
||||||
const handleInput = document.getElementById('thread-handle');
|
const handleInput = document.getElementById('thread-handle');
|
||||||
|
const titleInput = document.getElementById('thread-title');
|
||||||
const copyBtn = document.getElementById('thread-copy');
|
const copyBtn = document.getElementById('thread-copy');
|
||||||
|
const saveBtn = document.getElementById('thread-save');
|
||||||
|
const shareBtn = document.getElementById('thread-share');
|
||||||
|
const genImageBtn = document.getElementById('gen-image-btn');
|
||||||
|
const toggleDraftsBtn = document.getElementById('toggle-drafts');
|
||||||
|
const draftsList = document.getElementById('drafts-list');
|
||||||
|
const imagePreview = document.getElementById('thread-image-preview');
|
||||||
|
const imageThumb = document.getElementById('thread-image-thumb');
|
||||||
|
const shareLinkArea = document.getElementById('share-link-area');
|
||||||
|
|
||||||
const svgReply = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>';
|
const svgReply = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>';
|
||||||
const svgRetweet = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>';
|
const svgRetweet = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M17 1l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 23l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>';
|
||||||
|
|
@ -513,7 +787,7 @@ function renderThreadBuilderPage(space: string): string {
|
||||||
'<div class="tweet-card__avatar">' + esc(initial) + '</div>' +
|
'<div class="tweet-card__avatar">' + esc(initial) + '</div>' +
|
||||||
'<span class="tweet-card__name">' + esc(name) + '</span>' +
|
'<span class="tweet-card__name">' + esc(name) + '</span>' +
|
||||||
'<span class="tweet-card__handle">' + esc(handle) + '</span>' +
|
'<span class="tweet-card__handle">' + esc(handle) + '</span>' +
|
||||||
'<span class="tweet-card__dot">·</span>' +
|
'<span class="tweet-card__dot">·</span>' +
|
||||||
'<span class="tweet-card__time">now</span>' +
|
'<span class="tweet-card__time">now</span>' +
|
||||||
'</div>' +
|
'</div>' +
|
||||||
'<p class="tweet-card__content">' + esc(text) + '</p>' +
|
'<p class="tweet-card__content">' + esc(text) + '</p>' +
|
||||||
|
|
@ -533,10 +807,219 @@ function renderThreadBuilderPage(space: string): string {
|
||||||
}).join('');
|
}).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Draft management ──
|
||||||
|
async function saveDraft() {
|
||||||
|
const tweets = textarea.value.split(/\\n---\\n/).map(t => t.trim()).filter(Boolean);
|
||||||
|
if (!tweets.length) return;
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
name: nameInput.value || 'Your Name',
|
||||||
|
handle: handleInput.value || '@yourhandle',
|
||||||
|
title: titleInput.value || tweets[0].substring(0, 60),
|
||||||
|
tweets,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
let res;
|
||||||
|
if (currentThreadId) {
|
||||||
|
res = await fetch(base + 'api/threads/' + currentThreadId, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
res = await fetch(base + 'api/threads', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.id) {
|
||||||
|
currentThreadId = data.id;
|
||||||
|
history.replaceState(null, '', base + 'thread/' + data.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
saveBtn.textContent = 'Saved!';
|
||||||
|
setTimeout(() => { saveBtn.textContent = 'Save Draft'; }, 2000);
|
||||||
|
loadDraftList();
|
||||||
|
} catch (e) {
|
||||||
|
saveBtn.textContent = 'Error';
|
||||||
|
setTimeout(() => { saveBtn.textContent = 'Save Draft'; }, 2000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadDraft(id) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(base + 'api/threads/' + id);
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.error) return;
|
||||||
|
|
||||||
|
currentThreadId = data.id;
|
||||||
|
nameInput.value = data.name || '';
|
||||||
|
handleInput.value = data.handle || '';
|
||||||
|
titleInput.value = data.title || '';
|
||||||
|
textarea.value = data.tweets.join('\\n---\\n');
|
||||||
|
|
||||||
|
if (data.imageUrl) {
|
||||||
|
imageThumb.src = data.imageUrl;
|
||||||
|
imagePreview.hidden = false;
|
||||||
|
genImageBtn.textContent = 'Regenerate Image';
|
||||||
|
} else {
|
||||||
|
imagePreview.hidden = true;
|
||||||
|
genImageBtn.textContent = 'Generate Preview Image';
|
||||||
|
}
|
||||||
|
|
||||||
|
history.replaceState(null, '', base + 'thread/' + data.id);
|
||||||
|
renderPreview();
|
||||||
|
loadDraftList();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to load draft:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteDraft(id) {
|
||||||
|
if (!confirm('Delete this draft?')) return;
|
||||||
|
try {
|
||||||
|
await fetch(base + 'api/threads/' + id, { method: 'DELETE' });
|
||||||
|
if (currentThreadId === id) {
|
||||||
|
currentThreadId = null;
|
||||||
|
history.replaceState(null, '', base + 'thread');
|
||||||
|
imagePreview.hidden = true;
|
||||||
|
genImageBtn.textContent = 'Generate Preview Image';
|
||||||
|
shareLinkArea.innerHTML = '';
|
||||||
|
}
|
||||||
|
loadDraftList();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to delete draft:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadDraftList() {
|
||||||
|
try {
|
||||||
|
const res = await fetch(base + 'api/threads');
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!data.threads?.length) {
|
||||||
|
draftsList.innerHTML = '<div class="thread-drafts__empty">No saved drafts</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
draftsList.innerHTML = data.threads.map(t => {
|
||||||
|
const date = new Date(t.updatedAt);
|
||||||
|
const dateStr = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||||
|
const active = t.id === currentThreadId ? ' thread-draft-item--active' : '';
|
||||||
|
return '<div class="thread-draft-item' + active + '">' +
|
||||||
|
'<div class="thread-draft-item__info" data-load-id="' + esc(t.id) + '">' +
|
||||||
|
'<strong>' + esc(t.title) + '</strong>' +
|
||||||
|
'<span>' + t.tweetCount + ' tweets · ' + dateStr + '</span>' +
|
||||||
|
'</div>' +
|
||||||
|
'<button class="thread-draft-item__delete" data-delete-id="' + esc(t.id) + '">×</button>' +
|
||||||
|
'</div>';
|
||||||
|
}).join('');
|
||||||
|
|
||||||
|
// Attach event listeners
|
||||||
|
draftsList.querySelectorAll('[data-load-id]').forEach(el => {
|
||||||
|
el.addEventListener('click', () => loadDraft(el.dataset.loadId));
|
||||||
|
});
|
||||||
|
draftsList.querySelectorAll('[data-delete-id]').forEach(el => {
|
||||||
|
el.addEventListener('click', (e) => { e.stopPropagation(); deleteDraft(el.dataset.deleteId); });
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
draftsList.innerHTML = '<div class="thread-drafts__empty">Failed to load drafts</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function shareThread() {
|
||||||
|
shareBtn.textContent = 'Saving...';
|
||||||
|
shareBtn.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await saveDraft();
|
||||||
|
if (!currentThreadId) { shareBtn.textContent = 'Share'; shareBtn.disabled = false; return; }
|
||||||
|
|
||||||
|
if (imagePreview.hidden) {
|
||||||
|
shareBtn.textContent = 'Generating image...';
|
||||||
|
await generateImage();
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = window.location.origin + base + 'thread/' + currentThreadId;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(url);
|
||||||
|
shareBtn.textContent = 'Link Copied!';
|
||||||
|
} catch {
|
||||||
|
shareBtn.textContent = 'Shared!';
|
||||||
|
}
|
||||||
|
|
||||||
|
shareLinkArea.innerHTML = '<div class="thread-share-link">' +
|
||||||
|
'<code>' + esc(url) + '</code>' +
|
||||||
|
'<button id="copy-share-link">Copy</button>' +
|
||||||
|
'</div>';
|
||||||
|
document.getElementById('copy-share-link')?.addEventListener('click', () => {
|
||||||
|
navigator.clipboard.writeText(url);
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
shareBtn.textContent = 'Error';
|
||||||
|
}
|
||||||
|
setTimeout(() => { shareBtn.textContent = 'Share'; shareBtn.disabled = false; }, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function generateImage() {
|
||||||
|
if (!currentThreadId) {
|
||||||
|
await saveDraft();
|
||||||
|
if (!currentThreadId) return;
|
||||||
|
}
|
||||||
|
|
||||||
|
genImageBtn.textContent = 'Generating...';
|
||||||
|
genImageBtn.disabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(base + 'api/threads/' + currentThreadId + '/image', { method: 'POST' });
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (data.imageUrl) {
|
||||||
|
imageThumb.src = data.imageUrl;
|
||||||
|
imagePreview.hidden = false;
|
||||||
|
genImageBtn.textContent = 'Regenerate Image';
|
||||||
|
} else {
|
||||||
|
genImageBtn.textContent = 'Generation Failed';
|
||||||
|
setTimeout(() => { genImageBtn.textContent = 'Generate Preview Image'; }, 2000);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
genImageBtn.textContent = 'Generation Failed';
|
||||||
|
setTimeout(() => { genImageBtn.textContent = 'Generate Preview Image'; }, 2000);
|
||||||
|
} finally {
|
||||||
|
genImageBtn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-save on blur if thread has been saved once
|
||||||
|
function scheduleAutoSave() {
|
||||||
|
if (!currentThreadId) return;
|
||||||
|
clearTimeout(autoSaveTimer);
|
||||||
|
autoSaveTimer = setTimeout(() => saveDraft(), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Event listeners ──
|
||||||
textarea.addEventListener('input', renderPreview);
|
textarea.addEventListener('input', renderPreview);
|
||||||
nameInput.addEventListener('input', renderPreview);
|
nameInput.addEventListener('input', renderPreview);
|
||||||
handleInput.addEventListener('input', renderPreview);
|
handleInput.addEventListener('input', renderPreview);
|
||||||
|
|
||||||
|
textarea.addEventListener('blur', scheduleAutoSave);
|
||||||
|
nameInput.addEventListener('blur', scheduleAutoSave);
|
||||||
|
handleInput.addEventListener('blur', scheduleAutoSave);
|
||||||
|
titleInput.addEventListener('blur', scheduleAutoSave);
|
||||||
|
|
||||||
|
saveBtn.addEventListener('click', saveDraft);
|
||||||
|
shareBtn.addEventListener('click', shareThread);
|
||||||
|
genImageBtn.addEventListener('click', generateImage);
|
||||||
|
|
||||||
|
toggleDraftsBtn.addEventListener('click', () => {
|
||||||
|
draftsList.hidden = !draftsList.hidden;
|
||||||
|
toggleDraftsBtn.innerHTML = draftsList.hidden ? 'Saved Drafts ▾' : 'Saved Drafts ▴';
|
||||||
|
});
|
||||||
|
|
||||||
copyBtn.addEventListener('click', async () => {
|
copyBtn.addEventListener('click', async () => {
|
||||||
const tweets = textarea.value.split(/\\n---\\n/).map(t => t.trim()).filter(Boolean);
|
const tweets = textarea.value.split(/\\n---\\n/).map(t => t.trim()).filter(Boolean);
|
||||||
if (!tweets.length) return;
|
if (!tweets.length) return;
|
||||||
|
|
@ -551,9 +1034,65 @@ function renderThreadBuilderPage(space: string): string {
|
||||||
setTimeout(() => { copyBtn.textContent = 'Copy Thread'; }, 2000);
|
setTimeout(() => { copyBtn.textContent = 'Copy Thread'; }, 2000);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Load initial data ──
|
||||||
|
if (window.__THREAD_DATA__) {
|
||||||
|
const data = window.__THREAD_DATA__;
|
||||||
|
currentThreadId = data.id;
|
||||||
|
nameInput.value = data.name || '';
|
||||||
|
handleInput.value = data.handle || '';
|
||||||
|
titleInput.value = data.title || '';
|
||||||
|
textarea.value = data.tweets.join('\\n---\\n');
|
||||||
|
if (data.imageUrl) {
|
||||||
|
imageThumb.src = data.imageUrl;
|
||||||
|
imagePreview.hidden = false;
|
||||||
|
genImageBtn.textContent = 'Regenerate Image';
|
||||||
|
}
|
||||||
|
renderPreview();
|
||||||
|
}
|
||||||
|
loadDraftList();
|
||||||
</script>`;
|
</script>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Thread permalink with OG tags ──
|
||||||
|
routes.get("/thread/:id", async (c) => {
|
||||||
|
const space = c.req.param("space") || "demo";
|
||||||
|
const id = c.req.param("id");
|
||||||
|
if (!id || id.includes("..") || id.includes("/")) return c.text("Not found", 404);
|
||||||
|
|
||||||
|
const thread = await loadThread(id);
|
||||||
|
if (!thread) return c.text("Thread not found", 404);
|
||||||
|
|
||||||
|
const desc = escapeHtml((thread.tweets[0] || "").substring(0, 200));
|
||||||
|
const titleText = escapeHtml(`Thread by ${thread.handle}`);
|
||||||
|
const origin = "https://rspace.online";
|
||||||
|
|
||||||
|
let ogHead = `
|
||||||
|
<meta property="og:title" content="${titleText}">
|
||||||
|
<meta property="og:description" content="${desc}">
|
||||||
|
<meta property="og:type" content="article">
|
||||||
|
<meta name="twitter:card" content="summary_large_image">
|
||||||
|
<meta name="twitter:title" content="${titleText}">
|
||||||
|
<meta name="twitter:description" content="${desc}">`;
|
||||||
|
|
||||||
|
if (thread.imageUrl) {
|
||||||
|
ogHead += `
|
||||||
|
<meta property="og:image" content="${origin}${thread.imageUrl}">
|
||||||
|
<meta name="twitter:image" content="${origin}${thread.imageUrl}">`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.html(renderShell({
|
||||||
|
title: `${thread.title || "Thread"} — rSocials | rSpace`,
|
||||||
|
moduleId: "rsocials",
|
||||||
|
spaceSlug: space,
|
||||||
|
modules: getModuleInfoList(),
|
||||||
|
theme: "dark",
|
||||||
|
body: renderThreadBuilderPage(space, thread),
|
||||||
|
styles: `<style>${THREAD_CSS}</style>`,
|
||||||
|
head: ogHead,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
routes.get("/thread", (c) => {
|
routes.get("/thread", (c) => {
|
||||||
const space = c.req.param("space") || "demo";
|
const space = c.req.param("space") || "demo";
|
||||||
return c.html(renderShell({
|
return c.html(renderShell({
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue