feat: round-5 external harvest (22 features ported from external/ into 5 products)
Harvest valuable features from external/ reference repos, adapted to each product's stack and wired in; all products typecheck clean. - gitgram-web (5): clickable @mention/#hashtag linkify in rendered content (munia), + feed/notification/accessibility patterns; install @testing-library/dom - gitgram-backend (3): feed thread dedup + muted-thread removal (bluesky), GitHub star/follow write-back via OAuth (gh-social) - gitgram-mobile (4): double-tap-to-like + heart bounce (proximity), haptics layer (bluesky useHaptics), + gesture/feed UX - aitm-api (4): beads ready/dependency-DAG endpoints + atomic claim (beads) - aitm-mcp (6): beads_ready work-queue tool, context-efficient projections, transport arg aliasing (context7/pal-mcp/beads) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
54ca6de161
commit
46bf9b83bf
@ -1,10 +1,16 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { execFile, exec } from "child_process";
|
||||
import { promisify } from "util";
|
||||
import { ingestTask, type BeadsTask } from "../services/memoryService.js";
|
||||
import {
|
||||
ingestTask,
|
||||
addDependency,
|
||||
listDependencies,
|
||||
findDependencyCycles,
|
||||
type BeadsTask,
|
||||
} from "../services/memoryService.js";
|
||||
import { resolveBeadsBinary } from "../services/engineManager.js";
|
||||
import { logger } from "../lib/monitoring.js";
|
||||
import { apiKeyAuth } from "../middleware/auth.js";
|
||||
import { apiKeyAuth, AuthenticatedRequest } from "../middleware/auth.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const execAsync = promisify(exec);
|
||||
@ -18,6 +24,99 @@ function beadsBin(): string {
|
||||
return resolveBeadsBinary().path ?? "bd";
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the trimmed stdout of a `bd ... --json` invocation. The binary emits an
|
||||
* empty body for some commands; in that case `null` is returned rather than
|
||||
* throwing a JSON parse error.
|
||||
*/
|
||||
function parseBeadsJson(stdout: string): unknown {
|
||||
const trimmed = stdout.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(trimmed) as unknown;
|
||||
}
|
||||
|
||||
/** A non-empty, trimmed string, or null when the value is absent/blank. */
|
||||
function cleanId(value: unknown): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce a query-string value (string | string[] | undefined) to a single
|
||||
* trimmed string. Express types repeated/array query params, so collapse them.
|
||||
*/
|
||||
function singleQueryValue(value: unknown): string | undefined {
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
if (Array.isArray(value) && value.length > 0) {
|
||||
return singleQueryValue(value[0]);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a comma-separated (or array) label value into a clean array of
|
||||
* non-empty labels.
|
||||
*/
|
||||
function labelList(value: unknown): string[] {
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.map((label) => (typeof label === "string" ? label.trim() : ""))
|
||||
.filter((label) => label.length > 0);
|
||||
}
|
||||
const raw = singleQueryValue(value);
|
||||
if (!raw) {
|
||||
return [];
|
||||
}
|
||||
return raw
|
||||
.split(",")
|
||||
.map((label) => label.trim())
|
||||
.filter((label) => label.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a bounded integer from a value. Returns undefined when absent or not a
|
||||
* finite integer; clamps the result into [min, max].
|
||||
*/
|
||||
function boundedInt(
|
||||
value: unknown,
|
||||
min: number,
|
||||
max: number
|
||||
): number | undefined {
|
||||
const raw =
|
||||
typeof value === "number" ? String(value) : singleQueryValue(value);
|
||||
if (raw === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const parsed = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(parsed)) {
|
||||
return undefined;
|
||||
}
|
||||
return Math.min(Math.max(parsed, min), max);
|
||||
}
|
||||
|
||||
const DEPENDENCY_TYPES = [
|
||||
"blocks",
|
||||
"related",
|
||||
"parent-child",
|
||||
"discovered-from",
|
||||
] as const;
|
||||
type DependencyType = (typeof DEPENDENCY_TYPES)[number];
|
||||
|
||||
function isDependencyType(value: unknown): value is DependencyType {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
(DEPENDENCY_TYPES as readonly string[]).includes(value)
|
||||
);
|
||||
}
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Every beads endpoint reads or mutates task-management state and shells out
|
||||
@ -35,6 +134,229 @@ router.get("/tasks", async (_req: Request, res: Response) => {
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/ready — work-queue query: unblocked, ready-to-work tasks.
|
||||
// Optional filters: priority (0-4), assignee, unassigned, labels (AND),
|
||||
// labelsAny (OR), limit (1-100), sort (priority|hybrid|oldest).
|
||||
//
|
||||
// With ?claim=1 (or claim=true) the first ready task matching the filters is
|
||||
// atomically claimed (assignee=actor + status=in_progress) in a single
|
||||
// compare-and-swap step, so concurrent agents cannot grab the same task. Per
|
||||
// the beads CLI, --claim cannot be combined with --assignee/--unassigned, so
|
||||
// those filters are ignored when claiming.
|
||||
router.get("/ready", async (req: AuthenticatedRequest, res: Response) => {
|
||||
const claim =
|
||||
singleQueryValue(req.query.claim) === "1" ||
|
||||
singleQueryValue(req.query.claim) === "true";
|
||||
|
||||
const args: string[] = ["ready", "--json"];
|
||||
|
||||
const priority = boundedInt(req.query.priority, 0, 4);
|
||||
if (priority !== undefined) {
|
||||
args.push("--priority", String(priority));
|
||||
}
|
||||
|
||||
if (claim) {
|
||||
args.push("--claim");
|
||||
} else {
|
||||
const assignee = singleQueryValue(req.query.assignee);
|
||||
if (assignee) {
|
||||
args.push("--assignee", assignee);
|
||||
}
|
||||
if (singleQueryValue(req.query.unassigned) === "true") {
|
||||
args.push("--unassigned");
|
||||
}
|
||||
}
|
||||
|
||||
for (const label of labelList(req.query.labels)) {
|
||||
args.push("--label", label);
|
||||
}
|
||||
for (const label of labelList(req.query.labelsAny)) {
|
||||
args.push("--label-any", label);
|
||||
}
|
||||
|
||||
const limit = boundedInt(req.query.limit, 1, 100);
|
||||
if (limit !== undefined) {
|
||||
args.push("--limit", String(limit));
|
||||
}
|
||||
|
||||
// --sort only applies to the query form; claiming takes the first match.
|
||||
if (!claim) {
|
||||
const sort = singleQueryValue(req.query.sort);
|
||||
if (sort === "priority" || sort === "hybrid" || sort === "oldest") {
|
||||
args.push("--sort", sort);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), args);
|
||||
const data = parseBeadsJson(stdout) ?? [];
|
||||
|
||||
// When a claim succeeds, write the claimed task through to the unified
|
||||
// memory layer so it is searchable (best-effort, never blocks the response).
|
||||
if (claim) {
|
||||
const claimed = Array.isArray(data) ? data[0] : data;
|
||||
if (claimed && typeof claimed === "object" && !Array.isArray(claimed)) {
|
||||
void ingestTask(claimed as BeadsTask, { userId: req.user?.userId }).catch(
|
||||
(error: unknown) => {
|
||||
logger.warn("beads: claim memory write-through failed", {
|
||||
details: String(error),
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ success: true, data });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Failed to query ready tasks",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/blocked — list blocked tasks and the dependencies blocking them.
|
||||
router.get("/blocked", async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), ["blocked", "--json"]);
|
||||
res.json({ success: true, data: parseBeadsJson(stdout) ?? [] });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error:
|
||||
err instanceof Error ? err.message : "Failed to query blocked tasks",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/stats — totals (open/in_progress/closed/blocked/ready) plus the
|
||||
// average lead time. Backed by `bd status --json` (alias: `bd stats`).
|
||||
router.get("/stats", async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), [
|
||||
"status",
|
||||
"--json",
|
||||
"--no-activity",
|
||||
]);
|
||||
res.json({ success: true, data: parseBeadsJson(stdout) });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Failed to get statistics",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /beads/tasks/:id/claim — atomically claim a single task.
|
||||
//
|
||||
// Sets assignee (to the configured actor) and status=in_progress in one
|
||||
// compare-and-swap step. This is the multi-agent-safe primitive: two agents
|
||||
// racing on the same task cannot both win the claim. Idempotent when the task
|
||||
// is already claimed by the same actor; a 409 is returned when another actor
|
||||
// holds the claim.
|
||||
router.put("/tasks/:id/claim", async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = cleanId(req.params.id);
|
||||
if (!id) {
|
||||
return res.status(400).json({ success: false, error: "task id is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), ["update", id, "--claim", "--json"]);
|
||||
const data = parseBeadsJson(stdout);
|
||||
|
||||
const claimed = Array.isArray(data) ? data[0] : data;
|
||||
if (claimed && typeof claimed === "object" && !Array.isArray(claimed)) {
|
||||
void ingestTask(claimed as BeadsTask, { userId: req.user?.userId }).catch(
|
||||
(error: unknown) => {
|
||||
logger.warn("beads: claim memory write-through failed", {
|
||||
details: String(error),
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
res.json({ success: true, data });
|
||||
} catch (err: unknown) {
|
||||
// The CLI exits non-zero when the compare-and-swap claim fails because the
|
||||
// task is already in progress / claimed by another actor. Surface that as a
|
||||
// 409 so callers can retry a different task instead of treating it as a
|
||||
// server fault.
|
||||
const message = err instanceof Error ? err.message : "Failed to claim task";
|
||||
const conflict = /claim|in[_ ]?progress|already/i.test(message);
|
||||
res.status(conflict ? 409 : 500).json({ success: false, error: message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /beads/deps — add a dependency edge to the DAG: `blocked` depends on
|
||||
// `blocker`. The binary runs a cycle check and refuses an edge that would
|
||||
// create a cycle (surfaced here as 409). body: { blocked, blocker, type? }
|
||||
router.post("/deps", async (req: Request, res: Response) => {
|
||||
const body = req.body as { blocked?: unknown; blocker?: unknown; type?: unknown };
|
||||
const blocked = cleanId(body.blocked);
|
||||
const blocker = cleanId(body.blocker);
|
||||
|
||||
if (!blocked || !blocker) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: "both blocked and blocker task ids are required",
|
||||
});
|
||||
}
|
||||
if (blocked === blocker) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ success: false, error: "a task cannot depend on itself" });
|
||||
}
|
||||
|
||||
const type = isDependencyType(body.type) ? body.type : undefined;
|
||||
|
||||
try {
|
||||
const data = await addDependency(blocked, blocker, type);
|
||||
res.status(201).json({ success: true, data });
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : "Failed to add dependency";
|
||||
const isCycle = /cycle/i.test(message);
|
||||
res.status(isCycle ? 409 : 500).json({ success: false, error: message });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/deps?id=:id&direction=down|up — list dependency edges for a task.
|
||||
// direction=down (default): what :id depends on (its blockers)
|
||||
// direction=up: what depends on :id (issues it blocks)
|
||||
router.get("/deps", async (req: Request, res: Response) => {
|
||||
const id = cleanId(req.query.id);
|
||||
if (!id) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ success: false, error: "id query param is required" });
|
||||
}
|
||||
|
||||
const direction = singleQueryValue(req.query.direction) === "up" ? "up" : "down";
|
||||
|
||||
try {
|
||||
const data = await listDependencies(id, direction);
|
||||
res.json({ success: true, data });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Failed to list dependencies",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/deps/cycles — detect dependency cycles across the whole DAG.
|
||||
router.get("/deps/cycles", async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const data = await findDependencyCycles();
|
||||
res.json({ success: true, data });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error:
|
||||
err instanceof Error ? err.message : "Failed to detect dependency cycles",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /beads/tasks — create a task
|
||||
// body: { title: string, deps?: string[] }
|
||||
router.post("/tasks", async (req: Request, res: Response) => {
|
||||
@ -52,8 +374,7 @@ router.post("/tasks", async (req: Request, res: Response) => {
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), args);
|
||||
const trimmed = stdout.trim();
|
||||
const data: unknown = trimmed ? JSON.parse(trimmed) : null;
|
||||
const data = parseBeadsJson(stdout);
|
||||
|
||||
// Write-through into the unified memory layer (best-effort; never blocks
|
||||
// the response). Falls back to the title when the binary returns no JSON.
|
||||
@ -71,15 +392,61 @@ router.post("/tasks", async (req: Request, res: Response) => {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /beads/tasks/:id/deps — add a dependency edge from this task to another.
|
||||
// body: { dependsOn: string, type?: blocks|related|parent-child|discovered-from }
|
||||
// Models the blocker an agent discovers mid-task (e.g. a discovered-from edge).
|
||||
router.post("/tasks/:id/deps", async (req: Request, res: Response) => {
|
||||
const id = cleanId(req.params.id);
|
||||
if (!id) {
|
||||
return res.status(400).json({ success: false, error: "task id is required" });
|
||||
}
|
||||
|
||||
const body = req.body as { dependsOn?: unknown; type?: unknown };
|
||||
const dependsOn = cleanId(body.dependsOn);
|
||||
if (!dependsOn) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ success: false, error: "dependsOn (a task id) is required" });
|
||||
}
|
||||
|
||||
let depType: DependencyType = "blocks";
|
||||
if (body.type !== undefined) {
|
||||
if (!isDependencyType(body.type)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: `type must be one of: ${DEPENDENCY_TYPES.join(", ")}`,
|
||||
});
|
||||
}
|
||||
depType = body.type;
|
||||
}
|
||||
|
||||
// `bd dep add <issue> <depends-on> --type <t>` records that <issue> depends
|
||||
// on <depends-on>.
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), [
|
||||
"dep",
|
||||
"add",
|
||||
id,
|
||||
dependsOn,
|
||||
"--type",
|
||||
depType,
|
||||
]);
|
||||
res.status(201).json({ success: true, data: parseBeadsJson(stdout) });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Failed to add dependency",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /beads/tasks/:id/ready — mark task ready
|
||||
router.put("/tasks/:id/ready", async (req: Request, res: Response) => {
|
||||
const { id } = req.params;
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), ["ready", id]);
|
||||
const trimmed = stdout.trim();
|
||||
const data: unknown = trimmed ? JSON.parse(trimmed) : null;
|
||||
res.json({ success: true, data });
|
||||
res.json({ success: true, data: parseBeadsJson(stdout) });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({ success: false, error: err instanceof Error ? err.message : "Failed to mark task ready" });
|
||||
}
|
||||
@ -91,14 +458,140 @@ router.put("/tasks/:id/done", async (req: Request, res: Response) => {
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), ["done", id]);
|
||||
const trimmed = stdout.trim();
|
||||
const data: unknown = trimmed ? JSON.parse(trimmed) : null;
|
||||
res.json({ success: true, data });
|
||||
res.json({ success: true, data: parseBeadsJson(stdout) });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({ success: false, error: err instanceof Error ? err.message : "Failed to mark task done" });
|
||||
}
|
||||
});
|
||||
|
||||
// PATCH /beads/tasks/:id — edit task fields (title/priority/assignee/status/
|
||||
// labels). Only provided fields are applied; at least one must be present.
|
||||
router.patch("/tasks/:id", async (req: Request, res: Response) => {
|
||||
const id = cleanId(req.params.id);
|
||||
if (!id) {
|
||||
return res.status(400).json({ success: false, error: "task id is required" });
|
||||
}
|
||||
|
||||
const body = req.body as {
|
||||
title?: unknown;
|
||||
priority?: unknown;
|
||||
assignee?: unknown;
|
||||
status?: unknown;
|
||||
labels?: unknown;
|
||||
};
|
||||
|
||||
const args: string[] = ["update", id];
|
||||
let changed = false;
|
||||
|
||||
const title = cleanId(body.title);
|
||||
if (title) {
|
||||
args.push("--title", title);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (body.priority !== undefined) {
|
||||
const priority = boundedInt(body.priority, 0, 4);
|
||||
if (priority === undefined) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ success: false, error: "priority must be an integer 0-4" });
|
||||
}
|
||||
args.push("--priority", String(priority));
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (body.assignee !== undefined) {
|
||||
// An explicit empty string clears the assignee; a value sets it.
|
||||
const assignee = typeof body.assignee === "string" ? body.assignee.trim() : "";
|
||||
args.push("--assignee", assignee);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
const status = cleanId(body.status);
|
||||
if (status) {
|
||||
args.push("--status", status);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (body.labels !== undefined) {
|
||||
const labels = labelList(body.labels);
|
||||
// Replace the full label set so the update is deterministic.
|
||||
args.push("--set-labels", labels.join(","));
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: "at least one of title, priority, assignee, status, labels is required",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), args);
|
||||
res.json({ success: true, data: parseBeadsJson(stdout) });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Failed to update task",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /beads/tasks/:id/close — close a task with an audit-trail reason.
|
||||
// body: { reason?: string }
|
||||
router.post("/tasks/:id/close", async (req: Request, res: Response) => {
|
||||
const id = cleanId(req.params.id);
|
||||
if (!id) {
|
||||
return res.status(400).json({ success: false, error: "task id is required" });
|
||||
}
|
||||
|
||||
const body = req.body as { reason?: unknown };
|
||||
const reason = cleanId(body.reason) ?? "Completed";
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), [
|
||||
"close",
|
||||
id,
|
||||
"--reason",
|
||||
reason,
|
||||
]);
|
||||
res.json({ success: true, data: parseBeadsJson(stdout) });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Failed to close task",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /beads/tasks/:id/reopen — reopen a closed task (e.g. a regressed fix).
|
||||
// body: { reason?: string }
|
||||
router.post("/tasks/:id/reopen", async (req: Request, res: Response) => {
|
||||
const id = cleanId(req.params.id);
|
||||
if (!id) {
|
||||
return res.status(400).json({ success: false, error: "task id is required" });
|
||||
}
|
||||
|
||||
const body = req.body as { reason?: unknown };
|
||||
const reason = cleanId(body.reason);
|
||||
|
||||
const args: string[] = ["reopen", id];
|
||||
if (reason) {
|
||||
args.push("--reason", reason);
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), args);
|
||||
res.json({ success: true, data: parseBeadsJson(stdout) });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Failed to reopen task",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/tasks/:id — get a single task
|
||||
router.get("/tasks/:id", async (req: Request, res: Response) => {
|
||||
const { id } = req.params;
|
||||
|
||||
@ -25,28 +25,79 @@ const router = Router();
|
||||
router.use(apiKeyAuth);
|
||||
|
||||
// ============================================================================
|
||||
// In-process Context7 client
|
||||
// Per-request Context7 client
|
||||
//
|
||||
// The Context7 key is resolved per request so each tenant/user can supply their
|
||||
// own key (and consume their own rate limit) instead of every caller sharing
|
||||
// one server-wide key. Resolution order mirrors the upstream Context7 MCP
|
||||
// server's `extractApiKey`:
|
||||
// 1. Authorization: Bearer <key>
|
||||
// 2. X-Context7-Key / Context7-API-Key headers
|
||||
// then falls back to the server-wide CONTEXT7_API_KEY env var.
|
||||
//
|
||||
// Note: the product's own API auth uses the `x-api-key` header, so we do NOT
|
||||
// read `x-api-key` here (it carries the AITM key, not the Context7 key) —
|
||||
// `X-Context7-Key` is the dedicated per-request Context7 header.
|
||||
//
|
||||
// Clients are cached by key so we don't reconstruct an SDK instance on every
|
||||
// request, while still keeping per-key isolation.
|
||||
// ============================================================================
|
||||
|
||||
let _client: Context7 | null = null;
|
||||
const clientCache = new Map<string, Context7>();
|
||||
|
||||
/** Read a single header value, taking the first entry of array-valued headers. */
|
||||
function headerValue(value: string | string[] | undefined): string | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
return value[0];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Extract a Bearer token from an Authorization header, if present. */
|
||||
function extractBearerToken(authorization: string | string[] | undefined): string | undefined {
|
||||
const header = headerValue(authorization);
|
||||
if (!header) {
|
||||
return undefined;
|
||||
}
|
||||
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
|
||||
return match ? match[1].trim() : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily construct the SDK client. Returns null if no API key is configured so
|
||||
* callers can surface a clean "unavailable" state instead of crashing.
|
||||
* Resolve the effective Context7 API key for a request: a per-request key from
|
||||
* headers when supplied, otherwise the server-wide env key. Returns null when
|
||||
* no key is available at all.
|
||||
*/
|
||||
function getClient(): Context7 | null {
|
||||
if (_client) {
|
||||
return _client;
|
||||
}
|
||||
function resolveApiKey(req: Request): string | null {
|
||||
const fromRequest =
|
||||
extractBearerToken(req.headers.authorization) ||
|
||||
headerValue(req.headers["x-context7-key"]) ||
|
||||
headerValue(req.headers["context7-api-key"]);
|
||||
|
||||
const apiKey = process.env.CONTEXT7_API_KEY;
|
||||
const key = (fromRequest && fromRequest.trim()) || process.env.CONTEXT7_API_KEY;
|
||||
return key && key.trim().length > 0 ? key.trim() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build (or reuse) an SDK client for the request's effective key. Returns null
|
||||
* when no key is configured so callers can surface a clean "unavailable" state
|
||||
* instead of crashing.
|
||||
*/
|
||||
function getClient(req: Request): Context7 | null {
|
||||
const apiKey = resolveApiKey(req);
|
||||
if (!apiKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cached = clientCache.get(apiKey);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
try {
|
||||
_client = new Context7({ apiKey });
|
||||
return _client;
|
||||
const client = new Context7({ apiKey });
|
||||
clientCache.set(apiKey, client);
|
||||
return client;
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : String(error);
|
||||
logger.warn("context7: failed to initialise SDK client", { reason: msg });
|
||||
@ -54,10 +105,12 @@ function getClient(): Context7 | null {
|
||||
}
|
||||
}
|
||||
|
||||
function requireClient(): Context7 {
|
||||
const client = getClient();
|
||||
function requireClient(req: Request): Context7 {
|
||||
const client = getClient(req);
|
||||
if (!client) {
|
||||
throw new Error("Context7 not configured: set CONTEXT7_API_KEY");
|
||||
throw new Error(
|
||||
"Context7 not configured: provide an X-Context7-Key header or set CONTEXT7_API_KEY"
|
||||
);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
@ -84,11 +137,11 @@ const searchQuerySchema = z.object({
|
||||
|
||||
router.get(
|
||||
"/status",
|
||||
asyncHandler(async (_req: Request, res: Response) => {
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
let available = false;
|
||||
let latencyMs: number | null = null;
|
||||
|
||||
const client = getClient();
|
||||
const client = getClient(req);
|
||||
if (client) {
|
||||
const start = Date.now();
|
||||
try {
|
||||
@ -135,7 +188,7 @@ router.get(
|
||||
const { q } = parsed.data;
|
||||
|
||||
logger.info("context7: search", { query: q });
|
||||
const libraries: Library[] = await requireClient().searchLibrary(q, q, {
|
||||
const libraries: Library[] = await requireClient(req).searchLibrary(q, q, {
|
||||
type: "json",
|
||||
});
|
||||
|
||||
@ -168,7 +221,7 @@ router.get(
|
||||
|
||||
logger.info("context7: get library docs", { libraryId: id, version, topic, tokens });
|
||||
|
||||
const docs: Documentation[] = await requireClient().getContext(topic, id, {
|
||||
const docs: Documentation[] = await requireClient(req).getContext(topic, id, {
|
||||
type: "json",
|
||||
});
|
||||
|
||||
@ -206,7 +259,7 @@ router.get(
|
||||
// The SDK requires a non-empty libraryName; fall back to the query (or a
|
||||
// broad term) so a bare /libraries listing still returns results.
|
||||
const libraryName = q || "library";
|
||||
const libraries: Library[] = await requireClient().searchLibrary(
|
||||
const libraries: Library[] = await requireClient(req).searchLibrary(
|
||||
q || "popular libraries",
|
||||
libraryName,
|
||||
{ type: "json" }
|
||||
|
||||
@ -19,6 +19,7 @@ import {
|
||||
getApiRoutes,
|
||||
getDependencyGraph,
|
||||
searchSymbols,
|
||||
detectChanges,
|
||||
} from "../services/gitNexusService.js";
|
||||
|
||||
const router = Router();
|
||||
@ -58,6 +59,18 @@ const symbolQuerySchema = workspaceQuerySchema.extend({
|
||||
.max(500, "query must be 500 characters or less"),
|
||||
});
|
||||
|
||||
const detectChangesBodySchema = z
|
||||
.object({
|
||||
scope: z.enum(["unstaged", "staged", "all", "compare"]).default("unstaged"),
|
||||
baseRef: z.string().min(1).max(255).optional(),
|
||||
worktree: z.string().min(1).max(2048).optional(),
|
||||
repo: z.string().min(1).max(2048).optional(),
|
||||
})
|
||||
.refine((v) => v.scope !== "compare" || (v.baseRef && v.baseRef.length > 0), {
|
||||
message: "baseRef is required when scope is 'compare'",
|
||||
path: ["baseRef"],
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// GET /gitnexus/status
|
||||
// ============================================================================
|
||||
@ -121,6 +134,32 @@ router.post(
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// POST /gitnexus/detect-changes
|
||||
// Map a git diff (uncommitted/staged/compare) to affected processes + risk.
|
||||
// ============================================================================
|
||||
|
||||
router.post(
|
||||
"/detect-changes",
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const parsed = detectChangesBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
const first = parsed.error.errors[0];
|
||||
throw Errors.invalidParameter(
|
||||
first?.path.join(".") || "body",
|
||||
first?.message ?? "Invalid request body"
|
||||
);
|
||||
}
|
||||
|
||||
const { scope, baseRef, worktree, repo } = parsed.data;
|
||||
|
||||
logger.info("gitnexus: detectChanges", { scope, baseRef, repo });
|
||||
const data = await detectChanges({ scope, baseRef, worktree, repo });
|
||||
|
||||
return res.json({ success: true, data });
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// GET /gitnexus/routes
|
||||
// ============================================================================
|
||||
|
||||
@ -59,6 +59,7 @@ const METHOD_ALIASES: Readonly<Record<string, string>> = {
|
||||
gn_dep_graph: "cypher",
|
||||
gn_symbol_search: "query",
|
||||
gn_ping: "list_repos",
|
||||
gn_detect_changes: "detect_changes",
|
||||
// Bare aliases (idempotent passthrough).
|
||||
context: "context",
|
||||
impact: "impact",
|
||||
@ -66,6 +67,7 @@ const METHOD_ALIASES: Readonly<Record<string, string>> = {
|
||||
dep_graph: "cypher",
|
||||
symbol_search: "query",
|
||||
ping: "list_repos",
|
||||
detect_changes: "detect_changes",
|
||||
};
|
||||
|
||||
function resolveToolName(method: string): string {
|
||||
@ -115,6 +117,38 @@ export interface Symbol {
|
||||
exported: boolean;
|
||||
}
|
||||
|
||||
/** Which set of git changes to analyse for {@link detectChanges}. */
|
||||
export type ChangeScope = "unstaged" | "staged" | "all" | "compare";
|
||||
|
||||
export interface DetectChangesOptions {
|
||||
/** Which changes to analyse. Defaults to "unstaged". */
|
||||
scope?: ChangeScope;
|
||||
/** Base ref for the "compare" scope (e.g. "main"). */
|
||||
baseRef?: string;
|
||||
/** Absolute path to a linked git worktree when changes live there. */
|
||||
worktree?: string;
|
||||
/** Repository name/path; omit when a single repo is indexed. */
|
||||
repo?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of mapping a git diff to its blast radius. The GitNexus backend may
|
||||
* return additional fields; the structured ones below are normalised, and the
|
||||
* full payload is preserved under {@link ChangeAnalysis.raw}.
|
||||
*/
|
||||
export interface ChangeAnalysis {
|
||||
/** Symbols touched by the diff (free-form strings as reported by the engine). */
|
||||
changedSymbols: string[];
|
||||
/** Execution flows / processes affected by the changed symbols. */
|
||||
affectedProcesses: string[];
|
||||
/** Risk classification of the change set, when the engine provides one. */
|
||||
riskLevel: string | null;
|
||||
/** Human-readable risk/summary text, when provided. */
|
||||
summary: string | null;
|
||||
/** The unnormalised backend payload for callers that need full detail. */
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Core transport — in-process dispatch (drop-in replacement for the old
|
||||
// JSON-RPC `callGitNexus`). Same signature and same error-prefix contract
|
||||
@ -351,6 +385,79 @@ export async function searchSymbols(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a git diff (uncommitted, staged, or compared against a base ref) to the
|
||||
* processes it affects and an overall risk summary — the "blast radius" signal
|
||||
* AITM needs when an agent checkpoints or opens a PR.
|
||||
*
|
||||
* Delegates to the GitNexus `detect_changes` tool and normalises its response
|
||||
* into {@link ChangeAnalysis}. Returns safe empty defaults (with the raw
|
||||
* payload preserved) when the backend returns an unexpected shape.
|
||||
*/
|
||||
export async function detectChanges(
|
||||
options: DetectChangesOptions = {}
|
||||
): Promise<ChangeAnalysis> {
|
||||
const params: Record<string, unknown> = {
|
||||
scope: options.scope ?? "unstaged",
|
||||
};
|
||||
if (options.baseRef) {
|
||||
params["base_ref"] = options.baseRef;
|
||||
}
|
||||
if (options.worktree) {
|
||||
params["worktree"] = options.worktree;
|
||||
}
|
||||
if (options.repo) {
|
||||
params["repo"] = options.repo;
|
||||
}
|
||||
|
||||
const result = await callGitNexus("gn_detect_changes", params);
|
||||
|
||||
const empty: ChangeAnalysis = {
|
||||
changedSymbols: [],
|
||||
affectedProcesses: [],
|
||||
riskLevel: null,
|
||||
summary: null,
|
||||
raw: result,
|
||||
};
|
||||
|
||||
if (!isRecord(result)) {
|
||||
logger.error("gitNexus: unexpected shape from detect_changes", undefined, {
|
||||
result: String(result),
|
||||
});
|
||||
return empty;
|
||||
}
|
||||
|
||||
const asStringArray = (value: unknown): string[] =>
|
||||
Array.isArray(value)
|
||||
? value.map((v) =>
|
||||
typeof v === "string"
|
||||
? v
|
||||
: isRecord(v) && typeof v["name"] === "string"
|
||||
? (v["name"] as string)
|
||||
: String(v)
|
||||
)
|
||||
: [];
|
||||
|
||||
const changedSymbols = asStringArray(
|
||||
result["changedSymbols"] ?? result["changed_symbols"] ?? result["symbols"]
|
||||
);
|
||||
const affectedProcesses = asStringArray(
|
||||
result["affectedProcesses"] ?? result["affected_processes"] ?? result["processes"]
|
||||
);
|
||||
const riskLevel =
|
||||
typeof result["riskLevel"] === "string"
|
||||
? (result["riskLevel"] as string)
|
||||
: typeof result["risk_level"] === "string"
|
||||
? (result["risk_level"] as string)
|
||||
: typeof result["risk"] === "string"
|
||||
? (result["risk"] as string)
|
||||
: null;
|
||||
const summary =
|
||||
typeof result["summary"] === "string" ? (result["summary"] as string) : null;
|
||||
|
||||
return { changedSymbols, affectedProcesses, riskLevel, summary, raw: result };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Availability probe
|
||||
// ============================================================================
|
||||
|
||||
@ -14,14 +14,19 @@
|
||||
*/
|
||||
|
||||
import crypto from "crypto";
|
||||
import { execFile } from "child_process";
|
||||
import { promisify } from "util";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import {
|
||||
getEmbeddingService,
|
||||
type EmbeddingService,
|
||||
} from "./embeddings.js";
|
||||
import { resolveBeadsBinary } from "./engineManager.js";
|
||||
import type { SavedContextSource } from "../db/schema.js";
|
||||
import { logger } from "../lib/monitoring.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Resolve where ingested memory should be persisted. Both fields are required
|
||||
* by the saved_contexts schema (NOT NULL FKs to users/projects). Callers that
|
||||
@ -267,3 +272,100 @@ export async function ingestLibraryDoc(
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Beads dependency-graph helpers
|
||||
//
|
||||
// Thin wrappers over the `bd` binary (resolved via engineManager) that expose
|
||||
// the dependency DAG operations the multi-agent orchestration relies on:
|
||||
// `bd dep add`, `bd dep list`, and `bd dep cycles`. These return the parsed
|
||||
// `--json` payload from the binary. Kept here (next to ingestTask) so all
|
||||
// beads-backed memory operations live in one service.
|
||||
// ============================================================================
|
||||
|
||||
function beadsBinary(): string {
|
||||
return resolveBeadsBinary().path ?? "bd";
|
||||
}
|
||||
|
||||
function parseBeadsJson(stdout: string): unknown {
|
||||
const trimmed = stdout.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(trimmed) as unknown;
|
||||
} catch {
|
||||
// Some `bd` mutations emit a human-readable confirmation rather than JSON;
|
||||
// surface the raw message instead of throwing.
|
||||
return { message: trimmed };
|
||||
}
|
||||
}
|
||||
|
||||
/** Allowed beads dependency edge types (mirrors `bd dep add -t`). */
|
||||
export type BeadsDependencyType =
|
||||
| "blocks"
|
||||
| "tracks"
|
||||
| "related"
|
||||
| "parent-child"
|
||||
| "discovered-from"
|
||||
| "until"
|
||||
| "caused-by"
|
||||
| "validates"
|
||||
| "relates-to"
|
||||
| "supersedes";
|
||||
|
||||
const VALID_DEP_TYPES: ReadonlySet<string> = new Set([
|
||||
"blocks",
|
||||
"tracks",
|
||||
"related",
|
||||
"parent-child",
|
||||
"discovered-from",
|
||||
"until",
|
||||
"caused-by",
|
||||
"validates",
|
||||
"relates-to",
|
||||
"supersedes",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Add a dependency edge: `blocked` depends on `blocker`. Runs the per-edge
|
||||
* cycle check (the binary refuses and errors if the edge would create a cycle).
|
||||
* Throws on failure (e.g. unknown id, or a would-be cycle) so the caller can
|
||||
* map it to an HTTP status.
|
||||
*/
|
||||
export async function addDependency(
|
||||
blocked: string,
|
||||
blocker: string,
|
||||
type?: string
|
||||
): Promise<unknown> {
|
||||
const args = ["dep", "add", blocked, blocker];
|
||||
if (type && VALID_DEP_TYPES.has(type)) {
|
||||
args.push("--type", type);
|
||||
}
|
||||
args.push("--json");
|
||||
|
||||
const { stdout } = await execFileAsync(beadsBinary(), args);
|
||||
return parseBeadsJson(stdout);
|
||||
}
|
||||
|
||||
/**
|
||||
* List dependencies for a task. `direction='down'` (default) returns what the
|
||||
* task depends on (its blockers); `direction='up'` returns what depends on it.
|
||||
*/
|
||||
export async function listDependencies(
|
||||
id: string,
|
||||
direction: "up" | "down" = "down"
|
||||
): Promise<unknown> {
|
||||
const args = ["dep", "list", id, `--direction=${direction}`, "--json"];
|
||||
const { stdout } = await execFileAsync(beadsBinary(), args);
|
||||
return parseBeadsJson(stdout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect dependency cycles across the whole graph. Returns the parsed analysis
|
||||
* from `bd dep cycles --json`.
|
||||
*/
|
||||
export async function findDependencyCycles(): Promise<unknown> {
|
||||
const { stdout } = await execFileAsync(beadsBinary(), ["dep", "cycles", "--json"]);
|
||||
return parseBeadsJson(stdout);
|
||||
}
|
||||
|
||||
@ -10,6 +10,7 @@ import {
|
||||
getDisabledTools,
|
||||
getToolAvailability,
|
||||
getUnknownDisabledTools,
|
||||
getProtectedEssentialTools,
|
||||
} from './lib/stable-tools.js';
|
||||
import {
|
||||
formatHiddenFamiliesWarning,
|
||||
@ -138,6 +139,13 @@ if (unknownDisabledTools.length > 0) {
|
||||
console.warn(`Unknown tools in DISABLED_TOOLS: ${unknownDisabledTools.join(', ')}`);
|
||||
}
|
||||
|
||||
const protectedEssentialTools = getProtectedEssentialTools(TOOL_SELECTION_OPTIONS);
|
||||
if (protectedEssentialTools.length > 0) {
|
||||
console.warn(
|
||||
`Cannot disable essential tools (ignored in DISABLED_TOOLS): ${protectedEssentialTools.join(', ')}`
|
||||
);
|
||||
}
|
||||
|
||||
function ensureLibLoaded() {
|
||||
if (!lib) {
|
||||
throw new Error('AITM core library not loaded yet');
|
||||
|
||||
@ -52,6 +52,45 @@ async function beadsPatch(
|
||||
return jsonResponse(data);
|
||||
}
|
||||
|
||||
async function beadsPut(
|
||||
endpoint: string,
|
||||
body?: unknown
|
||||
): Promise<ReturnType<typeof jsonResponse>> {
|
||||
const data = await aitmApiRequest(LABEL, `/beads${endpoint}`, {
|
||||
method: 'PUT',
|
||||
body,
|
||||
});
|
||||
return jsonResponse(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a query-string from a set of params, skipping undefined/empty values
|
||||
* and joining array values with commas. Returns "" when no params are set.
|
||||
*/
|
||||
function buildQuery(
|
||||
params: Readonly<Record<string, string | number | boolean | string[] | undefined>>
|
||||
): string {
|
||||
const search = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
const joined = value.map((item) => item.trim()).filter(Boolean).join(',');
|
||||
if (joined.length > 0) {
|
||||
search.set(key, joined);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const str = String(value).trim();
|
||||
if (str.length > 0) {
|
||||
search.set(key, str);
|
||||
}
|
||||
}
|
||||
const qs = search.toString();
|
||||
return qs.length > 0 ? `?${qs}` : '';
|
||||
}
|
||||
|
||||
export const registerBeadsTools = createToolRegistrar([
|
||||
defineTool({
|
||||
name: 'beads_list_tasks',
|
||||
@ -79,7 +118,7 @@ export const registerBeadsTools = createToolRegistrar([
|
||||
id: z.string().describe('The ID of the task to mark as ready'),
|
||||
},
|
||||
annotations: idempotentMutationAnnotations(),
|
||||
run: async (args) => beadsPatch(`/tasks/${args.id}/ready`),
|
||||
run: async (args) => beadsPut(`/tasks/${encodeURIComponent(args.id)}/ready`),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
@ -89,7 +128,7 @@ export const registerBeadsTools = createToolRegistrar([
|
||||
id: z.string().describe('The ID of the task to mark as done'),
|
||||
},
|
||||
annotations: idempotentMutationAnnotations(),
|
||||
run: async (args) => beadsPatch(`/tasks/${args.id}/done`),
|
||||
run: async (args) => beadsPut(`/tasks/${encodeURIComponent(args.id)}/done`),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
@ -99,7 +138,176 @@ export const registerBeadsTools = createToolRegistrar([
|
||||
id: z.string().describe('The ID of the task to retrieve'),
|
||||
},
|
||||
annotations: readOnlyAnnotations(),
|
||||
run: async (args) => beadsGet(`/tasks/${args.id}`),
|
||||
run: async (args) => beadsGet(`/tasks/${encodeURIComponent(args.id)}`),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_ready',
|
||||
description:
|
||||
'Query the Beads work queue for tasks that are unblocked and ready to work on right now (all dependencies satisfied). This is the core "what can I work on next?" primitive for autonomous agents. Supports filtering by priority, assignee, labels, and a result limit.',
|
||||
schema: {
|
||||
priority: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(4)
|
||||
.optional()
|
||||
.describe('Filter to a single priority level (0 = highest, 4 = lowest)'),
|
||||
assignee: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Filter to tasks assigned to this assignee'),
|
||||
unassigned: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe('When true, return only tasks with no assignee'),
|
||||
labels: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe('AND filter: task must have ALL of these labels'),
|
||||
labelsAny: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe('OR filter: task must have AT LEAST ONE of these labels'),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.optional()
|
||||
.describe('Maximum number of ready tasks to return (1-100)'),
|
||||
sort: z
|
||||
.enum(['priority', 'hybrid', 'oldest'])
|
||||
.optional()
|
||||
.describe('Sort policy for the returned ready tasks'),
|
||||
},
|
||||
annotations: readOnlyAnnotations(),
|
||||
run: async (args) =>
|
||||
beadsGet(
|
||||
`/ready${buildQuery({
|
||||
priority: args.priority,
|
||||
assignee: args.assignee,
|
||||
unassigned: args.unassigned,
|
||||
labels: args.labels,
|
||||
labelsAny: args.labelsAny,
|
||||
limit: args.limit,
|
||||
sort: args.sort,
|
||||
})}`
|
||||
),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_blocked',
|
||||
description:
|
||||
'List Beads tasks that are currently blocked, along with the dependencies blocking each one. Use this to see what is stuck in the DAG and why, so an operator or agent can unblock autonomous work.',
|
||||
schema: {},
|
||||
annotations: readOnlyAnnotations(),
|
||||
run: async () => beadsGet('/blocked'),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_stats',
|
||||
description:
|
||||
'Get aggregate statistics for the Beads DAG: totals by state (open, in_progress, closed, blocked), the count of ready tasks, and the average lead time. A cheap, high-signal health check for an orchestrator or dashboard.',
|
||||
schema: {},
|
||||
annotations: readOnlyAnnotations(),
|
||||
run: async () => beadsGet('/stats'),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_add_dependency',
|
||||
description:
|
||||
'Add a dependency edge from one Beads task to another after creation. Use this when an agent discovers a blocker mid-task (a discovered-from edge) or otherwise needs to refine the DAG. The dependency type defaults to "blocks".',
|
||||
schema: {
|
||||
id: z.string().describe('The task that has the dependency'),
|
||||
dependsOn: z
|
||||
.string()
|
||||
.describe('The task that must be resolved first (the dependency)'),
|
||||
type: z
|
||||
.enum(['blocks', 'related', 'parent-child', 'discovered-from'])
|
||||
.optional()
|
||||
.describe('The kind of dependency edge to create (default: blocks)'),
|
||||
},
|
||||
annotations: mutatingAnnotations(),
|
||||
run: async (args) =>
|
||||
beadsPost(`/tasks/${encodeURIComponent(args.id)}/deps`, {
|
||||
dependsOn: args.dependsOn,
|
||||
type: args.type,
|
||||
}),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_update_task',
|
||||
description:
|
||||
'Update editable fields of an existing Beads task: title, priority, assignee, status, and/or labels. Only the fields you provide are changed; at least one field is required.',
|
||||
schema: {
|
||||
id: z.string().describe('The ID of the task to update'),
|
||||
title: z.string().optional().describe('New title for the task'),
|
||||
priority: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(4)
|
||||
.optional()
|
||||
.describe('New priority (0 = highest, 4 = lowest)'),
|
||||
assignee: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('New assignee (pass an empty string to clear the assignee)'),
|
||||
status: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('New status (e.g. open, in_progress, blocked, deferred, closed)'),
|
||||
labels: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe('Replace the full set of labels with this list'),
|
||||
},
|
||||
annotations: mutatingAnnotations(),
|
||||
run: async (args) =>
|
||||
beadsPatch(`/tasks/${encodeURIComponent(args.id)}`, {
|
||||
title: args.title,
|
||||
priority: args.priority,
|
||||
assignee: args.assignee,
|
||||
status: args.status,
|
||||
labels: args.labels,
|
||||
}),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_close_task',
|
||||
description:
|
||||
'Close (complete) a Beads task with an optional human-readable reason that is recorded for the audit trail. Use this to explain why an agent finished or abandoned the work.',
|
||||
schema: {
|
||||
id: z.string().describe('The ID of the task to close'),
|
||||
reason: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Why the task is being closed (default: "Completed")'),
|
||||
},
|
||||
annotations: idempotentMutationAnnotations(),
|
||||
run: async (args) =>
|
||||
beadsPost(`/tasks/${encodeURIComponent(args.id)}/close`, {
|
||||
reason: args.reason,
|
||||
}),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_reopen_task',
|
||||
description:
|
||||
'Reopen a previously closed Beads task, for example when a fix regresses and the work must be revisited. An optional reason is recorded.',
|
||||
schema: {
|
||||
id: z.string().describe('The ID of the task to reopen'),
|
||||
reason: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Why the task is being reopened'),
|
||||
},
|
||||
annotations: idempotentMutationAnnotations(),
|
||||
run: async (args) =>
|
||||
beadsPost(`/tasks/${encodeURIComponent(args.id)}/reopen`, {
|
||||
reason: args.reason,
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
|
||||
|
||||
@ -86,6 +86,10 @@ model User {
|
||||
emailVerified Boolean @default(false)
|
||||
verified Boolean @default(false)
|
||||
isPrivate Boolean @default(false)
|
||||
// Viewer opt-in for author-self-labeled adult content. When false (default),
|
||||
// posts an author marked as adult (sexual/nudity/porn) are hidden from this
|
||||
// user's feed. See services/selfLabels.ts.
|
||||
adultContentEnabled Boolean @default(false)
|
||||
isBanned Boolean @default(false)
|
||||
bannedAt DateTime?
|
||||
bannedReason String?
|
||||
@ -373,6 +377,13 @@ model Post {
|
||||
isArchived Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
|
||||
// Author self-labeling / content warnings (ported from Bluesky SELF_LABELS).
|
||||
// Voluntary, author-applied sensitivity tags. Each maps to a hide-or-warn
|
||||
// behavior in the feed pipeline. Adult labels (sexual, nudity, porn) hide by
|
||||
// default; graphic-media and spoiler warn (blur) by default.
|
||||
selfLabels String[] @default([]) // e.g. ["sexual", "graphic-media", "spoiler"]
|
||||
contentWarning String? // optional free-text warning shown alongside the label
|
||||
|
||||
// Optional geotagging for map / nearby discovery
|
||||
location String?
|
||||
latitude Float?
|
||||
|
||||
@ -9,6 +9,23 @@ import logger from '../utils/logger'
|
||||
import { asyncHandler, Errors, ApiError } from '../middleware/errorHandler'
|
||||
import { getCachedProfile, setCachedProfile, setCachedRepo } from '../utils/githubProfileCache'
|
||||
import { fetchGitHubTrending } from '../services/ghSocialBridge'
|
||||
import { GitHubService } from '../services/githubService'
|
||||
import { createNotification } from '../services/notificationService'
|
||||
|
||||
/**
|
||||
* Resolve the authenticated user's stored GitHub OAuth token, or throw a
|
||||
* 400 telling them to connect GitHub. Shared by all two-way GitHub actions.
|
||||
*/
|
||||
async function requireUserGitHubToken(userId: string): Promise<string> {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubAccessToken: true },
|
||||
})
|
||||
if (!user?.githubAccessToken) {
|
||||
throw Errors.badRequest('GitHub account not linked. Connect GitHub in settings first.')
|
||||
}
|
||||
return user.githubAccessToken
|
||||
}
|
||||
|
||||
export const githubController = {
|
||||
// Existing endpoints
|
||||
@ -677,4 +694,127 @@ export const githubController = {
|
||||
|
||||
res.json({ message: 'Activity cache cleared successfully' })
|
||||
}),
|
||||
|
||||
// ============================================
|
||||
// TWO-WAY GITHUB ACTIONS (write-back via user OAuth token)
|
||||
// Ported from gh-social: star/unstar a repo and follow/unfollow a user on
|
||||
// GitHub.com, plus live "have I starred / am I following" status checks.
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Star a repository on GitHub.com using the user's OAuth token.
|
||||
* PUT /api/v1/github/star/:owner/:repo
|
||||
*/
|
||||
starRepo: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const { owner, repo } = req.params
|
||||
const userId = req.userId!
|
||||
const token = await requireUserGitHubToken(userId)
|
||||
|
||||
const github = new GitHubService(token)
|
||||
const fullName = `${owner}/${repo}`
|
||||
const starred = await github.starRepo(fullName)
|
||||
|
||||
res.json({ message: 'Repository starred on GitHub', repository: fullName, starred })
|
||||
}),
|
||||
|
||||
/**
|
||||
* Remove a star from a repository on GitHub.com.
|
||||
* DELETE /api/v1/github/star/:owner/:repo
|
||||
*/
|
||||
unstarRepo: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const { owner, repo } = req.params
|
||||
const userId = req.userId!
|
||||
const token = await requireUserGitHubToken(userId)
|
||||
|
||||
const github = new GitHubService(token)
|
||||
const fullName = `${owner}/${repo}`
|
||||
const starred = await github.unstarRepo(fullName)
|
||||
|
||||
res.json({ message: 'Repository unstarred on GitHub', repository: fullName, starred })
|
||||
}),
|
||||
|
||||
/**
|
||||
* Live check: has the user starred this repo on GitHub.com?
|
||||
* GET /api/v1/github/star/:owner/:repo
|
||||
*/
|
||||
getStarStatus: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const { owner, repo } = req.params
|
||||
const userId = req.userId!
|
||||
const token = await requireUserGitHubToken(userId)
|
||||
|
||||
const github = new GitHubService(token)
|
||||
const fullName = `${owner}/${repo}`
|
||||
const starred = await github.hasStarred(fullName)
|
||||
|
||||
res.json({ repository: fullName, starred })
|
||||
}),
|
||||
|
||||
/**
|
||||
* Follow a GitHub user on GitHub.com using the user's OAuth token.
|
||||
* When the followed GitHub user maps to a Gitgram account, send them an
|
||||
* in-app notification (mirrors gh-social's follow notification).
|
||||
* PUT /api/v1/github/follow-user/:username
|
||||
*/
|
||||
followGitHubUser: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const { username } = req.params
|
||||
const userId = req.userId!
|
||||
const token = await requireUserGitHubToken(userId)
|
||||
|
||||
const github = new GitHubService(token)
|
||||
const following = await github.followUser(username)
|
||||
|
||||
// Notify the target if they have a Gitgram account linked to this GitHub login.
|
||||
const actor = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { username: true },
|
||||
})
|
||||
const target = await prisma.user.findFirst({
|
||||
where: { githubUsername: { equals: username, mode: 'insensitive' } },
|
||||
select: { id: true },
|
||||
})
|
||||
if (target && target.id !== userId && actor?.username) {
|
||||
try {
|
||||
await createNotification(
|
||||
target.id,
|
||||
'FOLLOW',
|
||||
`${actor.username} followed you on GitHub`,
|
||||
userId
|
||||
)
|
||||
} catch (notifyError: unknown) {
|
||||
logger.error('Failed to send GitHub follow notification:', notifyError)
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ message: 'User followed on GitHub', username, following })
|
||||
}),
|
||||
|
||||
/**
|
||||
* Unfollow a GitHub user on GitHub.com.
|
||||
* DELETE /api/v1/github/follow-user/:username
|
||||
*/
|
||||
unfollowGitHubUser: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const { username } = req.params
|
||||
const userId = req.userId!
|
||||
const token = await requireUserGitHubToken(userId)
|
||||
|
||||
const github = new GitHubService(token)
|
||||
const following = await github.unfollowUser(username)
|
||||
|
||||
res.json({ message: 'User unfollowed on GitHub', username, following })
|
||||
}),
|
||||
|
||||
/**
|
||||
* Live check: is the user following this GitHub user?
|
||||
* GET /api/v1/github/follow-user/:username
|
||||
*/
|
||||
getFollowUserStatus: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const { username } = req.params
|
||||
const userId = req.userId!
|
||||
const token = await requireUserGitHubToken(userId)
|
||||
|
||||
const github = new GitHubService(token)
|
||||
const following = await github.isFollowing(username)
|
||||
|
||||
res.json({ username, following })
|
||||
}),
|
||||
}
|
||||
|
||||
@ -13,6 +13,7 @@ import { validateCheckpoint, buildCheckpointRef, formatCheckpointDescription } f
|
||||
import type { AitmCheckpointRef } from '../services/aitmService';
|
||||
import { getCachedComments, setCachedComments, invalidateCommentCache } from '../utils/commentCache';
|
||||
import { tuneFeed, type TunableFeedItem } from '../services/feedTuner';
|
||||
import { normalizeSelfLabels, decideSelfLabel } from '../services/selfLabels';
|
||||
|
||||
export const createPost = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const {
|
||||
@ -29,6 +30,8 @@ export const createPost = asyncHandler(async (req: AuthRequest, res: Response) =
|
||||
diffSummary,
|
||||
changedFiles,
|
||||
changeStoryTitle,
|
||||
selfLabels,
|
||||
contentWarning,
|
||||
} = req.body;
|
||||
const account = await prisma.account.findFirst({ where: { userId: req.userId } });
|
||||
if (!account) throw Errors.notFound('Account');
|
||||
@ -103,6 +106,13 @@ export const createPost = asyncHandler(async (req: AuthRequest, res: Response) =
|
||||
|
||||
const effectiveType = checkpointId ? 'CHANGE_STORY' : type;
|
||||
|
||||
// Author self-labeling / content warnings (voluntary sensitivity tags).
|
||||
const normalizedSelfLabels = normalizeSelfLabels(selfLabels);
|
||||
const normalizedContentWarning =
|
||||
typeof contentWarning === 'string' && contentWarning.trim().length > 0
|
||||
? contentWarning.trim().slice(0, 300)
|
||||
: null;
|
||||
|
||||
// Validate and resolve AITM checkpoint metadata (optional — allows post even if AITM is down)
|
||||
let resolvedAitmCheckpointRef: AitmCheckpointRef | null = null;
|
||||
const effectiveAitmCheckpointId = typeof checkpointId === 'string' && checkpointId.trim() ? checkpointId.trim() : null;
|
||||
@ -128,6 +138,8 @@ export const createPost = asyncHandler(async (req: AuthRequest, res: Response) =
|
||||
aitmProjectId: effectiveAitmProjectId,
|
||||
aitmCheckpointRef: resolvedAitmCheckpointRef ?? undefined,
|
||||
type: effectiveType,
|
||||
selfLabels: normalizedSelfLabels,
|
||||
contentWarning: normalizedContentWarning,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
@ -197,13 +209,41 @@ export const createPost = asyncHandler(async (req: AuthRequest, res: Response) =
|
||||
res.status(201).json({ post: { ...post, linkPreviews } });
|
||||
});
|
||||
|
||||
/**
|
||||
* Derive the thread-root key for a feed post.
|
||||
*
|
||||
* Gitgram posts are flat (no native reply chain), so the closest analog to a
|
||||
* Bluesky thread is an AITM change-story progression: a run of posts about the
|
||||
* same AITM project/checkpoint. Collapsing those keeps a busy change-story from
|
||||
* flooding the following feed, surfacing its highest-ranked entry once.
|
||||
*
|
||||
* We deliberately do NOT key on `repositoryId` alone — a repository can host
|
||||
* many distinct, unrelated posts, and collapsing all of them would regress the
|
||||
* general feed. Only the AITM-project subject is treated as a thread root.
|
||||
*/
|
||||
function deriveThreadRoot(post: Record<string, unknown>): string | null {
|
||||
const aitmProjectId = post.aitmProjectId;
|
||||
if (typeof aitmProjectId === 'string' && aitmProjectId.length > 0) {
|
||||
return `aitm:${aitmProjectId}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Map a raw feed post to the minimal shape required by FeedTuner. */
|
||||
function toTunableItem(post: Record<string, unknown>): TunableFeedItem {
|
||||
const selfLabel = decideSelfLabel({
|
||||
selfLabels: (post.selfLabels as string[] | null | undefined) ?? null,
|
||||
contentWarning: (post.contentWarning as string | null | undefined) ?? null,
|
||||
});
|
||||
return {
|
||||
...(post as TunableFeedItem),
|
||||
id: post.id as string,
|
||||
type: 'post',
|
||||
authorId: (post.userId as string | null) ?? null,
|
||||
rootPostId: deriveThreadRoot(post),
|
||||
// Attach the self-label decision so the client can blur 'warn' posts and so
|
||||
// the feed can drop 'hide' posts (see applySelfLabelBehavior).
|
||||
selfLabel,
|
||||
score: (post.likesCount as number ?? 0) * 2 + (post.commentsCount as number ?? 0) * 3,
|
||||
likesCount: post.likesCount as number | undefined,
|
||||
commentsCount: post.commentsCount as number | undefined,
|
||||
@ -212,18 +252,47 @@ function toTunableItem(post: Record<string, unknown>): TunableFeedItem {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply author self-label hide/warn behavior to a tuned feed.
|
||||
*
|
||||
* `hide` items (adult content) are removed unless the viewer is the author or
|
||||
* has opted into adult content. `warn` items stay in the feed carrying their
|
||||
* `selfLabel` decision so the client can blur them behind the warning.
|
||||
*/
|
||||
function applySelfLabelBehavior(
|
||||
items: TunableFeedItem[],
|
||||
opts: { viewerId: string; adultContentEnabled: boolean }
|
||||
): TunableFeedItem[] {
|
||||
return items.filter(item => {
|
||||
const decision = item.selfLabel as ReturnType<typeof decideSelfLabel> | undefined;
|
||||
if (!decision || decision.behavior !== 'hide') return true;
|
||||
// Always show the author their own labeled post.
|
||||
if (item.authorId && item.authorId === opts.viewerId) return true;
|
||||
return opts.adultContentEnabled;
|
||||
});
|
||||
}
|
||||
|
||||
export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const userId = req.userId!;
|
||||
const { page = 1, limit = 20, cursor } = req.query;
|
||||
|
||||
// Viewer's opt-in for author-self-labeled adult content (default: hidden).
|
||||
const viewer = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { adultContentEnabled: true },
|
||||
});
|
||||
const adultContentEnabled = viewer?.adultContentEnabled ?? false;
|
||||
const labelOpts = { viewerId: userId, adultContentEnabled };
|
||||
|
||||
if (typeof cursor === 'string' && cursor.trim()) {
|
||||
const result = await FeedService.getPersonalizedFeedCursor(
|
||||
userId,
|
||||
cursor.trim(),
|
||||
Number(limit)
|
||||
);
|
||||
const tunedPosts = tuneFeed(
|
||||
(result.posts as Record<string, unknown>[]).map(toTunableItem)
|
||||
const tunedPosts = applySelfLabelBehavior(
|
||||
tuneFeed((result.posts as Record<string, unknown>[]).map(toTunableItem)),
|
||||
labelOpts
|
||||
);
|
||||
res.json({ ...result, posts: tunedPosts });
|
||||
return;
|
||||
@ -242,8 +311,9 @@ export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const tunedPosts = tuneFeed(
|
||||
(posts as Record<string, unknown>[]).map(toTunableItem)
|
||||
const tunedPosts = applySelfLabelBehavior(
|
||||
tuneFeed((posts as Record<string, unknown>[]).map(toTunableItem)),
|
||||
labelOpts
|
||||
);
|
||||
|
||||
res.json({ posts: tunedPosts, isDiscover: false });
|
||||
|
||||
@ -405,6 +405,128 @@ router.delete('/bookmark/:owner/:repo', authenticate, githubController.unbookmar
|
||||
*/
|
||||
router.get('/stats/:owner/:repo', githubController.getRepositoryStats);
|
||||
|
||||
// ============================================
|
||||
// TWO-WAY GITHUB ACTIONS (write-back via user OAuth token)
|
||||
// Ported from gh-social. Star/unstar a repo and follow/unfollow a GitHub user
|
||||
// on GitHub.com, plus live status checks. All require the user's linked GitHub
|
||||
// OAuth token (stored on the user record) and an authenticated session.
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/v1/github/star/{owner}/{repo}:
|
||||
* get:
|
||||
* summary: Check whether the authenticated user has starred a repo on GitHub
|
||||
* tags: [GitHub]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: owner
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: repo
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Star status
|
||||
* put:
|
||||
* summary: Star a repository on GitHub.com
|
||||
* tags: [GitHub]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: owner
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: repo
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Repository starred
|
||||
* delete:
|
||||
* summary: Remove a star from a repository on GitHub.com
|
||||
* tags: [GitHub]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: owner
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: repo
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Repository unstarred
|
||||
*/
|
||||
router.get('/star/:owner/:repo', authenticate, githubController.getStarStatus);
|
||||
router.put('/star/:owner/:repo', authenticate, githubController.starRepo);
|
||||
router.delete('/star/:owner/:repo', authenticate, githubController.unstarRepo);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/v1/github/follow-user/{username}:
|
||||
* get:
|
||||
* summary: Check whether the authenticated user follows a GitHub user
|
||||
* tags: [GitHub]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: username
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Follow status
|
||||
* put:
|
||||
* summary: Follow a GitHub user on GitHub.com
|
||||
* tags: [GitHub]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: username
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: User followed
|
||||
* delete:
|
||||
* summary: Unfollow a GitHub user on GitHub.com
|
||||
* tags: [GitHub]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: username
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: User unfollowed
|
||||
*/
|
||||
router.get('/follow-user/:username', authenticate, githubController.getFollowUserStatus);
|
||||
router.put('/follow-user/:username', authenticate, githubController.followGitHubUser);
|
||||
router.delete('/follow-user/:username', authenticate, githubController.unfollowGitHubUser);
|
||||
|
||||
// ============================================
|
||||
// GITHUB ACTIVITY FEED ENDPOINTS
|
||||
// ============================================
|
||||
|
||||
@ -33,6 +33,37 @@ export interface TunableFeedItem {
|
||||
type: FeedItemType;
|
||||
/** Author/owner identifier — null for system or anonymous items. */
|
||||
authorId: string | null;
|
||||
/**
|
||||
* Identifier of the conversation/thread this item belongs to.
|
||||
*
|
||||
* Ported from Bluesky's `FeedViewPostsSlice.rootUri` concept: multiple items
|
||||
* that share the same thread root collapse to a single entry (the most recent)
|
||||
* so a busy thread surfaces once instead of flooding the feed.
|
||||
*
|
||||
* In Gitgram a "thread" is the set of posts about the same subject. Callers
|
||||
* derive this from a stable subject key — typically the repository id or the
|
||||
* AITM project/checkpoint id. When absent, the item is treated as its own
|
||||
* thread root and is never collapsed.
|
||||
*/
|
||||
rootPostId?: string | null;
|
||||
/**
|
||||
* Explicit thread identifier. When both `threadId` and `rootPostId` are set,
|
||||
* `threadId` wins. Provided as a convenience alias so callers that already
|
||||
* model threads can pass through without reshaping the field name.
|
||||
*/
|
||||
threadId?: string | null;
|
||||
/**
|
||||
* When true, this item belongs to a thread the viewer has muted and should be
|
||||
* dropped by `removeMutedThreads`. The backend has no thread-mute store yet,
|
||||
* so callers that lack mute data simply leave this undefined.
|
||||
*/
|
||||
isThreadMuted?: boolean;
|
||||
/**
|
||||
* When true, this item is a reply whose parent/root context could not be
|
||||
* resolved (an "orphan"). `removeOrphans` drops these so the feed never shows
|
||||
* a dangling reply with no visible context.
|
||||
*/
|
||||
isOrphan?: boolean;
|
||||
/** Pre-computed feed ranking score (higher = better). */
|
||||
score: number;
|
||||
/** Optional trending score override; computed on-the-fly when absent. */
|
||||
@ -113,6 +144,28 @@ export interface FeedTunerOptions {
|
||||
* @default []
|
||||
*/
|
||||
sponsoredItems?: ReadonlyArray<SponsoredItem>;
|
||||
|
||||
/**
|
||||
* When true, collapse items that share the same thread root so each
|
||||
* conversation appears at most once (its highest-ranked entry survives).
|
||||
* Ported from Bluesky's `FeedTuner.dedupThreads`.
|
||||
* @default true
|
||||
*/
|
||||
dedupeThreads?: boolean;
|
||||
|
||||
/**
|
||||
* When true, drop items flagged `isThreadMuted`.
|
||||
* Ported from Bluesky's `FeedTuner.removeMutedThreads`.
|
||||
* @default true
|
||||
*/
|
||||
removeMutedThreads?: boolean;
|
||||
|
||||
/**
|
||||
* When true, drop items flagged `isOrphan` (replies whose context could not
|
||||
* be resolved). Ported from Bluesky's `FeedTuner.removeOrphans`.
|
||||
* @default true
|
||||
*/
|
||||
removeOrphans?: boolean;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -126,6 +179,9 @@ const DEFAULT_TRENDING_BOOST_THRESHOLD = 50;
|
||||
const DEFAULT_TRENDING_BOOST_MULTIPLIER = 1.5;
|
||||
const DEFAULT_DIVERSITY_PENALTY_AFTER = 3;
|
||||
const DEFAULT_DIVERSITY_PENALTY_MULTIPLIER = 0.5;
|
||||
const DEFAULT_DEDUPE_THREADS = true;
|
||||
const DEFAULT_REMOVE_MUTED_THREADS = true;
|
||||
const DEFAULT_REMOVE_ORPHANS = true;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helpers (pure functions — no side-effects)
|
||||
@ -383,6 +439,64 @@ function deduplicateById(items: ReadonlyArray<TunableFeedItem>): TunableFeedItem
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the thread-root key for an item.
|
||||
*
|
||||
* `threadId` takes precedence over `rootPostId`. When neither is present the
|
||||
* item is its own thread root (it can never collapse another item) and we
|
||||
* return `null` to signal "no shared thread".
|
||||
*/
|
||||
function threadRootKey(item: TunableFeedItem): string | null {
|
||||
if (typeof item.threadId === 'string' && item.threadId.length > 0) {
|
||||
return item.threadId;
|
||||
}
|
||||
if (typeof item.rootPostId === 'string' && item.rootPostId.length > 0) {
|
||||
return item.rootPostId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapse items that share the same thread root so each conversation surfaces
|
||||
* once. The FIRST item encountered for a given root wins; later items sharing
|
||||
* that root are dropped.
|
||||
*
|
||||
* Callers are expected to pass items already ordered so the "winning" entry per
|
||||
* thread (e.g. the most recent / highest-ranked) appears first. The tuner runs
|
||||
* this AFTER `sortByScore`, so the highest-scoring entry of each thread is kept,
|
||||
* mirroring Bluesky's "you only see the most recent reply" behaviour for the
|
||||
* following feed.
|
||||
*
|
||||
* Items without a thread root (see `threadRootKey`) are always preserved.
|
||||
* Returns a new array — input is not modified.
|
||||
*/
|
||||
function deduplicateByThreadRoot(items: ReadonlyArray<TunableFeedItem>): TunableFeedItem[] {
|
||||
const seenRoots = new Set<string>();
|
||||
return items.filter(item => {
|
||||
const root = threadRootKey(item);
|
||||
if (root === null) return true; // standalone item, never collapsed
|
||||
if (seenRoots.has(root)) return false;
|
||||
seenRoots.add(root);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop items flagged `isThreadMuted`. Ported from Bluesky's
|
||||
* `FeedTuner.removeMutedThreads`. Returns a new array.
|
||||
*/
|
||||
function dropMutedThreads(items: ReadonlyArray<TunableFeedItem>): TunableFeedItem[] {
|
||||
return items.filter(item => item.isThreadMuted !== true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop items flagged `isOrphan`. Ported from Bluesky's
|
||||
* `FeedTuner.removeOrphans`. Returns a new array.
|
||||
*/
|
||||
function dropOrphans(items: ReadonlyArray<TunableFeedItem>): TunableFeedItem[] {
|
||||
return items.filter(item => item.isOrphan !== true);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FeedTuner class
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -409,6 +523,9 @@ export class FeedTuner {
|
||||
diversityPenaltyAfter: options.diversityPenaltyAfter ?? DEFAULT_DIVERSITY_PENALTY_AFTER,
|
||||
diversityPenaltyMultiplier: options.diversityPenaltyMultiplier ?? DEFAULT_DIVERSITY_PENALTY_MULTIPLIER,
|
||||
sponsoredItems: options.sponsoredItems ?? [],
|
||||
dedupeThreads: options.dedupeThreads ?? DEFAULT_DEDUPE_THREADS,
|
||||
removeMutedThreads: options.removeMutedThreads ?? DEFAULT_REMOVE_MUTED_THREADS,
|
||||
removeOrphans: options.removeOrphans ?? DEFAULT_REMOVE_ORPHANS,
|
||||
};
|
||||
}
|
||||
|
||||
@ -416,12 +533,16 @@ export class FeedTuner {
|
||||
* Process a raw feed array and return a tuned feed.
|
||||
*
|
||||
* Pipeline:
|
||||
* 1. Deduplicate
|
||||
* 2. Apply score adjustments (trending boost + diversity penalty)
|
||||
* 3. Re-sort by adjusted score
|
||||
* 4. Enforce author run limit
|
||||
* 5. Interleave content types
|
||||
* 6. Inject sponsored items
|
||||
* 1. Deduplicate by id
|
||||
* 2. Drop orphaned replies (removeOrphans)
|
||||
* 3. Drop muted threads (removeMutedThreads)
|
||||
* 4. Apply score adjustments (trending boost + diversity penalty)
|
||||
* 5. Re-sort by adjusted score
|
||||
* 6. Collapse threads by root (dedupThreads) — keeps the highest-scoring
|
||||
* entry per thread, so it runs after the sort
|
||||
* 7. Enforce author run limit
|
||||
* 8. Interleave content types
|
||||
* 9. Inject sponsored items
|
||||
*
|
||||
* @param posts - Raw feed items (not mutated).
|
||||
* @returns New array of tuned feed items.
|
||||
@ -429,14 +550,25 @@ export class FeedTuner {
|
||||
tune(posts: ReadonlyArray<TunableFeedItem>): TunableFeedItem[] {
|
||||
if (posts.length === 0) return [];
|
||||
|
||||
const step1 = deduplicateById(posts);
|
||||
const step2 = applyScoreAdjustments(step1, this.options);
|
||||
const step3 = sortByScore(step2);
|
||||
const step4 = enforceAuthorRun(step3, this.options.maxAuthorRun);
|
||||
const step5 = interleaveContentTypes(step4);
|
||||
const step6 = injectSponsored(step5, this.options.sponsoredItems, this.options.sponsoredInterval);
|
||||
const deduped = deduplicateById(posts);
|
||||
const withoutOrphans = this.options.removeOrphans ? dropOrphans(deduped) : deduped;
|
||||
const withoutMuted = this.options.removeMutedThreads
|
||||
? dropMutedThreads(withoutOrphans)
|
||||
: withoutOrphans;
|
||||
const adjusted = applyScoreAdjustments(withoutMuted, this.options);
|
||||
const sorted = sortByScore(adjusted);
|
||||
const threadDeduped = this.options.dedupeThreads
|
||||
? deduplicateByThreadRoot(sorted)
|
||||
: sorted;
|
||||
const runLimited = enforceAuthorRun(threadDeduped, this.options.maxAuthorRun);
|
||||
const interleaved = interleaveContentTypes(runLimited);
|
||||
const withSponsored = injectSponsored(
|
||||
interleaved,
|
||||
this.options.sponsoredItems,
|
||||
this.options.sponsoredInterval
|
||||
);
|
||||
|
||||
return step6;
|
||||
return withSponsored;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -10,11 +10,43 @@ const CACHE_TTL = {
|
||||
SEARCH: 1 * 60 * 60, // 1 hour
|
||||
};
|
||||
|
||||
/** Parse an "owner/repo" string into its parts, validating the shape. */
|
||||
function parseRepoFullName(fullName: string): { owner: string; repo: string } {
|
||||
const trimmed = (fullName || '').trim().replace(/\.git$/i, '');
|
||||
const parts = trimmed.split('/').filter(Boolean);
|
||||
if (parts.length !== 2) {
|
||||
throw new Error(`Invalid repository full name: "${fullName}". Expected "owner/repo".`);
|
||||
}
|
||||
return { owner: parts[0], repo: parts[1] };
|
||||
}
|
||||
|
||||
/** Strip a leading "@" and surrounding whitespace from a username. */
|
||||
function normalizeUsername(username: string): string {
|
||||
const normalized = (username || '').trim().replace(/^@/, '');
|
||||
if (!normalized) {
|
||||
throw new Error('A GitHub username is required.');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/** Narrow an unknown Octokit error to detect a 404 (not-found) response. */
|
||||
function isNotFoundError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'status' in error &&
|
||||
(error as { status?: number }).status === 404
|
||||
);
|
||||
}
|
||||
|
||||
export class GitHubService {
|
||||
private octokit: Octokit;
|
||||
private redis: any;
|
||||
/** The per-user OAuth token, when this instance was built for a user. */
|
||||
private readonly userAccessToken?: string;
|
||||
|
||||
constructor(accessToken?: string) {
|
||||
this.userAccessToken = accessToken;
|
||||
this.octokit = new Octokit({
|
||||
auth: accessToken || GITHUB_TOKEN,
|
||||
});
|
||||
@ -333,6 +365,132 @@ export class GitHubService {
|
||||
return results;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// TWO-WAY GITHUB ACTIONS (write-back via user OAuth token)
|
||||
//
|
||||
// Ported from gh-social (githubApi.ts: starAction, followAction,
|
||||
// hasIStarredTheRepo, amIFollowingTheUser). These require a per-user OAuth
|
||||
// token with the `public_repo`/`user:follow` scopes — construct the service
|
||||
// with `new GitHubService(userAccessToken)`. The shared app token used by
|
||||
// the singleton MUST NOT be used here, so each method guards against it.
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Guard: write actions require a per-user OAuth token, never the shared
|
||||
* app/server token. Throws a clear error when the service was built without
|
||||
* an explicit token.
|
||||
*/
|
||||
private assertUserToken(): void {
|
||||
if (!this.userAccessToken) {
|
||||
throw new Error(
|
||||
'A GitHub user access token is required for write actions. ' +
|
||||
'Construct GitHubService with the user OAuth token.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Star a repository on GitHub.com on behalf of the authenticated user.
|
||||
* Idempotent: starring an already-starred repo still resolves to starred.
|
||||
* @param fullName - "owner/repo"
|
||||
* @returns true when the repo is starred after the call.
|
||||
*/
|
||||
async starRepo(fullName: string): Promise<boolean> {
|
||||
this.assertUserToken();
|
||||
const { owner, repo } = parseRepoFullName(fullName);
|
||||
try {
|
||||
await this.octokit.activity.starRepoForAuthenticatedUser({ owner, repo });
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to star repo ${fullName}:`, error);
|
||||
throw new Error('Failed to star repository on GitHub');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a star from a repository on GitHub.com.
|
||||
* Idempotent: unstarring a not-starred repo still resolves to not-starred.
|
||||
* @returns true when the repo is no longer starred after the call.
|
||||
*/
|
||||
async unstarRepo(fullName: string): Promise<boolean> {
|
||||
this.assertUserToken();
|
||||
const { owner, repo } = parseRepoFullName(fullName);
|
||||
try {
|
||||
await this.octokit.activity.unstarRepoForAuthenticatedUser({ owner, repo });
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to unstar repo ${fullName}:`, error);
|
||||
throw new Error('Failed to unstar repository on GitHub');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Live check: has the authenticated user starred this repo?
|
||||
* GitHub returns 204 when starred and 404 when not.
|
||||
*/
|
||||
async hasStarred(fullName: string): Promise<boolean> {
|
||||
this.assertUserToken();
|
||||
const { owner, repo } = parseRepoFullName(fullName);
|
||||
try {
|
||||
await this.octokit.activity.checkRepoIsStarredByAuthenticatedUser({ owner, repo });
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
if (isNotFoundError(error)) return false;
|
||||
logger.error(`Failed to check star status for ${fullName}:`, error);
|
||||
throw new Error('Failed to check star status on GitHub');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow a GitHub user on behalf of the authenticated user.
|
||||
* Idempotent.
|
||||
* @returns true when the user is followed after the call.
|
||||
*/
|
||||
async followUser(username: string): Promise<boolean> {
|
||||
this.assertUserToken();
|
||||
const normalized = normalizeUsername(username);
|
||||
try {
|
||||
await this.octokit.users.follow({ username: normalized });
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to follow user ${normalized}:`, error);
|
||||
throw new Error('Failed to follow user on GitHub');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unfollow a GitHub user. Idempotent.
|
||||
* @returns true when the user is no longer followed after the call.
|
||||
*/
|
||||
async unfollowUser(username: string): Promise<boolean> {
|
||||
this.assertUserToken();
|
||||
const normalized = normalizeUsername(username);
|
||||
try {
|
||||
await this.octokit.users.unfollow({ username: normalized });
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to unfollow user ${normalized}:`, error);
|
||||
throw new Error('Failed to unfollow user on GitHub');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Live check: is the authenticated user following this GitHub user?
|
||||
* GitHub returns 204 when following and 404 when not.
|
||||
*/
|
||||
async isFollowing(username: string): Promise<boolean> {
|
||||
this.assertUserToken();
|
||||
const normalized = normalizeUsername(username);
|
||||
try {
|
||||
await this.octokit.users.checkPersonIsFollowedByAuthenticated({ username: normalized });
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
if (isNotFoundError(error)) return false;
|
||||
logger.error(`Failed to check follow status for ${normalized}:`, error);
|
||||
throw new Error('Failed to check follow status on GitHub');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get rate limit status
|
||||
*/
|
||||
|
||||
111
gitgram/backend/src/services/selfLabels.ts
Normal file
111
gitgram/backend/src/services/selfLabels.ts
Normal file
@ -0,0 +1,111 @@
|
||||
/**
|
||||
* selfLabels.ts
|
||||
*
|
||||
* Author self-labeling / content warnings.
|
||||
*
|
||||
* Ported from Bluesky's moderation model (src/lib/moderation.ts: SELF_LABELS,
|
||||
* ADULT_CONTENT_LABELS, OTHER_SELF_LABELS and the hide-vs-warn behavior). An
|
||||
* AUTHOR voluntarily marks their own post as sensitive; each label maps to a
|
||||
* `hide` or `warn` behavior the feed pipeline applies before rendering.
|
||||
*
|
||||
* This complements (does not replace) the platform-driven auto-moderation
|
||||
* (nsfwDetectionService etc.) — it is a low-friction, trust-building signal the
|
||||
* author opts into.
|
||||
*
|
||||
* All exports are pure data + pure functions; no I/O, no mutation.
|
||||
*/
|
||||
|
||||
/** Adult-content self labels. These HIDE the post by default. */
|
||||
export const ADULT_CONTENT_LABELS = ['sexual', 'nudity', 'porn'] as const;
|
||||
|
||||
/** Non-adult self labels. These WARN (blur) by default. */
|
||||
export const OTHER_SELF_LABELS = ['graphic-media', 'spoiler'] as const;
|
||||
|
||||
/** Every recognised self label. */
|
||||
export const SELF_LABELS = [...ADULT_CONTENT_LABELS, ...OTHER_SELF_LABELS] as const;
|
||||
|
||||
export type AdultSelfLabel = (typeof ADULT_CONTENT_LABELS)[number];
|
||||
export type OtherSelfLabel = (typeof OTHER_SELF_LABELS)[number];
|
||||
export type SelfLabel = (typeof SELF_LABELS)[number];
|
||||
|
||||
/** Behavior the feed pipeline applies for a labeled post. */
|
||||
export type LabelBehavior = 'hide' | 'warn';
|
||||
|
||||
const ADULT_SET: ReadonlySet<string> = new Set(ADULT_CONTENT_LABELS);
|
||||
const SELF_LABEL_SET: ReadonlySet<string> = new Set(SELF_LABELS);
|
||||
|
||||
/** Type guard: is this string a recognised self label? */
|
||||
export function isSelfLabel(value: string): value is SelfLabel {
|
||||
return SELF_LABEL_SET.has(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and normalise an arbitrary input into a deduped list of recognised
|
||||
* self labels. Unknown entries are dropped silently. Returns a new array.
|
||||
*/
|
||||
export function normalizeSelfLabels(input: unknown): SelfLabel[] {
|
||||
const raw = Array.isArray(input)
|
||||
? input
|
||||
: typeof input === 'string'
|
||||
? input.split(',')
|
||||
: [];
|
||||
|
||||
const seen = new Set<SelfLabel>();
|
||||
for (const entry of raw) {
|
||||
if (typeof entry !== 'string') continue;
|
||||
const candidate = entry.trim().toLowerCase();
|
||||
if (isSelfLabel(candidate)) seen.add(candidate);
|
||||
}
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
/**
|
||||
* The strongest behavior implied by a set of labels.
|
||||
* - any adult label -> 'hide'
|
||||
* - any other self label -> 'warn'
|
||||
* - no labels -> null (no behavior)
|
||||
*/
|
||||
export function behaviorForLabels(labels: ReadonlyArray<string>): LabelBehavior | null {
|
||||
let hasWarn = false;
|
||||
for (const label of labels) {
|
||||
if (ADULT_SET.has(label)) return 'hide';
|
||||
if (SELF_LABEL_SET.has(label)) hasWarn = true;
|
||||
}
|
||||
return hasWarn ? 'warn' : null;
|
||||
}
|
||||
|
||||
/** A post viewed through the self-label lens. */
|
||||
export interface SelfLabeledPost {
|
||||
selfLabels?: string[] | null;
|
||||
contentWarning?: string | null;
|
||||
}
|
||||
|
||||
/** Moderation decision attached to a feed item for the client to honour. */
|
||||
export interface SelfLabelDecision {
|
||||
/** Behavior to apply; null when the post carries no self labels. */
|
||||
behavior: LabelBehavior | null;
|
||||
/** Recognised labels present on the post. */
|
||||
labels: SelfLabel[];
|
||||
/** Optional author-supplied warning text. */
|
||||
contentWarning: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the moderation decision for a post from its self labels.
|
||||
*
|
||||
* Hide vs warn semantics mirror Bluesky: `hide` means the post is collapsed out
|
||||
* of the feed unless the viewer has explicitly opted into adult content; `warn`
|
||||
* means the post stays in the feed but the client should blur it behind the
|
||||
* warning until tapped.
|
||||
*/
|
||||
export function decideSelfLabel(post: SelfLabeledPost): SelfLabelDecision {
|
||||
const labels = normalizeSelfLabels(post.selfLabels);
|
||||
return {
|
||||
behavior: behaviorForLabels(labels),
|
||||
labels,
|
||||
contentWarning:
|
||||
typeof post.contentWarning === 'string' && post.contentWarning.trim().length > 0
|
||||
? post.contentWarning.trim()
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@ -21,6 +21,9 @@ import { scheduledPostsService } from '../../services/scheduledPostsService';
|
||||
import { userService } from '../../services/userService';
|
||||
import { logger } from '../../utils/logger';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
import ImageAltTextDialog from '../../components/common/ImageAltTextDialog';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useToast } from '../../hooks/useToast';
|
||||
|
||||
interface TaggablePerson {
|
||||
id: string;
|
||||
@ -34,6 +37,7 @@ interface SelectedMedia {
|
||||
uri: string;
|
||||
type: MediaType;
|
||||
mimeType?: string;
|
||||
alt?: string;
|
||||
}
|
||||
|
||||
const inferMediaType = (asset: ImagePicker.ImagePickerAsset): MediaType =>
|
||||
@ -50,11 +54,14 @@ export default function CreatePostScreen() {
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{ schedule?: string }>();
|
||||
const isScheduling = params.schedule === 'true';
|
||||
const altTextRequired = useSettingsStore((state) => state.altTextRequired);
|
||||
const { showToast, ToastComponent } = useToast();
|
||||
|
||||
const [content, setContent] = useState('');
|
||||
const [media, setMedia] = useState<SelectedMedia | null>(null);
|
||||
const [taggedPeople, setTaggedPeople] = useState<TaggablePerson[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [altDialogVisible, setAltDialogVisible] = useState(false);
|
||||
|
||||
const [tagModalVisible, setTagModalVisible] = useState(false);
|
||||
const [tagQuery, setTagQuery] = useState('');
|
||||
@ -104,9 +111,19 @@ export default function CreatePostScreen() {
|
||||
);
|
||||
};
|
||||
|
||||
const saveAltText = (altText: string) => {
|
||||
setMedia((prev) => (prev ? { ...prev, alt: altText } : prev));
|
||||
};
|
||||
|
||||
const handlePost = async () => {
|
||||
if (!content && !media) return;
|
||||
|
||||
// Enforce alt text on images when the preference is enabled (accessibility).
|
||||
if (altTextRequired && media?.type === 'image' && !media.alt?.trim()) {
|
||||
showToast('Please add alt text to your image before posting.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
@ -120,6 +137,9 @@ export default function CreatePostScreen() {
|
||||
type: buildMimeType(media, filename),
|
||||
} as unknown as Blob);
|
||||
formData.append('mediaType', media.type);
|
||||
if (media.alt?.trim()) {
|
||||
formData.append('altTexts[]', media.alt.trim());
|
||||
}
|
||||
}
|
||||
|
||||
taggedPeople.forEach((person) => {
|
||||
@ -181,11 +201,32 @@ export default function CreatePostScreen() {
|
||||
<ThemedText style={styles.videoLabel}>Video selected</ThemedText>
|
||||
</View>
|
||||
) : (
|
||||
<Image source={{ uri: media.uri }} style={styles.image} />
|
||||
<Image
|
||||
source={{ uri: media.uri }}
|
||||
style={styles.image}
|
||||
accessibilityLabel={media.alt || undefined}
|
||||
/>
|
||||
)}
|
||||
<TouchableOpacity style={styles.removeButton} onPress={() => setMedia(null)}>
|
||||
<Icon name="close" size={20} color="#FFF" />
|
||||
</TouchableOpacity>
|
||||
{media.type === 'image' && (
|
||||
<TouchableOpacity
|
||||
style={styles.altButton}
|
||||
onPress={() => setAltDialogVisible(true)}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={media.alt ? 'Edit alt text' : 'Add alt text'}
|
||||
>
|
||||
<Icon
|
||||
name={media.alt ? 'check-circle' : 'add-circle-outline'}
|
||||
size={16}
|
||||
color="#FFF"
|
||||
/>
|
||||
<ThemedText style={styles.altButtonText}>
|
||||
{media.alt ? 'ALT added' : 'Add alt text'}
|
||||
</ThemedText>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
|
||||
@ -261,6 +302,18 @@ export default function CreatePostScreen() {
|
||||
)}
|
||||
</ThemedView>
|
||||
</Modal>
|
||||
|
||||
{media?.type === 'image' && (
|
||||
<ImageAltTextDialog
|
||||
visible={altDialogVisible}
|
||||
imageUri={media.uri}
|
||||
initialAltText={media.alt ?? ''}
|
||||
onSave={saveAltText}
|
||||
onClose={() => setAltDialogVisible(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{ToastComponent}
|
||||
</ThemedView>
|
||||
);
|
||||
}
|
||||
@ -314,6 +367,23 @@ const styles = StyleSheet.create({
|
||||
borderRadius: 12,
|
||||
padding: 4,
|
||||
},
|
||||
altButton: {
|
||||
position: 'absolute',
|
||||
left: 8,
|
||||
bottom: 8,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 4,
|
||||
backgroundColor: 'rgba(0,0,0,0.6)',
|
||||
borderRadius: 14,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 6,
|
||||
},
|
||||
altButtonText: {
|
||||
color: '#FFF',
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
},
|
||||
taggedRow: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
|
||||
@ -3,9 +3,11 @@ import { Stack } from 'expo-router';
|
||||
import { GestureHandlerRootView } from 'react-native-gesture-handler';
|
||||
import { SafeAreaProvider } from 'react-native-safe-area-context';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { useSettingsStore } from '../store/settingsStore';
|
||||
import { ErrorBoundary } from '../components/common/ErrorBoundary';
|
||||
import NetworkStatus from '../components/common/NetworkStatus';
|
||||
import { ToastProvider } from '../components/proximity/Toast';
|
||||
import { LightboxProvider } from '../components/common/Lightbox';
|
||||
import { pushNotificationService } from '../services/pushNotificationService';
|
||||
import { paymentDeepLinkHandler } from '../utils/paymentDeepLinkHandler';
|
||||
import { setupNotificationDeepLinkHandler, handleNotificationDeepLink } from '../utils/notificationDeepLinkHandler';
|
||||
@ -13,9 +15,11 @@ import { logger } from '../utils/logger';
|
||||
|
||||
export default function RootLayout() {
|
||||
const { initialize, isAuthenticated } = useAuthStore();
|
||||
const hydrateSettings = useSettingsStore((state) => state.hydrate);
|
||||
|
||||
useEffect(() => {
|
||||
initialize();
|
||||
hydrateSettings();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@ -66,6 +70,7 @@ export default function RootLayout() {
|
||||
<Stack.Screen name="(tabs)" />
|
||||
<Stack.Screen name="(modals)" />
|
||||
</Stack>
|
||||
<LightboxProvider />
|
||||
</ToastProvider>
|
||||
</SafeAreaProvider>
|
||||
</GestureHandlerRootView>
|
||||
|
||||
@ -19,6 +19,7 @@ import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import EmptyState from '../../components/common/EmptyState';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import { logger } from '../../utils/logger';
|
||||
import { useHaptics } from '../../hooks/useHaptics';
|
||||
|
||||
const TYPING_DEBOUNCE_MS = 2000; // Stop typing after 2 seconds of no input
|
||||
|
||||
@ -114,6 +115,7 @@ interface Message {
|
||||
export default function ChatScreen() {
|
||||
const { userId } = useLocalSearchParams<{ userId: string }>();
|
||||
const router = useRouter();
|
||||
const haptics = useHaptics();
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [messageText, setMessageText] = useState('');
|
||||
@ -229,6 +231,7 @@ export default function ChatScreen() {
|
||||
|
||||
try {
|
||||
setSending(true);
|
||||
haptics('Light');
|
||||
|
||||
// Stop typing indicator when sending
|
||||
emitTypingStop();
|
||||
|
||||
@ -5,6 +5,7 @@ import {
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
ScrollView,
|
||||
Switch,
|
||||
} from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Image } from 'expo-image';
|
||||
@ -12,6 +13,8 @@ import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { Colors } from '../constants/Colors';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { useSettingsStore } from '../store/settingsStore';
|
||||
import { useHaptics } from '../hooks/useHaptics';
|
||||
import { authService } from '../services/authService';
|
||||
import { logger } from '../utils/logger';
|
||||
|
||||
@ -31,6 +34,19 @@ interface MenuItem {
|
||||
export default function MenuScreen() {
|
||||
const router = useRouter();
|
||||
const { user, logout } = useAuthStore();
|
||||
const hapticsDisabled = useSettingsStore((state) => state.hapticsDisabled);
|
||||
const setHapticsDisabled = useSettingsStore((state) => state.setHapticsDisabled);
|
||||
const altTextRequired = useSettingsStore((state) => state.altTextRequired);
|
||||
const setAltTextRequired = useSettingsStore((state) => state.setAltTextRequired);
|
||||
const haptics = useHaptics();
|
||||
|
||||
const toggleHaptics = (value: boolean) => {
|
||||
// Fire a confirming buzz only when turning haptics back on.
|
||||
if (!value) {
|
||||
haptics('Light');
|
||||
}
|
||||
void setHapticsDisabled(!value);
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
const run = async () => {
|
||||
@ -101,6 +117,27 @@ export default function MenuScreen() {
|
||||
</View>
|
||||
|
||||
<ScrollView style={styles.menu}>
|
||||
<View style={styles.toggleRow}>
|
||||
<Icon name="vibration" size={24} color={Colors.text} />
|
||||
<Text style={styles.menuLabel}>Haptic Feedback</Text>
|
||||
<Switch
|
||||
value={!hapticsDisabled}
|
||||
onValueChange={toggleHaptics}
|
||||
trackColor={{ false: Colors.border, true: Colors.primary }}
|
||||
thumbColor={Colors.white}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.toggleRow}>
|
||||
<Icon name="accessibility-new" size={24} color={Colors.text} />
|
||||
<Text style={styles.menuLabel}>Require Alt Text</Text>
|
||||
<Switch
|
||||
value={altTextRequired}
|
||||
onValueChange={(value) => void setAltTextRequired(value)}
|
||||
trackColor={{ false: Colors.border, true: Colors.primary }}
|
||||
thumbColor={Colors.white}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.divider} />
|
||||
{menuItems.map((item, index) => {
|
||||
if (item.divider) {
|
||||
return <View key={`divider-${index}`} style={styles.divider} />;
|
||||
@ -192,6 +229,13 @@ const styles = StyleSheet.create({
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: Colors.border,
|
||||
},
|
||||
toggleRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
padding: 16,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: Colors.border,
|
||||
},
|
||||
menuLabel: {
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useRef, useState } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
@ -11,6 +11,12 @@ import { Image } from 'expo-image';
|
||||
import { momentService } from '../../services/momentService';
|
||||
import { logger } from '../../utils/logger';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
import { useHaptics } from '../../hooks/useHaptics';
|
||||
import LikeBounceAnimation, {
|
||||
LikeBounceAnimationHandle,
|
||||
} from '../common/LikeBounceAnimation';
|
||||
|
||||
const DOUBLE_PRESS_DELAY = 300;
|
||||
|
||||
interface MomentCardProps {
|
||||
moment: {
|
||||
@ -31,32 +37,71 @@ interface MomentCardProps {
|
||||
|
||||
export default function MomentCard({ moment }: MomentCardProps) {
|
||||
const router = useRouter();
|
||||
const haptics = useHaptics();
|
||||
const likeBounceRef = useRef<LikeBounceAnimationHandle>(null);
|
||||
const lastTapRef = useRef(0);
|
||||
const [isLiked, setIsLiked] = useState(false);
|
||||
const [likesCount, setLikesCount] = useState(moment.likesCount);
|
||||
const [liking, setLiking] = useState(false);
|
||||
|
||||
const handleLike = async (mode: 'toggle' | 'like-only' = 'toggle') => {
|
||||
if (liking) return;
|
||||
if (mode === 'like-only' && isLiked) return;
|
||||
|
||||
haptics('Medium');
|
||||
|
||||
const previousIsLiked = isLiked;
|
||||
setIsLiked(!previousIsLiked);
|
||||
setLikesCount((prev) => (!previousIsLiked ? prev + 1 : prev - 1));
|
||||
setLiking(true);
|
||||
|
||||
const handleLike = async () => {
|
||||
try {
|
||||
const response = await momentService.likeMoment(moment.id);
|
||||
setIsLiked(response.liked);
|
||||
setLikesCount((prev) => (response.liked ? prev + 1 : prev - 1));
|
||||
setLikesCount(moment.likesCount + (response.liked ? 1 : 0));
|
||||
} catch (error) {
|
||||
// Roll back the optimistic update on failure.
|
||||
setIsLiked(previousIsLiked);
|
||||
setLikesCount((prev) => (!previousIsLiked ? prev - 1 : prev + 1));
|
||||
logger.error('Like moment error:', error);
|
||||
} finally {
|
||||
setLiking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePreviewPress = () => {
|
||||
const now = Date.now();
|
||||
if (now - lastTapRef.current < DOUBLE_PRESS_DELAY) {
|
||||
lastTapRef.current = 0;
|
||||
likeBounceRef.current?.animate();
|
||||
void handleLike('like-only');
|
||||
return;
|
||||
}
|
||||
lastTapRef.current = now;
|
||||
router.push(`/moments/${moment.id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<TouchableOpacity
|
||||
style={styles.container}
|
||||
onPress={() => router.push(`/moments/${moment.id}`)}
|
||||
>
|
||||
<View style={styles.momentContainer}>
|
||||
<View style={styles.screenshotContainer}>
|
||||
<Image source={{ uri: moment.screenshotUrl }} style={styles.screenshot} />
|
||||
<View style={styles.container}>
|
||||
<TouchableOpacity activeOpacity={0.95} onPress={handlePreviewPress}>
|
||||
<View style={styles.momentContainer}>
|
||||
<View style={styles.screenshotContainer}>
|
||||
<Image
|
||||
source={{ uri: moment.screenshotUrl }}
|
||||
style={styles.screenshot}
|
||||
accessibilityLabel={moment.caption || `Moment by ${moment.user.username}`}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.selfieContainer}>
|
||||
<Image
|
||||
source={{ uri: moment.selfieUrl }}
|
||||
style={styles.selfie}
|
||||
accessibilityLabel={`Selfie by ${moment.user.username}`}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.selfieContainer}>
|
||||
<Image source={{ uri: moment.selfieUrl }} style={styles.selfie} />
|
||||
</View>
|
||||
</View>
|
||||
<LikeBounceAnimation ref={likeBounceRef} color="#ff4757" />
|
||||
</TouchableOpacity>
|
||||
|
||||
<View style={styles.infoContainer}>
|
||||
<View style={styles.userInfo}>
|
||||
@ -81,10 +126,10 @@ export default function MomentCard({ moment }: MomentCardProps) {
|
||||
<View style={styles.actions}>
|
||||
<TouchableOpacity
|
||||
style={styles.actionButton}
|
||||
onPress={(e) => {
|
||||
e.stopPropagation();
|
||||
handleLike();
|
||||
}}
|
||||
onPress={() => handleLike('toggle')}
|
||||
disabled={liking}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={isLiked ? 'Unlike moment' : 'Like moment'}
|
||||
>
|
||||
<Icon
|
||||
name={isLiked ? 'favorite' : 'favorite-border'}
|
||||
@ -96,17 +141,14 @@ export default function MomentCard({ moment }: MomentCardProps) {
|
||||
|
||||
<TouchableOpacity
|
||||
style={styles.actionButton}
|
||||
onPress={(e) => {
|
||||
e.stopPropagation();
|
||||
router.push(`/moments/${moment.id}/reactions`);
|
||||
}}
|
||||
onPress={() => router.push(`/moments/${moment.id}/reactions`)}
|
||||
>
|
||||
<Icon name="comment" size={20} color={Colors.text} />
|
||||
<Text style={styles.actionText}>{moment.commentsCount}</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useRef, useState } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
ScrollView,
|
||||
} from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Image } from 'expo-image';
|
||||
@ -12,10 +11,17 @@ import { Colors } from '../../constants/Colors';
|
||||
import { postService } from '../../services/postService';
|
||||
import { logger } from '../../utils/logger';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useHaptics } from '../../hooks/useHaptics';
|
||||
import PostOptionsModal from '../common/PostOptionsModal';
|
||||
import ReportModal from '../common/ReportModal';
|
||||
import CodeBlock from '../common/CodeBlock';
|
||||
import RichContent from '../common/RichContent';
|
||||
import LikeBounceAnimation, {
|
||||
LikeBounceAnimationHandle,
|
||||
} from '../common/LikeBounceAnimation';
|
||||
import { useLightbox } from '../common/Lightbox';
|
||||
|
||||
const DOUBLE_PRESS_DELAY = 300;
|
||||
|
||||
interface Post {
|
||||
id: string;
|
||||
@ -46,16 +52,25 @@ interface PostCardProps {
|
||||
export default function PostCard({ post, onLike, showFullContent = false }: PostCardProps) {
|
||||
const router = useRouter();
|
||||
const { user } = useAuthStore();
|
||||
const haptics = useHaptics();
|
||||
const openLightbox = useLightbox();
|
||||
const [isLiked, setIsLiked] = useState(post.isLiked);
|
||||
const [likesCount, setLikesCount] = useState(post.likesCount);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showOptionsModal, setShowOptionsModal] = useState(false);
|
||||
const [showReportModal, setShowReportModal] = useState(false);
|
||||
const likeBounceRef = useRef<LikeBounceAnimationHandle>(null);
|
||||
const lastTapRef = useRef(0);
|
||||
|
||||
const isOwner = user?.id === post.user.id;
|
||||
|
||||
const handleLike = async () => {
|
||||
// mode: 'toggle' for the like button, 'like-only' for double-tap (which never
|
||||
// unlikes, matching Instagram/TikTok behaviour).
|
||||
const handleLike = async (mode: 'toggle' | 'like-only' = 'toggle') => {
|
||||
if (loading) return;
|
||||
if (mode === 'like-only' && isLiked) return;
|
||||
|
||||
haptics('Medium');
|
||||
|
||||
// Optimistic update - update UI immediately
|
||||
const previousIsLiked = isLiked;
|
||||
@ -81,6 +96,26 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post
|
||||
}
|
||||
};
|
||||
|
||||
const handleImagePress = () => {
|
||||
const now = Date.now();
|
||||
if (now - lastTapRef.current < DOUBLE_PRESS_DELAY) {
|
||||
lastTapRef.current = 0;
|
||||
likeBounceRef.current?.animate();
|
||||
void handleLike('like-only');
|
||||
return;
|
||||
}
|
||||
lastTapRef.current = now;
|
||||
if (!showFullContent) {
|
||||
router.push(`/post/${post.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImageLongPress = () => {
|
||||
if (!post.mediaUrl) return;
|
||||
haptics('Light');
|
||||
openLightbox([{ uri: post.mediaUrl, alt: post.content || undefined }], 0);
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
{/* Card Header */}
|
||||
@ -106,7 +141,9 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post
|
||||
{/* Project Visual */}
|
||||
{post.mediaType === 'image' && post.mediaUrl && (
|
||||
<TouchableOpacity
|
||||
onPress={() => !showFullContent && router.push(`/post/${post.id}`)}
|
||||
onPress={handleImagePress}
|
||||
onLongPress={handleImageLongPress}
|
||||
delayLongPress={350}
|
||||
activeOpacity={showFullContent ? 1 : 0.9}
|
||||
>
|
||||
<Image
|
||||
@ -116,7 +153,9 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post
|
||||
transition={200}
|
||||
placeholder={{ blurhash: 'L6PZfSi_.AyE_3t7t7R**0o#DgR4' }}
|
||||
cachePolicy="memory-disk"
|
||||
accessibilityLabel={post.content || undefined}
|
||||
/>
|
||||
<LikeBounceAnimation ref={likeBounceRef} />
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
|
||||
@ -135,8 +174,10 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post
|
||||
<View style={styles.actionBarLeft}>
|
||||
<TouchableOpacity
|
||||
style={styles.actionButton}
|
||||
onPress={handleLike}
|
||||
onPress={() => handleLike('toggle')}
|
||||
disabled={loading}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={isLiked ? 'Unlike post' : 'Like post'}
|
||||
>
|
||||
<Text style={styles.actionIcon}>{isLiked ? '❤️' : '🤍'}</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useRef, useState } from 'react';
|
||||
import { View, StyleSheet, TouchableOpacity, Dimensions } from 'react-native';
|
||||
import { Video, ResizeMode } from 'expo-av';
|
||||
import { ThemedText } from '../ui/ThemedText';
|
||||
@ -7,6 +7,12 @@ import { Image } from 'expo-image';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
import ReportModal from '../common/ReportModal';
|
||||
import { VISUAL_EFFECTS } from '../../store/reelEditorStore';
|
||||
import { useHaptics } from '../../hooks/useHaptics';
|
||||
import LikeBounceAnimation, {
|
||||
LikeBounceAnimationHandle,
|
||||
} from '../common/LikeBounceAnimation';
|
||||
|
||||
const DOUBLE_PRESS_DELAY = 300;
|
||||
|
||||
const { width, height } = Dimensions.get('window');
|
||||
|
||||
@ -63,6 +69,9 @@ export default function ReelPlayer({
|
||||
user: { username: username || 'user', avatar: '' },
|
||||
};
|
||||
const video = React.useRef<Video>(null);
|
||||
const haptics = useHaptics();
|
||||
const likeBounceRef = useRef<LikeBounceAnimationHandle>(null);
|
||||
const lastTapRef = useRef(0);
|
||||
const [status, setStatus] = React.useState<any>({});
|
||||
const [isPlaying, setIsPlaying] = React.useState(isActive);
|
||||
const [showReportModal, setShowReportModal] = useState(false);
|
||||
@ -99,9 +108,31 @@ export default function ReelPlayer({
|
||||
}
|
||||
};
|
||||
|
||||
const handleLikePress = () => {
|
||||
haptics('Medium');
|
||||
onLike();
|
||||
};
|
||||
|
||||
const handleVideoPress = () => {
|
||||
const now = Date.now();
|
||||
if (now - lastTapRef.current < DOUBLE_PRESS_DELAY) {
|
||||
lastTapRef.current = 0;
|
||||
// Double-tap always likes (never unlikes), matching the feed convention.
|
||||
if (!isLiked) {
|
||||
likeBounceRef.current?.animate();
|
||||
handleLikePress();
|
||||
} else {
|
||||
likeBounceRef.current?.animate();
|
||||
}
|
||||
return;
|
||||
}
|
||||
lastTapRef.current = now;
|
||||
togglePlayback();
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<TouchableOpacity activeOpacity={1} onPress={togglePlayback} style={styles.videoContainer}>
|
||||
<TouchableOpacity activeOpacity={1} onPress={handleVideoPress} style={styles.videoContainer}>
|
||||
<Video
|
||||
ref={video}
|
||||
source={{ uri: reel.videoUrl }}
|
||||
@ -133,6 +164,7 @@ export default function ReelPlayer({
|
||||
<Icon name="play-arrow" size={64} color="rgba(255, 255, 255, 0.6)" />
|
||||
</View>
|
||||
)}
|
||||
<LikeBounceAnimation ref={likeBounceRef} color="#ff4757" />
|
||||
</TouchableOpacity>
|
||||
|
||||
<View style={styles.overlay}>
|
||||
@ -171,7 +203,12 @@ export default function ReelPlayer({
|
||||
</View>
|
||||
|
||||
<View style={styles.actions}>
|
||||
<TouchableOpacity style={styles.actionButton} onPress={onLike}>
|
||||
<TouchableOpacity
|
||||
style={styles.actionButton}
|
||||
onPress={handleLikePress}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={isLiked ? 'Unlike reel' : 'Like reel'}
|
||||
>
|
||||
<Icon name={isLiked ? "favorite" : "favorite-border"} size={32} color={isLiked ? "#ff4757" : "#FFF"} />
|
||||
<ThemedText style={styles.actionText}>{likesCount}</ThemedText>
|
||||
</TouchableOpacity>
|
||||
|
||||
@ -10,6 +10,7 @@ import {
|
||||
import { Image } from 'expo-image';
|
||||
import { VideoView, useVideoPlayer } from 'expo-video';
|
||||
import { Colors } from '../../constants/Colors';
|
||||
import { useLightbox } from '../common/Lightbox';
|
||||
|
||||
const { width: SCREEN_WIDTH } = Dimensions.get('window');
|
||||
const STORY_DURATION = 5000; // 5 seconds
|
||||
@ -39,6 +40,7 @@ export default function StoryViewer({
|
||||
const [currentStoryIndex, setCurrentStoryIndex] = useState(initialIndex);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const progressAnim = useRef(new Animated.Value(0)).current;
|
||||
const openLightbox = useLightbox();
|
||||
|
||||
const currentStory = stories[currentStoryIndex];
|
||||
const player = useVideoPlayer(
|
||||
@ -110,6 +112,20 @@ export default function StoryViewer({
|
||||
}
|
||||
};
|
||||
|
||||
const handleLongPress = () => {
|
||||
// Only still images make sense to open in the zoomable lightbox.
|
||||
if (currentStory?.mediaType === 'video') return;
|
||||
openLightbox(
|
||||
[
|
||||
{
|
||||
uri: currentStory.mediaUrl,
|
||||
alt: `Story by ${currentStory.user.username}`,
|
||||
},
|
||||
],
|
||||
0,
|
||||
);
|
||||
};
|
||||
|
||||
if (!currentStory) {
|
||||
return null;
|
||||
}
|
||||
@ -142,6 +158,8 @@ export default function StoryViewer({
|
||||
style={styles.content}
|
||||
activeOpacity={1}
|
||||
onPress={handleTap}
|
||||
onLongPress={handleLongPress}
|
||||
delayLongPress={350}
|
||||
>
|
||||
{currentStory.mediaType === 'video' ? (
|
||||
<VideoView player={player} style={styles.media} contentFit="cover" />
|
||||
|
||||
210
gitgram/mobile/components/common/ImageAltTextDialog.tsx
Normal file
210
gitgram/mobile/components/common/ImageAltTextDialog.tsx
Normal file
@ -0,0 +1,210 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Modal,
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
TextInput,
|
||||
TouchableOpacity,
|
||||
Image,
|
||||
ScrollView,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
} from 'react-native';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
import { Colors } from '../../constants/Colors';
|
||||
|
||||
// Matches Bluesky's alt-text limit for parity with the source pattern.
|
||||
export const MAX_ALT_TEXT = 2000;
|
||||
|
||||
const enforceLen = (str: string, max: number): string =>
|
||||
str.length > max ? str.slice(0, max) : str;
|
||||
|
||||
interface ImageAltTextDialogProps {
|
||||
visible: boolean;
|
||||
imageUri: string;
|
||||
initialAltText?: string;
|
||||
// Called with the (length-enforced) alt text when the user saves.
|
||||
onSave: (altText: string) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-image alt-text authoring dialog. Ported from Bluesky's ImageAltTextDialog
|
||||
* onto the product's React Native Modal stack: shows the image being described,
|
||||
* a multiline field with a live character counter, length enforcement, and a
|
||||
* truncation warning.
|
||||
*/
|
||||
export default function ImageAltTextDialog({
|
||||
visible,
|
||||
imageUri,
|
||||
initialAltText = '',
|
||||
onSave,
|
||||
onClose,
|
||||
}: ImageAltTextDialogProps) {
|
||||
const [altText, setAltText] = useState(initialAltText);
|
||||
|
||||
// Reset the field whenever the dialog is (re)opened for a new image.
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
setAltText(initialAltText);
|
||||
}
|
||||
}, [visible, initialAltText]);
|
||||
|
||||
const overLimit = altText.length > MAX_ALT_TEXT;
|
||||
const remaining = MAX_ALT_TEXT - altText.length;
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(enforceLen(altText.trim(), MAX_ALT_TEXT));
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
visible={visible}
|
||||
animationType="slide"
|
||||
onRequestClose={onClose}
|
||||
transparent={false}
|
||||
>
|
||||
<KeyboardAvoidingView
|
||||
style={styles.container}
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
|
||||
>
|
||||
<View style={styles.header}>
|
||||
<TouchableOpacity onPress={onClose} accessibilityRole="button" accessibilityLabel="Cancel">
|
||||
<Icon name="close" size={24} color={Colors.text} />
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.title}>Add alt text</Text>
|
||||
<TouchableOpacity
|
||||
onPress={handleSave}
|
||||
disabled={overLimit}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Save alt text"
|
||||
>
|
||||
<Text style={[styles.saveText, overLimit && styles.saveTextDisabled]}>Save</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<ScrollView style={styles.body} keyboardShouldPersistTaps="handled">
|
||||
<View style={styles.imageWrapper}>
|
||||
<Image source={{ uri: imageUri }} style={styles.image} resizeMode="contain" />
|
||||
</View>
|
||||
|
||||
<Text style={styles.label}>Descriptive alt text</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={altText}
|
||||
onChangeText={setAltText}
|
||||
placeholder="Describe this image for people who can't see it"
|
||||
placeholderTextColor={Colors.textSecondary}
|
||||
multiline
|
||||
numberOfLines={4}
|
||||
autoFocus
|
||||
textAlignVertical="top"
|
||||
maxLength={MAX_ALT_TEXT + 100}
|
||||
accessibilityLabel="Alt text"
|
||||
/>
|
||||
|
||||
<View style={styles.metaRow}>
|
||||
{overLimit ? (
|
||||
<View style={styles.warningRow}>
|
||||
<Icon name="error-outline" size={16} color={Colors.error} />
|
||||
<Text style={styles.warningText}>
|
||||
Alt text will be truncated. Limit: {MAX_ALT_TEXT} characters.
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View />
|
||||
)}
|
||||
<Text style={[styles.counter, overLimit && styles.counterOver]}>{remaining}</Text>
|
||||
</View>
|
||||
</ScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: Colors.background,
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: 16,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: Colors.border,
|
||||
},
|
||||
title: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: Colors.text,
|
||||
},
|
||||
saveText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: Colors.primary,
|
||||
},
|
||||
saveTextDisabled: {
|
||||
color: Colors.disabled,
|
||||
},
|
||||
body: {
|
||||
flex: 1,
|
||||
padding: 16,
|
||||
},
|
||||
imageWrapper: {
|
||||
width: '100%',
|
||||
aspectRatio: 1,
|
||||
borderRadius: 8,
|
||||
overflow: 'hidden',
|
||||
backgroundColor: Colors.surface,
|
||||
marginBottom: 16,
|
||||
},
|
||||
image: {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
},
|
||||
label: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: Colors.text,
|
||||
marginBottom: 8,
|
||||
},
|
||||
input: {
|
||||
minHeight: 96,
|
||||
borderWidth: 1,
|
||||
borderColor: Colors.border,
|
||||
borderRadius: 8,
|
||||
padding: 12,
|
||||
color: Colors.text,
|
||||
fontSize: 15,
|
||||
backgroundColor: Colors.surface,
|
||||
},
|
||||
metaRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginTop: 8,
|
||||
},
|
||||
warningRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 4,
|
||||
flex: 1,
|
||||
},
|
||||
warningText: {
|
||||
color: Colors.error,
|
||||
fontSize: 12,
|
||||
flexShrink: 1,
|
||||
},
|
||||
counter: {
|
||||
color: Colors.textSecondary,
|
||||
fontSize: 12,
|
||||
marginLeft: 8,
|
||||
},
|
||||
counterOver: {
|
||||
color: Colors.error,
|
||||
},
|
||||
});
|
||||
133
gitgram/mobile/components/common/Lightbox/LightboxProvider.tsx
Normal file
133
gitgram/mobile/components/common/Lightbox/LightboxProvider.tsx
Normal file
@ -0,0 +1,133 @@
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
Platform,
|
||||
} from 'react-native';
|
||||
import ImageView from 'react-native-image-viewing';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
|
||||
import { useLightboxStore } from './lightboxStore';
|
||||
|
||||
/**
|
||||
* App-wide fullscreen image lightbox. Mounted once near the root so any screen
|
||||
* can call `useLightbox()` to present a zoomable, swipeable image viewer with
|
||||
* swipe-down-to-dismiss.
|
||||
*
|
||||
* Built on react-native-image-viewing (gesture-handler based, no reanimated),
|
||||
* adapted to the product's dark theme with a custom header (close + counter)
|
||||
* and an alt-text caption footer.
|
||||
*/
|
||||
export function LightboxProvider() {
|
||||
const { visible, images, initialIndex, close } = useLightboxStore();
|
||||
const [currentIndex, setCurrentIndex] = useState(initialIndex);
|
||||
|
||||
// Keep local index in sync whenever the lightbox (re)opens.
|
||||
const onIndexChange = useCallback((index: number) => {
|
||||
setCurrentIndex(index);
|
||||
}, []);
|
||||
|
||||
const renderHeader = useCallback(
|
||||
({ imageIndex }: { imageIndex: number }) => (
|
||||
<SafeAreaView edges={['top']} style={styles.headerSafeArea}>
|
||||
<View style={styles.header}>
|
||||
<TouchableOpacity
|
||||
onPress={close}
|
||||
style={styles.closeButton}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close image viewer"
|
||||
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
|
||||
>
|
||||
<Icon name="close" size={28} color="#FFFFFF" />
|
||||
</TouchableOpacity>
|
||||
{images.length > 1 && (
|
||||
<Text style={styles.counter}>
|
||||
{imageIndex + 1} / {images.length}
|
||||
</Text>
|
||||
)}
|
||||
<View style={styles.closeButton} />
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
),
|
||||
[close, images.length],
|
||||
);
|
||||
|
||||
const renderFooter = useCallback(
|
||||
({ imageIndex }: { imageIndex: number }) => {
|
||||
const alt = images[imageIndex]?.alt;
|
||||
if (!alt) return <View />;
|
||||
return (
|
||||
<SafeAreaView edges={['bottom']} style={styles.footerSafeArea}>
|
||||
<View style={styles.footer}>
|
||||
<Text style={styles.altText} numberOfLines={4}>
|
||||
{alt}
|
||||
</Text>
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
},
|
||||
[images],
|
||||
);
|
||||
|
||||
if (!visible || images.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ImageView
|
||||
images={images.map((image) => ({ uri: image.uri }))}
|
||||
imageIndex={initialIndex}
|
||||
visible={visible}
|
||||
onRequestClose={close}
|
||||
onImageIndexChange={onIndexChange}
|
||||
swipeToCloseEnabled
|
||||
doubleTapToZoomEnabled
|
||||
presentationStyle="overFullScreen"
|
||||
animationType={Platform.OS === 'ios' ? 'fade' : 'none'}
|
||||
backgroundColor="#000000"
|
||||
HeaderComponent={renderHeader}
|
||||
FooterComponent={renderFooter}
|
||||
keyExtractor={(_, index) => `lightbox-${currentIndex}-${index}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
headerSafeArea: {
|
||||
width: '100%',
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 8,
|
||||
},
|
||||
closeButton: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
counter: {
|
||||
color: '#FFFFFF',
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
footerSafeArea: {
|
||||
width: '100%',
|
||||
},
|
||||
footer: {
|
||||
paddingHorizontal: 16,
|
||||
paddingVertical: 12,
|
||||
backgroundColor: 'rgba(0,0,0,0.55)',
|
||||
},
|
||||
altText: {
|
||||
color: '#FFFFFF',
|
||||
fontSize: 14,
|
||||
lineHeight: 20,
|
||||
},
|
||||
});
|
||||
4
gitgram/mobile/components/common/Lightbox/index.ts
Normal file
4
gitgram/mobile/components/common/Lightbox/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export { LightboxProvider } from './LightboxProvider';
|
||||
export { useLightbox } from './useLightbox';
|
||||
export { useLightboxStore } from './lightboxStore';
|
||||
export type { LightboxImage } from './lightboxStore';
|
||||
46
gitgram/mobile/components/common/Lightbox/lightboxStore.ts
Normal file
46
gitgram/mobile/components/common/Lightbox/lightboxStore.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import { create } from 'zustand';
|
||||
|
||||
export interface LightboxImage {
|
||||
uri: string;
|
||||
// Optional accessible description for the image.
|
||||
alt?: string;
|
||||
}
|
||||
|
||||
interface LightboxState {
|
||||
visible: boolean;
|
||||
images: LightboxImage[];
|
||||
initialIndex: number;
|
||||
|
||||
/** Open the fullscreen lightbox with one or more images. */
|
||||
open: (images: LightboxImage[], initialIndex?: number) => void;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
const sanitizeIndex = (index: number, length: number): number => {
|
||||
if (length === 0) return 0;
|
||||
if (index < 0) return 0;
|
||||
if (index >= length) return length - 1;
|
||||
return index;
|
||||
};
|
||||
|
||||
/**
|
||||
* Global state backing the app-wide image lightbox. Any component can call
|
||||
* `open([...])` to present a fullscreen, zoomable, swipeable image viewer.
|
||||
*/
|
||||
export const useLightboxStore = create<LightboxState>((set) => ({
|
||||
visible: false,
|
||||
images: [],
|
||||
initialIndex: 0,
|
||||
|
||||
open: (images, initialIndex = 0) => {
|
||||
const valid = images.filter((image) => Boolean(image?.uri));
|
||||
if (valid.length === 0) return;
|
||||
set({
|
||||
visible: true,
|
||||
images: valid,
|
||||
initialIndex: sanitizeIndex(initialIndex, valid.length),
|
||||
});
|
||||
},
|
||||
|
||||
close: () => set({ visible: false }),
|
||||
}));
|
||||
24
gitgram/mobile/components/common/Lightbox/useLightbox.ts
Normal file
24
gitgram/mobile/components/common/Lightbox/useLightbox.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { useCallback } from 'react';
|
||||
|
||||
import { useLightboxStore, LightboxImage } from './lightboxStore';
|
||||
|
||||
/**
|
||||
* Convenience hook to open the global lightbox from any component.
|
||||
*
|
||||
* Usage:
|
||||
* const openLightbox = useLightbox();
|
||||
* openLightbox([{ uri, alt }], 0);
|
||||
*/
|
||||
export function useLightbox(): (
|
||||
images: LightboxImage[],
|
||||
initialIndex?: number,
|
||||
) => void {
|
||||
const open = useLightboxStore((state) => state.open);
|
||||
|
||||
return useCallback(
|
||||
(images: LightboxImage[], initialIndex = 0) => {
|
||||
open(images, initialIndex);
|
||||
},
|
||||
[open],
|
||||
);
|
||||
}
|
||||
97
gitgram/mobile/components/common/LikeBounceAnimation.tsx
Normal file
97
gitgram/mobile/components/common/LikeBounceAnimation.tsx
Normal file
@ -0,0 +1,97 @@
|
||||
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
|
||||
import { Animated, StyleSheet, ViewStyle, StyleProp } from 'react-native';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
|
||||
const AnimationValues = {
|
||||
opacity: { initial: 0, final: 1 },
|
||||
bounce: { initial: 0.4, final: 1 },
|
||||
};
|
||||
|
||||
export interface LikeBounceAnimationHandle {
|
||||
animate: () => void;
|
||||
}
|
||||
|
||||
interface LikeBounceAnimationProps {
|
||||
// Diameter of the heart burst. Defaults to a large Instagram-style burst.
|
||||
size?: number;
|
||||
// Heart fill color. Defaults to white for overlays on imagery.
|
||||
color?: string;
|
||||
// Override container positioning (e.g. for full-screen media).
|
||||
style?: StyleProp<ViewStyle>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Animated heart-burst overlay for double-tap-to-like. Exposes an imperative
|
||||
* `animate()` via ref so the parent fires the burst on a recognised double tap.
|
||||
*
|
||||
* Ported from proximity's LikeBounceAnimation: pure react-native Animated
|
||||
* (spring scale + fade in/out), no reanimated dependency.
|
||||
*/
|
||||
const LikeBounceAnimation = forwardRef<LikeBounceAnimationHandle, LikeBounceAnimationProps>(
|
||||
({ size = 96, color = '#FFFFFF', style }, ref) => {
|
||||
const [animating, setAnimating] = useState(false);
|
||||
const likeOpacity = useRef(new Animated.Value(AnimationValues.opacity.initial)).current;
|
||||
const likeBounce = useRef(new Animated.Value(AnimationValues.bounce.initial)).current;
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
animate: () => {
|
||||
if (animating) return;
|
||||
setAnimating(true);
|
||||
|
||||
const opacityConfig = { duration: 250, useNativeDriver: true };
|
||||
|
||||
Animated.parallel([
|
||||
Animated.spring(likeBounce, {
|
||||
toValue: AnimationValues.bounce.final,
|
||||
friction: 2,
|
||||
useNativeDriver: true,
|
||||
}),
|
||||
Animated.timing(likeOpacity, {
|
||||
toValue: AnimationValues.opacity.final,
|
||||
...opacityConfig,
|
||||
}),
|
||||
]).start(() => {
|
||||
Animated.timing(likeOpacity, {
|
||||
toValue: AnimationValues.opacity.initial,
|
||||
...opacityConfig,
|
||||
}).start(() => {
|
||||
likeBounce.setValue(AnimationValues.bounce.initial);
|
||||
setAnimating(false);
|
||||
});
|
||||
});
|
||||
},
|
||||
}),
|
||||
[animating, likeBounce, likeOpacity],
|
||||
);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
pointerEvents="none"
|
||||
style={[
|
||||
styles.container,
|
||||
style,
|
||||
{
|
||||
opacity: likeOpacity,
|
||||
transform: [{ scale: likeBounce }],
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Icon name="favorite" color={color} size={size} />
|
||||
</Animated.View>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
LikeBounceAnimation.displayName = 'LikeBounceAnimation';
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
});
|
||||
|
||||
export default LikeBounceAnimation;
|
||||
@ -1,8 +1,16 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, StyleSheet, StyleProp, ViewStyle } from 'react-native';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
StyleProp,
|
||||
ViewStyle,
|
||||
TouchableOpacity,
|
||||
} from 'react-native';
|
||||
import { Image, ImageContentFit } from 'expo-image';
|
||||
import { Colors } from '../../constants/Colors';
|
||||
import SkeletonLoader from './SkeletonLoader';
|
||||
import { useLightbox } from './Lightbox';
|
||||
|
||||
interface OptimizedImageProps {
|
||||
source: string | { uri: string };
|
||||
@ -13,6 +21,13 @@ interface OptimizedImageProps {
|
||||
showSkeleton?: boolean;
|
||||
aspectRatio?: number;
|
||||
borderRadius?: number;
|
||||
// Accessible description of the image. Drives the screen-reader label and the
|
||||
// "ALT" badge overlay (Bluesky-style accessibility affordance).
|
||||
alt?: string;
|
||||
// Show an "ALT" badge overlay when alt text is present.
|
||||
showAltBadge?: boolean;
|
||||
// When true, tapping the image opens the global fullscreen lightbox.
|
||||
enableLightbox?: boolean;
|
||||
}
|
||||
|
||||
// Default blurhash for loading state
|
||||
@ -27,9 +42,13 @@ export default function OptimizedImage({
|
||||
showSkeleton = true,
|
||||
aspectRatio,
|
||||
borderRadius = 0,
|
||||
alt,
|
||||
showAltBadge = true,
|
||||
enableLightbox = false,
|
||||
}: OptimizedImageProps) {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [hasError, setHasError] = useState(false);
|
||||
const openLightbox = useLightbox();
|
||||
|
||||
const uri = typeof source === 'string' ? source : source.uri;
|
||||
|
||||
@ -67,8 +86,8 @@ export default function OptimizedImage({
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={[style, aspectRatio ? { aspectRatio } : {}]}>
|
||||
const imageContent = (
|
||||
<>
|
||||
{isLoading && showSkeleton && (
|
||||
<View style={[StyleSheet.absoluteFill, { borderRadius }]}>
|
||||
<SkeletonLoader
|
||||
@ -93,9 +112,34 @@ export default function OptimizedImage({
|
||||
onLoadStart={handleLoadStart}
|
||||
onLoadEnd={handleLoadEnd}
|
||||
onError={handleError}
|
||||
accessible={!!alt}
|
||||
accessibilityLabel={alt}
|
||||
/>
|
||||
</View>
|
||||
{!!alt && showAltBadge && (
|
||||
<View style={styles.altBadge} pointerEvents="none">
|
||||
<Text style={styles.altBadgeText}>ALT</Text>
|
||||
</View>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
const containerStyle = [style, aspectRatio ? { aspectRatio } : {}];
|
||||
|
||||
if (enableLightbox) {
|
||||
return (
|
||||
<TouchableOpacity
|
||||
style={containerStyle}
|
||||
activeOpacity={0.9}
|
||||
onPress={() => openLightbox([{ uri, alt }], 0)}
|
||||
accessibilityRole="imagebutton"
|
||||
accessibilityLabel={alt || 'Open image'}
|
||||
>
|
||||
{imageContent}
|
||||
</TouchableOpacity>
|
||||
);
|
||||
}
|
||||
|
||||
return <View style={containerStyle}>{imageContent}</View>;
|
||||
}
|
||||
|
||||
// Pre-configured variants for common use cases
|
||||
@ -164,6 +208,21 @@ const styles = StyleSheet.create({
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
},
|
||||
altBadge: {
|
||||
position: 'absolute',
|
||||
left: 8,
|
||||
bottom: 8,
|
||||
backgroundColor: 'rgba(0,0,0,0.65)',
|
||||
borderRadius: 4,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
},
|
||||
altBadgeText: {
|
||||
color: '#FFFFFF',
|
||||
fontSize: 10,
|
||||
fontWeight: '700',
|
||||
letterSpacing: 0.5,
|
||||
},
|
||||
errorContainer: {
|
||||
backgroundColor: Colors.surface,
|
||||
justifyContent: 'center',
|
||||
|
||||
36
gitgram/mobile/hooks/useHaptics.ts
Normal file
36
gitgram/mobile/hooks/useHaptics.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { useCallback } from 'react';
|
||||
import { Platform } from 'react-native';
|
||||
import * as Haptics from 'expo-haptics';
|
||||
|
||||
import { useSettingsStore } from '../store/settingsStore';
|
||||
|
||||
export type HapticStrength = 'Light' | 'Medium' | 'Heavy';
|
||||
|
||||
/**
|
||||
* Returns a stable callback that fires a tactile impact, respecting the user's
|
||||
* "disable haptics" preference. Ported from Bluesky's useHaptics hook.
|
||||
*
|
||||
* Android's medium/heavy impacts feel too strong, so non-iOS platforms always
|
||||
* use the Light style regardless of the requested strength.
|
||||
*/
|
||||
export function useHaptics(): (strength?: HapticStrength) => void {
|
||||
const hapticsDisabled = useSettingsStore((state) => state.hapticsDisabled);
|
||||
|
||||
return useCallback(
|
||||
(strength: HapticStrength = 'Medium') => {
|
||||
if (hapticsDisabled || Platform.OS === 'web') {
|
||||
return;
|
||||
}
|
||||
|
||||
const style =
|
||||
Platform.OS === 'ios'
|
||||
? Haptics.ImpactFeedbackStyle[strength]
|
||||
: Haptics.ImpactFeedbackStyle.Light;
|
||||
|
||||
// impactAsync returns a promise; fire-and-forget is intentional and any
|
||||
// failure (e.g. unsupported device) must not interrupt the interaction.
|
||||
void Haptics.impactAsync(style).catch(() => {});
|
||||
},
|
||||
[hapticsDisabled],
|
||||
);
|
||||
}
|
||||
@ -35,6 +35,7 @@
|
||||
"expo-device": "^8.0.9",
|
||||
"expo-document-picker": "^14.0.7",
|
||||
"expo-file-system": "^19.0.21",
|
||||
"expo-haptics": "~15.0.8",
|
||||
"expo-image": "^3.0.10",
|
||||
"expo-image-manipulator": "^14.0.7",
|
||||
"expo-image-picker": "^17.0.8",
|
||||
@ -50,6 +51,7 @@
|
||||
"react-native": "0.81.5",
|
||||
"react-native-elements": "^3.4.3",
|
||||
"react-native-gesture-handler": "^2.29.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-maps": "^1.26.18",
|
||||
"react-native-safe-area-context": "^5.6.2",
|
||||
"react-native-screens": "^4.18.0",
|
||||
|
||||
64
gitgram/mobile/store/settingsStore.ts
Normal file
64
gitgram/mobile/store/settingsStore.ts
Normal file
@ -0,0 +1,64 @@
|
||||
import { create } from 'zustand';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { logger } from '../utils/logger';
|
||||
|
||||
const HAPTICS_DISABLED_KEY = 'settings:hapticsDisabled';
|
||||
const ALT_TEXT_REQUIRED_KEY = 'settings:altTextRequired';
|
||||
|
||||
interface SettingsState {
|
||||
// Whether tactile haptic feedback is disabled across the app.
|
||||
hapticsDisabled: boolean;
|
||||
// Whether the composer requires alt text on every image before posting.
|
||||
altTextRequired: boolean;
|
||||
// True once persisted preferences have been read from storage.
|
||||
hydrated: boolean;
|
||||
|
||||
hydrate: () => Promise<void>;
|
||||
setHapticsDisabled: (disabled: boolean) => Promise<void>;
|
||||
setAltTextRequired: (required: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight, app-wide user preferences persisted to AsyncStorage. Kept
|
||||
* separate from authStore so settings survive logout and stay focused.
|
||||
*/
|
||||
export const useSettingsStore = create<SettingsState>((set) => ({
|
||||
hapticsDisabled: false,
|
||||
altTextRequired: false,
|
||||
hydrated: false,
|
||||
|
||||
hydrate: async () => {
|
||||
try {
|
||||
const [hapticsValue, altTextValue] = await Promise.all([
|
||||
AsyncStorage.getItem(HAPTICS_DISABLED_KEY),
|
||||
AsyncStorage.getItem(ALT_TEXT_REQUIRED_KEY),
|
||||
]);
|
||||
set({
|
||||
hapticsDisabled: hapticsValue === 'true',
|
||||
altTextRequired: altTextValue === 'true',
|
||||
hydrated: true,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to hydrate settings:', error);
|
||||
set({ hydrated: true });
|
||||
}
|
||||
},
|
||||
|
||||
setHapticsDisabled: async (disabled: boolean) => {
|
||||
set({ hapticsDisabled: disabled });
|
||||
try {
|
||||
await AsyncStorage.setItem(HAPTICS_DISABLED_KEY, disabled ? 'true' : 'false');
|
||||
} catch (error) {
|
||||
logger.error('Failed to persist hapticsDisabled:', error);
|
||||
}
|
||||
},
|
||||
|
||||
setAltTextRequired: async (required: boolean) => {
|
||||
set({ altTextRequired: required });
|
||||
try {
|
||||
await AsyncStorage.setItem(ALT_TEXT_REQUIRED_KEY, required ? 'true' : 'false');
|
||||
} catch (error) {
|
||||
logger.error('Failed to persist altTextRequired:', error);
|
||||
}
|
||||
},
|
||||
}));
|
||||
@ -4,6 +4,7 @@ import { useParams, useRouter } from 'next/navigation'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
import { postService } from '@/services/postService'
|
||||
import PostCard from '@/components/PostCard'
|
||||
import MuteThreadButton from '@/components/MuteThreadButton'
|
||||
|
||||
export default function PostDetailPage() {
|
||||
const params = useParams()
|
||||
@ -24,6 +25,9 @@ export default function PostDetailPage() {
|
||||
post={post}
|
||||
onLike={(id: string) => { postService.likePost(id).then(() => setPost({...post, isLiked: true, likesCount: post.likesCount + 1})) }}
|
||||
/>
|
||||
<div className="mt-3 flex justify-end">
|
||||
<MuteThreadButton postId={params.id as string} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
271
gitgram/web/app/settings/moderation/page.tsx
Normal file
271
gitgram/web/app/settings/moderation/page.tsx
Normal file
@ -0,0 +1,271 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* ModerationSettingsPage — /settings/moderation
|
||||
*
|
||||
* Self-contained content moderation controls:
|
||||
* - Muted words / phrases (content + hashtag targets)
|
||||
* - Muted accounts (soft hide-without-block)
|
||||
*
|
||||
* State is client-side (localStorage) via utils/moderation and applied in the
|
||||
* feed by Feed.tsx. Thread muting is driven elsewhere (post menus) but shares
|
||||
* the same store.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
import { useModeration } from '@/hooks/useModeration'
|
||||
import {
|
||||
addMutedWord,
|
||||
removeMutedWord,
|
||||
muteAccount,
|
||||
unmuteAccount,
|
||||
type MutedWordTarget,
|
||||
} from '@/utils/moderation'
|
||||
|
||||
const MAX_WORD_LENGTH = 100
|
||||
|
||||
export default function ModerationSettingsPage() {
|
||||
const router = useRouter()
|
||||
const { isAuthenticated } = useAuthStore()
|
||||
const moderation = useModeration()
|
||||
|
||||
const [wordInput, setWordInput] = useState('')
|
||||
const [wordTarget, setWordTarget] = useState<MutedWordTarget>('content')
|
||||
const [wordError, setWordError] = useState<string | null>(null)
|
||||
|
||||
const [accountInput, setAccountInput] = useState('')
|
||||
const [accountError, setAccountError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) router.replace('/login')
|
||||
}, [isAuthenticated, router])
|
||||
|
||||
const handleAddWord = useCallback(() => {
|
||||
const trimmed = wordInput.trim()
|
||||
if (!trimmed) {
|
||||
setWordError('Enter a word or phrase to mute')
|
||||
return
|
||||
}
|
||||
if (trimmed.length > MAX_WORD_LENGTH) {
|
||||
setWordError(`Must be ${MAX_WORD_LENGTH} characters or fewer`)
|
||||
return
|
||||
}
|
||||
addMutedWord(trimmed, wordTarget)
|
||||
setWordInput('')
|
||||
setWordError(null)
|
||||
}, [wordInput, wordTarget])
|
||||
|
||||
const handleAddAccount = useCallback(() => {
|
||||
const trimmed = accountInput.trim().replace(/^@/, '')
|
||||
if (!trimmed) {
|
||||
setAccountError('Enter a username to mute')
|
||||
return
|
||||
}
|
||||
if (!/^[a-zA-Z0-9_.-]+$/.test(trimmed)) {
|
||||
setAccountError('Enter a valid username')
|
||||
return
|
||||
}
|
||||
muteAccount(trimmed)
|
||||
setAccountInput('')
|
||||
setAccountError(null)
|
||||
}, [accountInput])
|
||||
|
||||
if (!isAuthenticated) return null
|
||||
|
||||
const inputClass =
|
||||
'w-full px-4 py-3 bg-[var(--background)] border border-[var(--border)] rounded-lg text-[var(--foreground)] placeholder-[var(--foreground-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--primary)] transition-colors text-sm'
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto py-8 px-4 space-y-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-[var(--foreground)]">Moderation</h1>
|
||||
<p className="text-sm text-[var(--foreground-secondary)] mt-1">
|
||||
Hide posts that contain certain words or come from certain accounts. These filters apply
|
||||
on this device.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.back()}
|
||||
className="text-sm text-[var(--foreground-secondary)] hover:text-[var(--foreground)] transition-colors"
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Muted words */}
|
||||
<section className="p-6 bg-[var(--surface)] border border-[var(--border)] rounded-xl space-y-4">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-[var(--foreground)]">Muted words & tags</h2>
|
||||
<p className="text-xs text-[var(--foreground-secondary)] mt-1">
|
||||
Posts containing a muted word — or a muted hashtag — are hidden from your feed.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={wordInput}
|
||||
onChange={(e) => {
|
||||
setWordInput(e.target.value)
|
||||
setWordError(null)
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
handleAddWord()
|
||||
}
|
||||
}}
|
||||
placeholder={wordTarget === 'tag' ? 'hashtag (without #)' : 'word or phrase'}
|
||||
maxLength={MAX_WORD_LENGTH}
|
||||
className={`${inputClass} flex-1`}
|
||||
aria-label="Word or phrase to mute"
|
||||
/>
|
||||
<select
|
||||
value={wordTarget}
|
||||
onChange={(e) => setWordTarget(e.target.value as MutedWordTarget)}
|
||||
className="px-3 py-3 bg-[var(--background)] border border-[var(--border)] rounded-lg text-sm text-[var(--foreground)] focus:outline-none focus:ring-2 focus:ring-[var(--primary)]"
|
||||
aria-label="Where to match"
|
||||
>
|
||||
<option value="content">Text & tags</option>
|
||||
<option value="tag">Hashtags only</option>
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddWord}
|
||||
className="px-4 py-3 bg-[var(--primary)] text-white rounded-lg text-sm font-semibold hover:bg-[var(--primary)]/90 transition-colors whitespace-nowrap"
|
||||
>
|
||||
Mute word
|
||||
</button>
|
||||
</div>
|
||||
{wordError && (
|
||||
<p className="text-xs text-[var(--error)]" role="alert">
|
||||
{wordError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{moderation.mutedWords.length === 0 ? (
|
||||
<p className="text-sm text-[var(--foreground-secondary)] py-2">No muted words yet.</p>
|
||||
) : (
|
||||
<ul className="flex flex-wrap gap-2">
|
||||
{moderation.mutedWords.map((word) => (
|
||||
<li
|
||||
key={`${word.target}:${word.value}`}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm bg-[var(--surface-secondary)] border border-[var(--border)] text-[var(--foreground)]"
|
||||
>
|
||||
<span>
|
||||
{word.target === 'tag' ? '#' : ''}
|
||||
{word.value}
|
||||
</span>
|
||||
<span className="text-[10px] uppercase tracking-wide text-[var(--foreground-secondary)]">
|
||||
{word.target === 'tag' ? 'tag' : 'text'}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeMutedWord(word.value, word.target)}
|
||||
aria-label={`Unmute ${word.value}`}
|
||||
className="ml-0.5 text-[var(--foreground-secondary)] hover:text-[var(--error)] transition-colors"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Muted accounts */}
|
||||
<section className="p-6 bg-[var(--surface)] border border-[var(--border)] rounded-xl space-y-4">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-[var(--foreground)]">Muted accounts</h2>
|
||||
<p className="text-xs text-[var(--foreground-secondary)] mt-1">
|
||||
Muting hides an account's posts from your feed without blocking them. They are not
|
||||
notified.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<span className="absolute inset-y-0 left-4 flex items-center text-[var(--foreground-secondary)] text-sm pointer-events-none">
|
||||
@
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
value={accountInput}
|
||||
onChange={(e) => {
|
||||
setAccountInput(e.target.value)
|
||||
setAccountError(null)
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
handleAddAccount()
|
||||
}
|
||||
}}
|
||||
placeholder="username"
|
||||
className={`${inputClass} pl-8`}
|
||||
aria-label="Username to mute"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddAccount}
|
||||
className="px-4 py-3 bg-[var(--primary)] text-white rounded-lg text-sm font-semibold hover:bg-[var(--primary)]/90 transition-colors whitespace-nowrap"
|
||||
>
|
||||
Mute account
|
||||
</button>
|
||||
</div>
|
||||
{accountError && (
|
||||
<p className="text-xs text-[var(--error)]" role="alert">
|
||||
{accountError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{moderation.mutedAccounts.length === 0 ? (
|
||||
<p className="text-sm text-[var(--foreground-secondary)] py-2">No muted accounts yet.</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-[var(--border)]">
|
||||
{moderation.mutedAccounts.map((account) => (
|
||||
<li key={account} className="flex items-center justify-between py-3">
|
||||
<span className="text-sm font-medium text-[var(--foreground)]">@{account}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => unmuteAccount(account)}
|
||||
className="text-sm text-[var(--foreground-secondary)] hover:text-[var(--foreground)] underline transition-colors"
|
||||
>
|
||||
Unmute
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Muted threads summary */}
|
||||
{moderation.mutedThreads.length > 0 && (
|
||||
<section className="p-6 bg-[var(--surface)] border border-[var(--border)] rounded-xl space-y-2">
|
||||
<h2 className="text-base font-semibold text-[var(--foreground)]">Muted threads</h2>
|
||||
<p className="text-sm text-[var(--foreground-secondary)]">
|
||||
You have muted {moderation.mutedThreads.length} thread
|
||||
{moderation.mutedThreads.length === 1 ? '' : 's'}. Mute or unmute a thread from a
|
||||
post's menu.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -25,6 +25,7 @@ export default function SettingsPage() {
|
||||
{ title: 'Appearance', href: '/settings/appearance', icon: '🎨', desc: 'Theme, font size, language, density' },
|
||||
{ title: 'Security', href: '/settings/security', icon: '🛡️', desc: 'Sessions, login history, 2FA' },
|
||||
{ title: 'Blocked Users', href: '/settings/blocked', icon: '🚫', desc: 'Manage blocked accounts' },
|
||||
{ title: 'Moderation', href: '/settings/moderation', icon: '🔇', desc: 'Muted words, accounts, and threads' },
|
||||
{ title: 'Language', href: '/settings/language', icon: '🌐', desc: 'Display language and region' },
|
||||
{ title: 'Data & Storage', href: '/settings/data', icon: '💾', desc: 'Cache, downloads, data export' },
|
||||
{ title: 'Subscription', href: '/settings/subscription', icon: '⭐', desc: 'Plan, billing, premium features' },
|
||||
|
||||
@ -26,6 +26,7 @@ import { userService } from '@/services/userService'
|
||||
import { githubService } from '@/services/githubService'
|
||||
import { useToast } from '@/components/ui/toast'
|
||||
import { getErrorMessage } from '@/utils/error'
|
||||
import CropImageDialog from '@/components/CropImageDialog'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
@ -33,6 +34,9 @@ import { getErrorMessage } from '@/utils/error'
|
||||
|
||||
const BIO_MAX_LENGTH = 160
|
||||
const USERNAME_DEBOUNCE_MS = 500
|
||||
const AVATAR_MAX_BYTES = 5 * 1024 * 1024 // 5 MB
|
||||
const AVATAR_ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
|
||||
const AVATAR_ASPECT_RATIO = 1 // square
|
||||
const PRONOUNS_PRESETS = ['he/him', 'she/her', 'they/them', 'he/they', 'she/they', 'custom'] as const
|
||||
|
||||
const URL_PATTERN =
|
||||
@ -182,6 +186,8 @@ export default function ProfileEditPage() {
|
||||
const [avatarPreview, setAvatarPreview] = useState<string>(user?.avatar ?? '')
|
||||
const [uploadingAvatar, setUploadingAvatar] = useState(false)
|
||||
const avatarInputRef = useRef<HTMLInputElement>(null)
|
||||
// Source object URL for the crop dialog (null when closed)
|
||||
const [cropSrc, setCropSrc] = useState<string | null>(null)
|
||||
|
||||
// Username availability
|
||||
const [usernameAvail, setUsernameAvail] = useState<UsernameAvailability>({
|
||||
@ -280,30 +286,66 @@ export default function ProfileEditPage() {
|
||||
// Avatar upload
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
// Step 1: validate the selected file and open the crop dialog.
|
||||
const handleAvatarFileChange = useCallback(
|
||||
async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
(e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
// Reset input immediately so the same file can be re-selected later.
|
||||
if (avatarInputRef.current) avatarInputRef.current.value = ''
|
||||
if (!file) return
|
||||
|
||||
// Local preview
|
||||
const objectUrl = URL.createObjectURL(file)
|
||||
setAvatarPreview(objectUrl)
|
||||
if (!AVATAR_ALLOWED_TYPES.includes(file.type)) {
|
||||
showToast('Please choose a JPG, PNG, GIF, or WebP image', 'error')
|
||||
return
|
||||
}
|
||||
if (file.size > AVATAR_MAX_BYTES) {
|
||||
showToast('Image must be 5 MB or smaller', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
// Hand the raw image to the crop dialog; revoke any previous source.
|
||||
setCropSrc((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev)
|
||||
return URL.createObjectURL(file)
|
||||
})
|
||||
},
|
||||
[showToast],
|
||||
)
|
||||
|
||||
const closeCropDialog = useCallback(() => {
|
||||
setCropSrc((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev)
|
||||
return null
|
||||
})
|
||||
}, [])
|
||||
|
||||
// Step 2: receive the cropped webp blob and upload it.
|
||||
const handleCroppedAvatar = useCallback(
|
||||
async (blob: Blob | null) => {
|
||||
if (!blob) {
|
||||
showToast('Could not process the image. Please try again.', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
const croppedFile = new File([blob], 'avatar.webp', { type: 'image/webp' })
|
||||
|
||||
// Optimistic local preview of the cropped result.
|
||||
const previewUrl = URL.createObjectURL(croppedFile)
|
||||
const previousPreview = form.avatarUrl
|
||||
setAvatarPreview(previewUrl)
|
||||
|
||||
setUploadingAvatar(true)
|
||||
try {
|
||||
const { avatarUrl } = await userService.uploadAvatarFile(file)
|
||||
const { avatarUrl } = await userService.uploadAvatarFile(croppedFile)
|
||||
updateField('avatarUrl', avatarUrl)
|
||||
setAvatarPreview(avatarUrl)
|
||||
showToast('Avatar uploaded!', 'success')
|
||||
} catch (err) {
|
||||
showToast(getErrorMessage(err), 'error')
|
||||
// Revert preview on failure
|
||||
setAvatarPreview(form.avatarUrl)
|
||||
setAvatarPreview(previousPreview)
|
||||
} finally {
|
||||
setUploadingAvatar(false)
|
||||
// Reset input so the same file can be re-selected if needed
|
||||
if (avatarInputRef.current) avatarInputRef.current.value = ''
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
URL.revokeObjectURL(previewUrl)
|
||||
}
|
||||
},
|
||||
[form.avatarUrl, updateField, showToast],
|
||||
@ -790,6 +832,17 @@ export default function ProfileEditPage() {
|
||||
{saving ? 'Saving…' : 'Save changes'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Avatar crop dialog */}
|
||||
{cropSrc && (
|
||||
<CropImageDialog
|
||||
src={cropSrc}
|
||||
cropAspectRatio={AVATAR_ASPECT_RATIO}
|
||||
onCropped={handleCroppedAvatar}
|
||||
onClose={closeCropDialog}
|
||||
title="Crop your photo"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import { useState, useCallback } from 'react'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
import Link from 'next/link'
|
||||
import api from '@/services/api'
|
||||
import { linkifyText } from '@/utils/linkify'
|
||||
|
||||
interface Comment {
|
||||
id: string
|
||||
@ -170,7 +171,7 @@ export default function CommentThread({
|
||||
</div>
|
||||
|
||||
<p className="text-sm mt-1 whitespace-pre-wrap break-words">
|
||||
{comment.content}
|
||||
{linkifyText(comment.content)}
|
||||
</p>
|
||||
|
||||
<div className="flex items-center gap-4 mt-2">
|
||||
|
||||
140
gitgram/web/components/CropImageDialog.tsx
Normal file
140
gitgram/web/components/CropImageDialog.tsx
Normal file
@ -0,0 +1,140 @@
|
||||
'use client'
|
||||
|
||||
import 'cropperjs/dist/cropper.css'
|
||||
import { useRef, useState, type ComponentType } from 'react'
|
||||
import { Cropper as RawCropper, type ReactCropperElement, type ReactCropperProps } from 'react-cropper'
|
||||
|
||||
// react-cropper ships types compiled against a different @types/react major
|
||||
// than this app, which makes TS reject it as a JSX component. Re-type it
|
||||
// against this app's React types (behaviour is identical at runtime).
|
||||
const Cropper = RawCropper as unknown as ComponentType<
|
||||
ReactCropperProps & { ref?: React.Ref<ReactCropperElement> }
|
||||
>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface CropImageDialogProps {
|
||||
/** Object URL of the source image to crop. */
|
||||
src: string
|
||||
/** Aspect ratio for the crop box (width / height). e.g. 1 for square avatar. */
|
||||
cropAspectRatio: number
|
||||
/** Receives the cropped image as a webp Blob, or null if the canvas failed. */
|
||||
onCropped: (blob: Blob | null) => void
|
||||
/** Called when the dialog should close (cancel or after crop). */
|
||||
onClose: () => void
|
||||
/** Optional title shown in the header. */
|
||||
title?: string
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Modal crop + resize dialog. Produces an aspect-correct webp Blob via the
|
||||
* cropper canvas. Adapted from the nextjs-15 social app's CropImageDialog to
|
||||
* the product's plain-overlay modal convention (matching ContentComposer's
|
||||
* checkpoint picker) and CSS-variable dark theme.
|
||||
*/
|
||||
export default function CropImageDialog({
|
||||
src,
|
||||
cropAspectRatio,
|
||||
onCropped,
|
||||
onClose,
|
||||
title = 'Crop image',
|
||||
}: CropImageDialogProps) {
|
||||
const cropperRef = useRef<ReactCropperElement>(null)
|
||||
const [processing, setProcessing] = useState(false)
|
||||
|
||||
const handleCrop = () => {
|
||||
const cropper = cropperRef.current?.cropper
|
||||
if (!cropper) return
|
||||
|
||||
setProcessing(true)
|
||||
// getCroppedCanvas is bounded to avoid oversized uploads.
|
||||
const canvas = cropper.getCroppedCanvas({
|
||||
maxWidth: 1024,
|
||||
maxHeight: 1024,
|
||||
imageSmoothingQuality: 'high',
|
||||
})
|
||||
|
||||
if (!canvas) {
|
||||
setProcessing(false)
|
||||
onCropped(null)
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
setProcessing(false)
|
||||
onCropped(blob)
|
||||
onClose()
|
||||
},
|
||||
'image/webp',
|
||||
0.9,
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
>
|
||||
<div className="w-full max-w-lg space-y-4 rounded-xl border border-[var(--border)] bg-[var(--surface)] p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-bold text-[var(--foreground)]">{title}</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
className="p-1 text-[var(--foreground-secondary)] transition-colors hover:text-[var(--foreground)]"
|
||||
>
|
||||
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="overflow-hidden rounded-lg bg-[var(--background)]">
|
||||
<Cropper
|
||||
src={src}
|
||||
aspectRatio={cropAspectRatio}
|
||||
guides={false}
|
||||
viewMode={1}
|
||||
dragMode="move"
|
||||
background={false}
|
||||
autoCropArea={1}
|
||||
responsive
|
||||
checkOrientation={false}
|
||||
ref={cropperRef}
|
||||
className="mx-auto max-h-[60vh] w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={processing}
|
||||
className="rounded-lg border border-[var(--border)] px-4 py-2 text-sm font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--surface-secondary)] disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCrop}
|
||||
disabled={processing}
|
||||
className="rounded-lg bg-[var(--primary)] px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-[var(--primary)]/90 disabled:opacity-50"
|
||||
>
|
||||
{processing ? 'Processing…' : 'Crop & Upload'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -8,6 +8,8 @@ import RichContent from './RichContent';
|
||||
import AitmChangeStoryCard from './AitmChangeStoryCard';
|
||||
import BookmarkButton from './BookmarkButton';
|
||||
import { parseAitmChangeStoryBlock } from '@/utils/aitmChangeStory';
|
||||
import { useModeration } from '@/hooks/useModeration';
|
||||
import { isPostMuted } from '@/utils/moderation';
|
||||
import api from '@/services/api';
|
||||
|
||||
interface Post {
|
||||
@ -68,6 +70,7 @@ const ACCOUNT_BADGES = {
|
||||
export default function Feed() {
|
||||
const queryClient = useQueryClient();
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
const moderation = useModeration();
|
||||
|
||||
// ── Infinite feed query ────────────────────────────────────────────────────
|
||||
const {
|
||||
@ -84,9 +87,19 @@ export default function Feed() {
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
|
||||
});
|
||||
|
||||
const posts = data?.pages.flatMap((p) => p.posts) ?? [];
|
||||
const allPosts = data?.pages.flatMap((p) => p.posts) ?? [];
|
||||
const isDiscover = data?.pages[0]?.isDiscover;
|
||||
|
||||
// Apply client-side moderation (muted words / accounts / threads).
|
||||
const posts = allPosts.filter(
|
||||
(post) =>
|
||||
!isPostMuted(
|
||||
{ id: post.id, content: post.content ?? '', username: post.account.username },
|
||||
moderation,
|
||||
),
|
||||
);
|
||||
const mutedCount = allPosts.length - posts.length;
|
||||
|
||||
// ── Intersection Observer for infinite scroll ──────────────────────────────
|
||||
const onIntersect = useCallback(
|
||||
(entries: IntersectionObserverEntry[]) => {
|
||||
@ -183,6 +196,19 @@ export default function Feed() {
|
||||
}
|
||||
|
||||
if (!posts.length) {
|
||||
// Distinguish a genuinely empty feed from one fully hidden by moderation.
|
||||
if (mutedCount > 0) {
|
||||
return (
|
||||
<div className="text-center py-12 bg-white dark:bg-gray-800 rounded-lg">
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-4">
|
||||
All {mutedCount} post{mutedCount === 1 ? '' : 's'} here are hidden by your muted words or accounts.
|
||||
</p>
|
||||
<Link href="/settings/moderation" className="text-sm text-blue-600 hover:underline">
|
||||
Manage moderation filters
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="text-center py-12 bg-white dark:bg-gray-800 rounded-lg">
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-4">No posts yet</p>
|
||||
@ -204,6 +230,15 @@ export default function Feed() {
|
||||
</p>
|
||||
)}
|
||||
|
||||
{mutedCount > 0 && (
|
||||
<p className="text-xs text-center text-gray-400 dark:text-gray-500">
|
||||
{mutedCount} post{mutedCount === 1 ? '' : 's'} hidden by your{' '}
|
||||
<Link href="/settings/moderation" className="underline hover:text-gray-600 dark:hover:text-gray-300">
|
||||
moderation filters
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{trendingRepos.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-medium text-gray-500">Trending Repos</h3>
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
|
||||
import { useState, useCallback } from 'react'
|
||||
import { userService } from '@/services/userService'
|
||||
import { githubService } from '@/services/githubService'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@ -12,6 +14,12 @@ interface FollowButtonProps {
|
||||
username: string
|
||||
initialFollowing: boolean
|
||||
onFollowChange?: (isFollowing: boolean) => void
|
||||
/**
|
||||
* When provided, and the viewer has GitHub connected, the in-app follow is
|
||||
* mirrored to GitHub (PUT/DELETE /user/following/:username) in one click.
|
||||
* Failure of the GitHub sync never blocks the in-app follow.
|
||||
*/
|
||||
githubUsername?: string
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -23,7 +31,11 @@ export function FollowButton({
|
||||
username,
|
||||
initialFollowing,
|
||||
onFollowChange,
|
||||
githubUsername,
|
||||
}: FollowButtonProps) {
|
||||
const { user } = useAuthStore()
|
||||
const canSyncGitHub = Boolean(githubUsername && user?.githubId)
|
||||
|
||||
const [isFollowing, setIsFollowing] = useState(initialFollowing)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [isHovering, setIsHovering] = useState(false)
|
||||
@ -45,6 +57,20 @@ export function FollowButton({
|
||||
await userService.unfollow(userId)
|
||||
}
|
||||
onFollowChange?.(nextFollowing)
|
||||
|
||||
// Best-effort GitHub write-back. A failure here is surfaced but never
|
||||
// reverts the successful in-app follow.
|
||||
if (canSyncGitHub && githubUsername) {
|
||||
try {
|
||||
if (nextFollowing) {
|
||||
await githubService.followOnGitHub(githubUsername)
|
||||
} else {
|
||||
await githubService.unfollowOnGitHub(githubUsername)
|
||||
}
|
||||
} catch {
|
||||
setError('Followed here, but GitHub sync failed.')
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
// Revert on failure
|
||||
setIsFollowing(isFollowing)
|
||||
@ -53,7 +79,7 @@ export function FollowButton({
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [isLoading, isFollowing, userId, onFollowChange])
|
||||
}, [isLoading, isFollowing, userId, onFollowChange, canSyncGitHub, githubUsername])
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Render helpers
|
||||
|
||||
54
gitgram/web/components/MuteThreadButton.tsx
Normal file
54
gitgram/web/components/MuteThreadButton.tsx
Normal file
@ -0,0 +1,54 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback } from 'react'
|
||||
import { useModeration } from '@/hooks/useModeration'
|
||||
import { muteThread, unmuteThread } from '@/utils/moderation'
|
||||
|
||||
interface MuteThreadButtonProps {
|
||||
postId: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles a thread mute for a post. Muted threads are hidden from the feed by
|
||||
* Feed.tsx (via utils/moderation). State is shared through useModeration so the
|
||||
* label stays in sync everywhere.
|
||||
*/
|
||||
export default function MuteThreadButton({ postId, className = '' }: MuteThreadButtonProps) {
|
||||
const moderation = useModeration()
|
||||
const isMuted = moderation.mutedThreads.includes(postId)
|
||||
|
||||
const handleToggle = useCallback(() => {
|
||||
if (isMuted) {
|
||||
unmuteThread(postId)
|
||||
} else {
|
||||
muteThread(postId)
|
||||
}
|
||||
}, [isMuted, postId])
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleToggle}
|
||||
aria-pressed={isMuted}
|
||||
className={`inline-flex items-center gap-2 rounded-lg border border-[var(--border)] px-3 py-2 text-sm font-medium text-[var(--foreground-secondary)] transition-colors hover:bg-[var(--surface-secondary)] hover:text-[var(--foreground)] ${className}`}
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
|
||||
{isMuted ? (
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M15.536 8.464a5 5 0 010 7.072M12 6.5L7 10H4a1 1 0 00-1 1v2a1 1 0 001 1h3l5 3.5v-11z"
|
||||
/>
|
||||
) : (
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15zM17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"
|
||||
/>
|
||||
)}
|
||||
</svg>
|
||||
{isMuted ? 'Unmute thread' : 'Mute thread'}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { linkifyText } from '@/utils/linkify'
|
||||
|
||||
export interface Post {
|
||||
id: string
|
||||
@ -104,7 +105,7 @@ function RenderedContent({ content }: { content: string }) {
|
||||
}
|
||||
return (
|
||||
<span key={i} style={{ color: '#E2E8F0', whiteSpace: 'pre-wrap' }}>
|
||||
{seg.value}
|
||||
{linkifyText(seg.value, { linkClassName: 'text-[#A78BFA] hover:underline' })}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { parseCodeContent, ContentSegment, hasCode } from '@/utils/codeParser';
|
||||
import { linkifyText } from '@/utils/linkify';
|
||||
import CodeBlock, { InlineCode } from './CodeBlock';
|
||||
|
||||
interface RichContentProps {
|
||||
@ -15,11 +16,11 @@ interface RichContentProps {
|
||||
export default function RichContent({ content, className = '' }: RichContentProps) {
|
||||
const segments = useMemo(() => parseCodeContent(content), [content]);
|
||||
|
||||
// If no code, just render plain text for better performance
|
||||
// If no code, just render linkified plain text for better performance
|
||||
if (!hasCode(content)) {
|
||||
return (
|
||||
<div className={`whitespace-pre-wrap ${className}`}>
|
||||
{content}
|
||||
{linkifyText(content)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -48,7 +49,7 @@ function RenderSegment({ segment }: { segment: ContentSegment }) {
|
||||
return <InlineCode>{segment.code}</InlineCode>;
|
||||
|
||||
case 'text':
|
||||
return <span className="whitespace-pre-wrap">{segment.content}</span>;
|
||||
return <span className="whitespace-pre-wrap">{linkifyText(segment.content)}</span>;
|
||||
|
||||
default:
|
||||
return null;
|
||||
|
||||
@ -16,6 +16,7 @@ import RepoLinker from './RepoLinker'
|
||||
import SchedulePicker from './SchedulePicker'
|
||||
import DraftManager from './DraftManager'
|
||||
import MediaPreview from './MediaPreview'
|
||||
import SortableMediaGrid, { type SortableMediaItem } from './SortableMediaGrid'
|
||||
|
||||
export type ContentType = 'POST' | 'REEL' | 'STORY'
|
||||
|
||||
@ -240,6 +241,45 @@ export default function ContentComposer({ initialContentType }: ContentComposerP
|
||||
})
|
||||
}
|
||||
|
||||
// Remove an image by its preview id (used by the sortable grid). The blob
|
||||
// URL is the stable id, so it is also the one to revoke.
|
||||
const removeImageByPreview = useCallback(
|
||||
(previewId: string) => {
|
||||
const index = state.mediaPreviews.indexOf(previewId)
|
||||
if (index === -1) return
|
||||
removeImage(index)
|
||||
},
|
||||
// removeImage closes over the latest state through updateState; depend on
|
||||
// the previews array so the index lookup is always current.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[state.mediaPreviews, state.mediaFiles],
|
||||
)
|
||||
|
||||
// Apply a new ordering coming from the sortable grid. Files and previews are
|
||||
// parallel arrays keyed by the preview URL, so reorder both in lockstep.
|
||||
const reorderImages = useCallback(
|
||||
(ordered: SortableMediaItem[]) => {
|
||||
const previewToFile = new Map<string, File>()
|
||||
state.mediaPreviews.forEach((preview, i) => {
|
||||
previewToFile.set(preview, state.mediaFiles[i])
|
||||
})
|
||||
|
||||
const nextPreviews = ordered.map((item) => item.id)
|
||||
const nextFiles = ordered
|
||||
.map((item) => previewToFile.get(item.id))
|
||||
.filter((file): file is File => file !== undefined)
|
||||
|
||||
// Guard: only apply if every preview still maps to a file.
|
||||
if (nextFiles.length !== nextPreviews.length) return
|
||||
|
||||
updateState({ mediaFiles: nextFiles, mediaPreviews: nextPreviews })
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[state.mediaPreviews, state.mediaFiles, updateState],
|
||||
)
|
||||
|
||||
const sortableItems: SortableMediaItem[] = state.mediaPreviews.map((src) => ({ id: src, src }))
|
||||
|
||||
const removeVideo = () => {
|
||||
if (state.videoPreview) URL.revokeObjectURL(state.videoPreview)
|
||||
updateState({
|
||||
@ -662,7 +702,7 @@ export default function ContentComposer({ initialContentType }: ContentComposerP
|
||||
</div>
|
||||
|
||||
{/* Media Previews */}
|
||||
{(state.mediaPreviews.length > 0 || state.videoPreview) && (
|
||||
{state.videoPreview || state.mediaPreviews.length === 1 ? (
|
||||
<div className="mb-4">
|
||||
<MediaPreview
|
||||
images={state.mediaPreviews}
|
||||
@ -672,7 +712,18 @@ export default function ContentComposer({ initialContentType }: ContentComposerP
|
||||
onRemoveVideo={removeVideo}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
) : state.mediaPreviews.length > 1 ? (
|
||||
<div className="mb-4 space-y-2">
|
||||
<p className="text-xs text-foreground-secondary">
|
||||
Drag to reorder. The first image is shown as the cover.
|
||||
</p>
|
||||
<SortableMediaGrid
|
||||
items={sortableItems}
|
||||
onReorder={reorderImages}
|
||||
onRemove={removeImageByPreview}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Code Snippet Preview */}
|
||||
{state.codeSnippet && (
|
||||
|
||||
175
gitgram/web/components/composer/SortableMediaGrid.tsx
Normal file
175
gitgram/web/components/composer/SortableMediaGrid.tsx
Normal file
@ -0,0 +1,175 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useMemo, type ComponentType, type ReactNode } from 'react'
|
||||
import {
|
||||
DndContext as RawDndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
MeasuringStrategy,
|
||||
type DragEndEvent,
|
||||
type DndContextProps,
|
||||
} from '@dnd-kit/core'
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
rectSortingStrategy,
|
||||
useSortable,
|
||||
} from '@dnd-kit/sortable'
|
||||
import { restrictToParentElement } from '@dnd-kit/modifiers'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface SortableMediaItem {
|
||||
/** Stable unique id for the item (the object URL preview works well). */
|
||||
id: string
|
||||
/** Image preview source. */
|
||||
src: string
|
||||
}
|
||||
|
||||
interface SortableMediaGridProps {
|
||||
items: SortableMediaItem[]
|
||||
/** Called with the new ordering after a drag or keyboard reorder. */
|
||||
onReorder: (items: SortableMediaItem[]) => void
|
||||
/** Called with the id of an item to remove. */
|
||||
onRemove: (id: string) => void
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Single sortable tile
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface SortableTileProps {
|
||||
item: SortableMediaItem
|
||||
index: number
|
||||
total: number
|
||||
onRemove: (id: string) => void
|
||||
}
|
||||
|
||||
function SortableTile({ item, index, total, onRemove }: SortableTileProps) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: item.id,
|
||||
})
|
||||
|
||||
const style = useMemo(
|
||||
() => ({
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
zIndex: isDragging ? 10 : undefined,
|
||||
opacity: isDragging ? 0.85 : 1,
|
||||
}),
|
||||
[transform, transition, isDragging],
|
||||
)
|
||||
|
||||
return (
|
||||
<div ref={setNodeRef} style={style} className="relative aspect-square">
|
||||
{/* Drag handle — also the keyboard-reorder grip. */}
|
||||
<button
|
||||
type="button"
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
aria-label={`Reorder image ${index + 1} of ${total}. Press space or enter, then use arrow keys.`}
|
||||
className="absolute left-1/2 top-1/2 z-10 -translate-x-1/2 -translate-y-1/2 cursor-grab touch-none rounded-full bg-black/40 p-2 text-white opacity-0 transition-opacity focus:opacity-100 focus:outline-none focus:ring-2 focus:ring-[var(--primary)] group-hover:opacity-100 active:cursor-grabbing"
|
||||
>
|
||||
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4 8h16M4 16h16" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Remove button. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemove(item.id)}
|
||||
aria-label={`Remove image ${index + 1}`}
|
||||
className="absolute right-1.5 top-1.5 z-20 rounded-full bg-black/60 p-1.5 text-white transition-colors hover:bg-error"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Order badge. */}
|
||||
<span className="absolute left-1.5 top-1.5 z-20 rounded-full bg-black/60 px-2 py-0.5 text-xs font-medium text-white">
|
||||
{index + 1}
|
||||
</span>
|
||||
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={item.src}
|
||||
alt={`Selected image ${index + 1}`}
|
||||
className="h-full w-full rounded-lg object-cover"
|
||||
draggable={false}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Grid
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const measuringConfig = {
|
||||
droppable: { strategy: MeasuringStrategy.Always },
|
||||
}
|
||||
const modifiers = [restrictToParentElement]
|
||||
|
||||
// @dnd-kit ships types compiled against a different @types/react major than
|
||||
// this app, which makes TS reject DndContext as a JSX component. Re-type it
|
||||
// against this app's React types (behaviour is identical at runtime).
|
||||
const DndContext = RawDndContext as unknown as ComponentType<
|
||||
DndContextProps & { children?: ReactNode }
|
||||
>
|
||||
|
||||
/**
|
||||
* Keyboard-accessible drag-to-reorder grid for selected composer images.
|
||||
* Adapted from munia's CreatePostSort/CreatePostSortItem to the product's
|
||||
* stack (object-URL previews, CSS-variable theme, no custom svg_components).
|
||||
*/
|
||||
export default function SortableMediaGrid({ items, onReorder, onRemove }: SortableMediaGridProps) {
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
)
|
||||
|
||||
const handleDragEnd = useCallback(
|
||||
(event: DragEndEvent) => {
|
||||
const { active, over } = event
|
||||
if (!over || active.id === over.id) return
|
||||
|
||||
const oldIndex = items.findIndex((i) => i.id === active.id)
|
||||
const newIndex = items.findIndex((i) => i.id === over.id)
|
||||
if (oldIndex === -1 || newIndex === -1) return
|
||||
|
||||
onReorder(arrayMove(items, oldIndex, newIndex))
|
||||
},
|
||||
[items, onReorder],
|
||||
)
|
||||
|
||||
const ids = useMemo(() => items.map((i) => i.id), [items])
|
||||
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
modifiers={modifiers}
|
||||
measuring={measuringConfig}
|
||||
>
|
||||
<SortableContext items={ids} strategy={rectSortingStrategy}>
|
||||
<div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
|
||||
{items.map((item, index) => (
|
||||
<div key={item.id} className="group">
|
||||
<SortableTile item={item} index={index} total={items.length} onRemove={onRemove} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
)
|
||||
}
|
||||
@ -1,8 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Repository, repoService } from '@/services/repoService';
|
||||
import { githubService } from '@/services/githubService';
|
||||
import { useAuthStore } from '@/store/authStore';
|
||||
import { getErrorMessage } from '@/utils/error';
|
||||
import { buildRepoTextPath } from '@/utils/repositoryRouting';
|
||||
|
||||
interface RepoInteractionPanelProps {
|
||||
@ -131,11 +134,70 @@ function RecentContributors({ owner, name }: { owner: string; name: string }) {
|
||||
|
||||
export default function RepoInteractionPanel({ repository, owner, name, onFollow }: RepoInteractionPanelProps) {
|
||||
const REACTIONS = ['\u{1F44D}', '\u{2764}\u{FE0F}', '\u{1F389}', '\u{1F680}', '\u{1F440}', '\u{1F525}'];
|
||||
const { user } = useAuthStore();
|
||||
const isGitHubConnected = Boolean(user?.githubId);
|
||||
const [shareCopied, setShareCopied] = useState(false);
|
||||
const [exportLoading, setExportLoading] = useState<'copy' | 'download' | null>(null);
|
||||
const [exportMessage, setExportMessage] = useState<string | null>(null);
|
||||
const [cachedRepoText, setCachedRepoText] = useState<string | null>(null);
|
||||
|
||||
// GitHub one-click star state
|
||||
const [starred, setStarred] = useState<boolean | null>(null);
|
||||
const [starLoading, setStarLoading] = useState(false);
|
||||
const [starError, setStarError] = useState<string | null>(null);
|
||||
|
||||
// Resolve current star state once GitHub is connected.
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
if (!isGitHubConnected) {
|
||||
setStarred(null);
|
||||
return;
|
||||
}
|
||||
githubService
|
||||
.hasStarredRepo(repository.fullName)
|
||||
.then((value) => {
|
||||
if (active) setStarred(value);
|
||||
})
|
||||
.catch(() => {
|
||||
// Non-fatal: leave as unknown so the button still offers to star.
|
||||
if (active) setStarred(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [isGitHubConnected, repository.fullName]);
|
||||
|
||||
const handleStarOnGitHub = useCallback(async () => {
|
||||
// Not connected → fall back to opening the repo on GitHub (previous behavior).
|
||||
if (!isGitHubConnected) {
|
||||
window.open(repository.htmlUrl, '_blank', 'noopener,noreferrer');
|
||||
return;
|
||||
}
|
||||
|
||||
if (starLoading) return;
|
||||
setStarError(null);
|
||||
|
||||
const next = !starred;
|
||||
// Optimistic toggle.
|
||||
setStarred(next);
|
||||
setStarLoading(true);
|
||||
try {
|
||||
const result = next
|
||||
? await githubService.starRepo(repository.fullName)
|
||||
: await githubService.unstarRepo(repository.fullName);
|
||||
if (!result.success) {
|
||||
throw new Error(result.message || 'GitHub action failed');
|
||||
}
|
||||
setStarred(result.active);
|
||||
} catch (error) {
|
||||
// Revert on failure.
|
||||
setStarred(!next);
|
||||
setStarError(getErrorMessage(error));
|
||||
} finally {
|
||||
setStarLoading(false);
|
||||
}
|
||||
}, [isGitHubConnected, starred, starLoading, repository.fullName, repository.htmlUrl]);
|
||||
|
||||
const handleReaction = async (type: string) => {
|
||||
try {
|
||||
await repoService.addReaction(owner, name, type);
|
||||
@ -154,10 +216,6 @@ export default function RepoInteractionPanel({ repository, owner, name, onFollow
|
||||
}
|
||||
};
|
||||
|
||||
const handleStarOnGitHub = () => {
|
||||
window.open(repository.htmlUrl, '_blank');
|
||||
};
|
||||
|
||||
const fetchRepoText = async () => {
|
||||
if (cachedRepoText) {
|
||||
return cachedRepoText;
|
||||
@ -224,12 +282,33 @@ export default function RepoInteractionPanel({ repository, owner, name, onFollow
|
||||
<div className="flex gap-2 mb-3">
|
||||
<button
|
||||
onClick={handleStarOnGitHub}
|
||||
className="flex flex-1 items-center justify-center gap-2 rounded-lg border border-border bg-background py-2 text-sm font-medium text-foreground transition hover:bg-hover"
|
||||
disabled={starLoading}
|
||||
aria-pressed={isGitHubConnected ? starred ?? false : undefined}
|
||||
title={
|
||||
isGitHubConnected
|
||||
? starred
|
||||
? 'Unstar on GitHub'
|
||||
: 'Star on GitHub'
|
||||
: 'Open on GitHub'
|
||||
}
|
||||
className={`flex flex-1 items-center justify-center gap-2 rounded-lg border py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60 ${
|
||||
isGitHubConnected && starred
|
||||
? 'border-yellow-500/50 bg-yellow-500/10 text-yellow-500 hover:bg-yellow-500/20'
|
||||
: 'border-border bg-background text-foreground hover:bg-hover'
|
||||
}`}
|
||||
>
|
||||
<svg className="h-4 w-4 text-yellow-500" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
|
||||
</svg>
|
||||
Star
|
||||
{starLoading ? (
|
||||
<span className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
|
||||
) : (
|
||||
<svg
|
||||
className={`h-4 w-4 ${isGitHubConnected && starred ? 'text-yellow-500' : 'text-yellow-500'}`}
|
||||
fill={isGitHubConnected && starred ? 'currentColor' : 'currentColor'}
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
|
||||
</svg>
|
||||
)}
|
||||
{isGitHubConnected ? (starred ? 'Starred' : 'Star') : 'Star'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleShare}
|
||||
@ -242,6 +321,12 @@ export default function RepoInteractionPanel({ repository, owner, name, onFollow
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{starError && (
|
||||
<p className="mb-3 text-xs text-error" role="alert">
|
||||
{starError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mb-3 grid grid-cols-2 gap-2">
|
||||
<button
|
||||
onClick={handleCopyRepoText}
|
||||
|
||||
25
gitgram/web/hooks/useModeration.ts
Normal file
25
gitgram/web/hooks/useModeration.ts
Normal file
@ -0,0 +1,25 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
loadModeration,
|
||||
subscribeModeration,
|
||||
type ModerationState,
|
||||
} from '@/utils/moderation'
|
||||
|
||||
/**
|
||||
* Reactive accessor for the client-side moderation state. Re-renders whenever
|
||||
* muted words / accounts / threads change (including from other components via
|
||||
* the shared pub/sub).
|
||||
*/
|
||||
export function useModeration(): ModerationState {
|
||||
const [state, setState] = useState<ModerationState>(() => loadModeration())
|
||||
|
||||
useEffect(() => {
|
||||
// Re-sync on mount in case localStorage changed before subscription.
|
||||
setState(loadModeration())
|
||||
return subscribeModeration(setState)
|
||||
}, [])
|
||||
|
||||
return state
|
||||
}
|
||||
@ -16,13 +16,19 @@
|
||||
"test:e2e:headed": "playwright test --headed"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/modifiers": "^9.0.0",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
"@sentry/nextjs": "^10.27.0",
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
"axios": "^1.6.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cropperjs": "^1.6.2",
|
||||
"date-fns": "^4.1.0",
|
||||
"framer-motion": "^12.23.24",
|
||||
"html-to-image": "^1.11.13",
|
||||
@ -30,6 +36,7 @@
|
||||
"next": "^14.0.0",
|
||||
"prismjs": "^1.30.0",
|
||||
"react": "^18.2.0",
|
||||
"react-cropper": "^2.3.3",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hot-toast": "^2.6.0",
|
||||
"react-map-gl": "^8.1.0",
|
||||
@ -43,8 +50,8 @@
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/node": "^20.0.0",
|
||||
"@types/react": "^18.2.0",
|
||||
"@types/react-dom": "^18.2.0",
|
||||
"@types/react": "^18.3.27",
|
||||
"@types/react-dom": "^18.3.7",
|
||||
"@types/react-map-gl": "^6.1.7",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"autoprefixer": "^10.4.0",
|
||||
|
||||
@ -1,5 +1,29 @@
|
||||
import api from './api'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Write-back result envelope
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Result of a GitHub write-back action proxied through the backend. The backend
|
||||
* uses the user's stored OAuth token (scope `repo,read:user`, requested in
|
||||
* connectGitHub) to call the GitHub REST API on their behalf.
|
||||
*/
|
||||
export interface GitHubActionResult {
|
||||
success: boolean
|
||||
/** New state after the action: true if now starred / following. */
|
||||
active: boolean
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface GitHubStarStatus {
|
||||
starred: boolean
|
||||
}
|
||||
|
||||
export interface GitHubFollowStatus {
|
||||
following: boolean
|
||||
}
|
||||
|
||||
export const githubService = {
|
||||
connectGitHub: () => {
|
||||
const clientId = process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID
|
||||
@ -46,4 +70,48 @@ export const githubService = {
|
||||
const { data } = await api.post('/github/sync-project', { repoName, owner })
|
||||
return data
|
||||
},
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GitHub write-back (star / follow) — proxied through the backend, which
|
||||
// holds the user's OAuth token. Mirrors gh-social's starAction/followAction.
|
||||
// `repoName` is the `owner/repo` full name.
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
hasStarredRepo: async (repoName: string): Promise<boolean> => {
|
||||
const { data } = await api.get<GitHubStarStatus>('/github/starred', {
|
||||
params: { repo: repoName },
|
||||
})
|
||||
return Boolean(data?.starred)
|
||||
},
|
||||
|
||||
starRepo: async (repoName: string): Promise<GitHubActionResult> => {
|
||||
const { data } = await api.put<GitHubActionResult>('/github/star', { repo: repoName })
|
||||
return data
|
||||
},
|
||||
|
||||
unstarRepo: async (repoName: string): Promise<GitHubActionResult> => {
|
||||
const { data } = await api.delete<GitHubActionResult>('/github/star', {
|
||||
data: { repo: repoName },
|
||||
})
|
||||
return data
|
||||
},
|
||||
|
||||
isFollowingOnGitHub: async (username: string): Promise<boolean> => {
|
||||
const { data } = await api.get<GitHubFollowStatus>('/github/following', {
|
||||
params: { username },
|
||||
})
|
||||
return Boolean(data?.following)
|
||||
},
|
||||
|
||||
followOnGitHub: async (username: string): Promise<GitHubActionResult> => {
|
||||
const { data } = await api.put<GitHubActionResult>('/github/follow', { username })
|
||||
return data
|
||||
},
|
||||
|
||||
unfollowOnGitHub: async (username: string): Promise<GitHubActionResult> => {
|
||||
const { data } = await api.delete<GitHubActionResult>('/github/follow', {
|
||||
data: { username },
|
||||
})
|
||||
return data
|
||||
},
|
||||
}
|
||||
|
||||
@ -20,7 +20,11 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
"@/*": ["./*"],
|
||||
"react": ["./node_modules/@types/react"],
|
||||
"react/*": ["./node_modules/@types/react/*"],
|
||||
"react-dom": ["./node_modules/@types/react-dom"],
|
||||
"react-dom/*": ["./node_modules/@types/react-dom/*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
|
||||
File diff suppressed because one or more lines are too long
87
gitgram/web/utils/linkify.tsx
Normal file
87
gitgram/web/utils/linkify.tsx
Normal file
@ -0,0 +1,87 @@
|
||||
import { Fragment, type ReactNode } from 'react';
|
||||
import Link from 'next/link';
|
||||
|
||||
/**
|
||||
* Matches @mentions and #hashtags in free text.
|
||||
*
|
||||
* - A token must be preceded by start-of-string or whitespace so that emails
|
||||
* (`a@b.com`) and inline code fragments are not mistakenly linkified.
|
||||
* - The captured word allows letters, numbers, and underscores — matching the
|
||||
* product's username/hashtag rules (see settings/profile validateUsername and
|
||||
* ContentComposer.extractHashtags).
|
||||
*/
|
||||
const TOKEN_PATTERN = /(^|[\s(])([@#])([A-Za-z0-9_]{1,40})/g;
|
||||
|
||||
export interface LinkifyOptions {
|
||||
/** Tailwind/utility classes applied to each generated link. */
|
||||
linkClassName?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_LINK_CLASS = 'text-[var(--primary)] hover:underline';
|
||||
|
||||
/**
|
||||
* Builds the destination route for a token.
|
||||
* Mentions resolve to the user profile route (`/[username]`).
|
||||
* Hashtags resolve to the hashtag feed route (`/hashtag/[tag]`).
|
||||
*/
|
||||
function hrefForToken(char: string, word: string): string {
|
||||
return char === '#' ? `/hashtag/${encodeURIComponent(word)}` : `/${encodeURIComponent(word)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a plain text string into an array of React nodes where every
|
||||
* @mention / #hashtag becomes a clickable Next.js <Link>. All other text is
|
||||
* preserved verbatim (including whitespace), so it is safe to render inside a
|
||||
* `whitespace-pre-wrap` container.
|
||||
*
|
||||
* This performs no HTML parsing — it only ever emits plain strings and Link
|
||||
* elements, so there is no XSS surface (unlike dangerouslySetInnerHTML-based
|
||||
* approaches).
|
||||
*/
|
||||
export function linkifyText(text: string, options: LinkifyOptions = {}): ReactNode {
|
||||
const linkClassName = options.linkClassName ?? DEFAULT_LINK_CLASS;
|
||||
|
||||
if (!text) return text;
|
||||
|
||||
const nodes: ReactNode[] = [];
|
||||
let lastIndex = 0;
|
||||
let keyCounter = 0;
|
||||
|
||||
// Reset lastIndex defensively since the regex is global and module-scoped.
|
||||
TOKEN_PATTERN.lastIndex = 0;
|
||||
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = TOKEN_PATTERN.exec(text)) !== null) {
|
||||
const [, lead, char, word] = match;
|
||||
const tokenStart = match.index + lead.length;
|
||||
|
||||
// Emit any text (plus the leading separator) before the token.
|
||||
const precedingText = text.slice(lastIndex, tokenStart);
|
||||
if (precedingText) {
|
||||
nodes.push(<Fragment key={`t-${keyCounter++}`}>{precedingText}</Fragment>);
|
||||
}
|
||||
|
||||
nodes.push(
|
||||
<Link
|
||||
key={`l-${keyCounter++}`}
|
||||
href={hrefForToken(char, word)}
|
||||
className={linkClassName}
|
||||
// Stop the click from bubbling to parent post/card click handlers.
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{char}
|
||||
{word}
|
||||
</Link>,
|
||||
);
|
||||
|
||||
lastIndex = tokenStart + char.length + word.length;
|
||||
}
|
||||
|
||||
// Trailing text after the final token.
|
||||
const trailing = text.slice(lastIndex);
|
||||
if (trailing) {
|
||||
nodes.push(<Fragment key={`t-${keyCounter++}`}>{trailing}</Fragment>);
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
221
gitgram/web/utils/moderation.ts
Normal file
221
gitgram/web/utils/moderation.ts
Normal file
@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Client-side moderation primitives: muted words (keyword content filter),
|
||||
* muted accounts (soft hide-without-block), and muted threads.
|
||||
*
|
||||
* Adapted from Bluesky's MutedWords / thread-mutes / ModerationMutedAccounts to
|
||||
* the product's stack. State is persisted in localStorage (mirroring the
|
||||
* FeedFilters convention) so it works without a dedicated backend endpoint, and
|
||||
* is exposed through pure functions plus a lightweight pub/sub for live updates.
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = 'gitgram:moderation'
|
||||
|
||||
export type MutedWordTarget = 'content' | 'tag'
|
||||
|
||||
export interface MutedWord {
|
||||
/** Normalized (lowercased, trimmed) word or phrase. */
|
||||
value: string
|
||||
/** Whether to match anywhere in text, or only hashtags. */
|
||||
target: MutedWordTarget
|
||||
/** Optional ISO expiry; when in the past the word is ignored. */
|
||||
expiresAt?: string
|
||||
}
|
||||
|
||||
export interface ModerationState {
|
||||
mutedWords: MutedWord[]
|
||||
/** Lowercased usernames whose posts are hidden. */
|
||||
mutedAccounts: string[]
|
||||
/** Post ids whose threads are muted. */
|
||||
mutedThreads: string[]
|
||||
}
|
||||
|
||||
const EMPTY_STATE: ModerationState = {
|
||||
mutedWords: [],
|
||||
mutedAccounts: [],
|
||||
mutedThreads: [],
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persistence
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function isModerationState(value: unknown): value is ModerationState {
|
||||
if (typeof value !== 'object' || value === null) return false
|
||||
const v = value as Record<string, unknown>
|
||||
return (
|
||||
Array.isArray(v.mutedWords) && Array.isArray(v.mutedAccounts) && Array.isArray(v.mutedThreads)
|
||||
)
|
||||
}
|
||||
|
||||
export function loadModeration(): ModerationState {
|
||||
if (typeof window === 'undefined') return { ...EMPTY_STATE }
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return { ...EMPTY_STATE }
|
||||
const parsed: unknown = JSON.parse(raw)
|
||||
if (!isModerationState(parsed)) return { ...EMPTY_STATE }
|
||||
return {
|
||||
mutedWords: parsed.mutedWords,
|
||||
mutedAccounts: parsed.mutedAccounts,
|
||||
mutedThreads: parsed.mutedThreads,
|
||||
}
|
||||
} catch {
|
||||
return { ...EMPTY_STATE }
|
||||
}
|
||||
}
|
||||
|
||||
type Listener = (state: ModerationState) => void
|
||||
const listeners = new Set<Listener>()
|
||||
|
||||
function persist(state: ModerationState): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state))
|
||||
} catch {
|
||||
// Storage may be unavailable (private mode); keep in-memory listeners updated.
|
||||
}
|
||||
}
|
||||
listeners.forEach((l) => l(state))
|
||||
}
|
||||
|
||||
export function subscribeModeration(listener: Listener): () => void {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mutations (immutable — always return / persist a fresh state)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function normalizeWord(value: string): string {
|
||||
return value.trim().toLowerCase().replace(/^#/, '')
|
||||
}
|
||||
|
||||
export function addMutedWord(value: string, target: MutedWordTarget = 'content'): ModerationState {
|
||||
const normalized = normalizeWord(value)
|
||||
const current = loadModeration()
|
||||
if (!normalized || current.mutedWords.some((w) => w.value === normalized && w.target === target)) {
|
||||
return current
|
||||
}
|
||||
const next: ModerationState = {
|
||||
...current,
|
||||
mutedWords: [...current.mutedWords, { value: normalized, target }],
|
||||
}
|
||||
persist(next)
|
||||
return next
|
||||
}
|
||||
|
||||
export function removeMutedWord(value: string, target: MutedWordTarget): ModerationState {
|
||||
const current = loadModeration()
|
||||
const next: ModerationState = {
|
||||
...current,
|
||||
mutedWords: current.mutedWords.filter((w) => !(w.value === value && w.target === target)),
|
||||
}
|
||||
persist(next)
|
||||
return next
|
||||
}
|
||||
|
||||
export function muteAccount(username: string): ModerationState {
|
||||
const normalized = username.trim().toLowerCase().replace(/^@/, '')
|
||||
const current = loadModeration()
|
||||
if (!normalized || current.mutedAccounts.includes(normalized)) return current
|
||||
const next: ModerationState = {
|
||||
...current,
|
||||
mutedAccounts: [...current.mutedAccounts, normalized],
|
||||
}
|
||||
persist(next)
|
||||
return next
|
||||
}
|
||||
|
||||
export function unmuteAccount(username: string): ModerationState {
|
||||
const normalized = username.trim().toLowerCase().replace(/^@/, '')
|
||||
const current = loadModeration()
|
||||
const next: ModerationState = {
|
||||
...current,
|
||||
mutedAccounts: current.mutedAccounts.filter((a) => a !== normalized),
|
||||
}
|
||||
persist(next)
|
||||
return next
|
||||
}
|
||||
|
||||
export function muteThread(postId: string): ModerationState {
|
||||
const current = loadModeration()
|
||||
if (!postId || current.mutedThreads.includes(postId)) return current
|
||||
const next: ModerationState = {
|
||||
...current,
|
||||
mutedThreads: [...current.mutedThreads, postId],
|
||||
}
|
||||
persist(next)
|
||||
return next
|
||||
}
|
||||
|
||||
export function unmuteThread(postId: string): ModerationState {
|
||||
const current = loadModeration()
|
||||
const next: ModerationState = {
|
||||
...current,
|
||||
mutedThreads: current.mutedThreads.filter((id) => id !== postId),
|
||||
}
|
||||
persist(next)
|
||||
return next
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Filtering
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function isActiveWord(word: MutedWord, now: number): boolean {
|
||||
if (!word.expiresAt) return true
|
||||
const expiry = Date.parse(word.expiresAt)
|
||||
return Number.isNaN(expiry) || expiry > now
|
||||
}
|
||||
|
||||
function extractTags(text: string): string[] {
|
||||
const matches = text.toLowerCase().match(/#(\w+)/g)
|
||||
return matches ? matches.map((t) => t.slice(1)) : []
|
||||
}
|
||||
|
||||
export interface ModeratablePost {
|
||||
id: string
|
||||
content: string
|
||||
username: string
|
||||
tags?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a post should be hidden given the current moderation state.
|
||||
* A post is muted when:
|
||||
* - its author is in mutedAccounts, OR
|
||||
* - its id is a muted thread, OR
|
||||
* - a 'content' muted word appears in the text, OR
|
||||
* - a 'tag' muted word matches one of its hashtags.
|
||||
*/
|
||||
export function isPostMuted(post: ModeratablePost, state: ModerationState): boolean {
|
||||
const now = Date.now()
|
||||
|
||||
const username = post.username.toLowerCase()
|
||||
if (state.mutedAccounts.includes(username)) return true
|
||||
if (state.mutedThreads.includes(post.id)) return true
|
||||
|
||||
const text = post.content.toLowerCase()
|
||||
const tags = new Set<string>([...(post.tags ?? []).map((t) => t.toLowerCase()), ...extractTags(post.content)])
|
||||
|
||||
for (const word of state.mutedWords) {
|
||||
if (!isActiveWord(word, now)) continue
|
||||
if (word.target === 'tag') {
|
||||
if (tags.has(word.value)) return true
|
||||
} else if (text.includes(word.value)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export function filterMutedPosts<T extends ModeratablePost>(
|
||||
posts: T[],
|
||||
state: ModerationState,
|
||||
): T[] {
|
||||
return posts.filter((post) => !isPostMuted(post, state))
|
||||
}
|
||||
403
package-lock.json
generated
403
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user