feat: round-7 external harvest (18 features, all products green)
- gitgram-web (4): external link-preview/unfurl cards, rich inline embed players (YouTube/Twitch/Spotify/Vimeo) - gitgram-backend (1): natural-language feed filtering (preferredLangOnly) + Post.contentLanguage - gitgram-mobile (4): notification grouping/aggregation, shared timeAgo util - aitm-api (7): GitNexus graph-RAG query + context retrieval endpoints (flagship surface) - aitm-mcp (2): beads_claim atomic claim-for-work tool + brief-deps projection Note: gitgram-backend adds Post.contentLanguage — run prisma migrate at deploy. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
50d986473e
commit
bfc29616b7
@ -764,6 +764,94 @@ router.post("/tasks/:id/reopen", async (req: Request, res: Response) => {
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/stale — issues not updated recently (potentially stuck/abandoned).
|
||||
//
|
||||
// Surfaces the fleet-health signal you want for a swarm of agents opening PRs:
|
||||
// in-progress tasks with no recent activity, forgotten open tasks, and outdated
|
||||
// work. Optional filters:
|
||||
// days — staleness threshold in days (>=1, default 30, max 3650)
|
||||
// status — open | in_progress | blocked | deferred
|
||||
// limit — max issues to return (1-1000, default 50)
|
||||
const STALE_STATUSES = ["open", "in_progress", "blocked", "deferred"] as const;
|
||||
|
||||
router.get("/stale", async (req: Request, res: Response) => {
|
||||
const args: string[] = ["stale", "--json"];
|
||||
|
||||
const days = boundedInt(req.query.days, 1, 3650);
|
||||
if (days !== undefined) {
|
||||
args.push("--days", String(days));
|
||||
}
|
||||
|
||||
const status = singleQueryValue(req.query.status);
|
||||
if (status !== undefined) {
|
||||
if (!(STALE_STATUSES as readonly string[]).includes(status)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: `status must be one of: ${STALE_STATUSES.join(", ")}`,
|
||||
});
|
||||
}
|
||||
args.push("--status", status);
|
||||
}
|
||||
|
||||
const limit = boundedInt(req.query.limit, 1, 1000);
|
||||
if (limit !== undefined) {
|
||||
args.push("--limit", String(limit));
|
||||
}
|
||||
|
||||
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 query stale tasks",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/prime — AI-optimized workflow context as markdown.
|
||||
//
|
||||
// Bootstraps an agent at session start with the current Beads workflow state
|
||||
// (ready work + conventions) instead of hand-assembling context. The CLI emits
|
||||
// markdown to stdout; we return it as text. Optional modifiers:
|
||||
// mode=full — force full CLI command reference (ignore MCP detection)
|
||||
// mode=mcp — force minimal MCP-mode reminders
|
||||
// stealth=1 — stealth mode (no git operations in the close protocol)
|
||||
// memoriesOnly=1 — output only persistent memories (for compact hooks)
|
||||
router.get("/prime", async (req: Request, res: Response) => {
|
||||
const args: string[] = ["prime"];
|
||||
|
||||
const mode = singleQueryValue(req.query.mode);
|
||||
if (mode === "full") {
|
||||
args.push("--full");
|
||||
} else if (mode === "mcp") {
|
||||
args.push("--mcp");
|
||||
}
|
||||
|
||||
if (singleQueryValue(req.query.stealth) === "1" || singleQueryValue(req.query.stealth) === "true") {
|
||||
args.push("--stealth");
|
||||
}
|
||||
if (
|
||||
singleQueryValue(req.query.memoriesOnly) === "1" ||
|
||||
singleQueryValue(req.query.memoriesOnly) === "true"
|
||||
) {
|
||||
args.push("--memories-only");
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(beadsBin(), args);
|
||||
// `bd prime` emits markdown to stdout (not JSON); return it verbatim so the
|
||||
// caller can inject it directly into an agent's session context.
|
||||
res.json({ success: true, data: { format: "markdown", content: stdout } });
|
||||
} catch (err: unknown) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error:
|
||||
err instanceof Error ? err.message : "Failed to prime agent context",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /beads/tasks/:id — get a single task
|
||||
router.get("/tasks/:id", async (req: Request, res: Response) => {
|
||||
const { id } = req.params;
|
||||
|
||||
@ -197,10 +197,45 @@ router.get(
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// GET /context7/libraries/:id/docs?version=&tokens=&topic=
|
||||
// GET /context7/libraries/:id/docs?version=&tokens=&topic=&query=
|
||||
// Fetch documentation for a resolved library ID.
|
||||
//
|
||||
// The Context7 `/v2/context` endpoint reranks documentation against the text it
|
||||
// receives. A `query` / `question` param sends a full natural-language question
|
||||
// ("How do I set up JWT auth in Express?") for relevance-based retrieval; the
|
||||
// coarser `topic` (a single subject keyword) is used as a fallback. When both
|
||||
// are absent we send "overview" to fetch a broad context dump.
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Resolve the retrieval text Context7 reranks against. Prefers an explicit
|
||||
* natural-language `query`/`question`, then falls back to `topic`, then to a
|
||||
* broad default. Returns the text plus which source it came from.
|
||||
*/
|
||||
function resolveRetrievalQuery(req: Request): {
|
||||
query: string;
|
||||
topic: string | null;
|
||||
source: "query" | "topic" | "default";
|
||||
} {
|
||||
const rawQuery =
|
||||
typeof req.query.query === "string"
|
||||
? req.query.query
|
||||
: typeof req.query.question === "string"
|
||||
? req.query.question
|
||||
: "";
|
||||
const trimmedQuery = rawQuery.trim();
|
||||
|
||||
const rawTopic = typeof req.query.topic === "string" ? req.query.topic.trim() : "";
|
||||
|
||||
if (trimmedQuery.length > 0) {
|
||||
return { query: trimmedQuery, topic: rawTopic.length > 0 ? rawTopic : null, source: "query" };
|
||||
}
|
||||
if (rawTopic.length > 0) {
|
||||
return { query: rawTopic, topic: rawTopic, source: "topic" };
|
||||
}
|
||||
return { query: "overview", topic: null, source: "default" };
|
||||
}
|
||||
|
||||
router.get(
|
||||
"/libraries/:id/docs",
|
||||
asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
|
||||
@ -213,21 +248,31 @@ router.get(
|
||||
// tokens is preserved in the REST contract; the SDK does not expose a
|
||||
// per-request token cap, so it is recorded but does not change the call.
|
||||
const tokens = clampTokens(req.query.tokens, 5_000);
|
||||
const topic = typeof req.query.topic === "string" ? req.query.topic : "overview";
|
||||
const { query, topic, source } = resolveRetrievalQuery(req);
|
||||
if (query.length > 2000) {
|
||||
throw Errors.invalidParameter("query", "query must be 2000 characters or less");
|
||||
}
|
||||
const version =
|
||||
typeof req.query.version === "string" && req.query.version.trim().length > 0
|
||||
? req.query.version.trim()
|
||||
: undefined;
|
||||
|
||||
logger.info("context7: get library docs", { libraryId: id, version, topic, tokens });
|
||||
logger.info("context7: get library docs", {
|
||||
libraryId: id,
|
||||
version,
|
||||
query,
|
||||
topic,
|
||||
source,
|
||||
tokens,
|
||||
});
|
||||
|
||||
const docs: Documentation[] = await requireClient(req).getContext(topic, id, {
|
||||
const docs: Documentation[] = await requireClient(req).getContext(query, id, {
|
||||
type: "json",
|
||||
});
|
||||
|
||||
// Write-through to the unified memory layer (best-effort; never blocks).
|
||||
void ingestLibraryDoc(
|
||||
{ libraryId: id, topic, version: version ?? null, docs },
|
||||
{ libraryId: id, topic: topic ?? query, version: version ?? null, docs },
|
||||
{ userId: req.user?.userId }
|
||||
).catch((error: unknown) => {
|
||||
logger.warn("context7: memory write-through failed", {
|
||||
@ -240,6 +285,92 @@ router.get(
|
||||
success: true,
|
||||
libraryId: id,
|
||||
version: version ?? null,
|
||||
query,
|
||||
data: docs,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// POST /context7/query
|
||||
// Natural-language query-docs flow: send a full question and a resolved library
|
||||
// id (or a search term to resolve first) and get back reranked documentation
|
||||
// for that specific question. Body: { query, libraryId? , library?, version? }.
|
||||
// ============================================================================
|
||||
|
||||
const queryDocsBodySchema = z.object({
|
||||
query: z
|
||||
.string({ required_error: "query is required" })
|
||||
.min(1, "query must not be empty")
|
||||
.max(2000, "query must be 2000 characters or less"),
|
||||
libraryId: z.string().min(1).max(512).optional(),
|
||||
library: z.string().min(1).max(512).optional(),
|
||||
version: z.string().min(1).max(128).optional(),
|
||||
});
|
||||
|
||||
router.post(
|
||||
"/query",
|
||||
asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
|
||||
const parsed = queryDocsBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
const first = parsed.error.errors[0];
|
||||
throw Errors.invalidParameter(
|
||||
first?.path.join(".") || "body",
|
||||
first?.message ?? "Invalid request body"
|
||||
);
|
||||
}
|
||||
if (!parsed.data.libraryId && !parsed.data.library) {
|
||||
throw Errors.invalidParameter(
|
||||
"libraryId",
|
||||
"one of 'libraryId' or 'library' (a search term) is required"
|
||||
);
|
||||
}
|
||||
|
||||
const { query, version } = parsed.data;
|
||||
const client = requireClient(req);
|
||||
|
||||
// Resolve a library search term to a concrete id when no id was supplied,
|
||||
// using the query as the relevance signal for the resolve step.
|
||||
let libraryId = parsed.data.libraryId?.trim();
|
||||
if (!libraryId && parsed.data.library) {
|
||||
const matches: Library[] = await client.searchLibrary(query, parsed.data.library, {
|
||||
type: "json",
|
||||
});
|
||||
const top = matches[0];
|
||||
if (!top || typeof top.id !== "string" || top.id.trim().length === 0) {
|
||||
throw Errors.invalidParameter(
|
||||
"library",
|
||||
`no Context7 library matched '${parsed.data.library}'`
|
||||
);
|
||||
}
|
||||
libraryId = top.id.trim();
|
||||
}
|
||||
|
||||
if (!libraryId) {
|
||||
throw Errors.invalidParameter("libraryId", "library id could not be resolved");
|
||||
}
|
||||
|
||||
logger.info("context7: query docs", { libraryId, query });
|
||||
|
||||
const docs: Documentation[] = await client.getContext(query, libraryId, {
|
||||
type: "json",
|
||||
});
|
||||
|
||||
void ingestLibraryDoc(
|
||||
{ libraryId, topic: query, version: version ?? null, docs },
|
||||
{ userId: req.user?.userId }
|
||||
).catch((error: unknown) => {
|
||||
logger.warn("context7: memory write-through failed", {
|
||||
libraryId,
|
||||
details: String(error),
|
||||
});
|
||||
});
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
libraryId,
|
||||
version: version ?? null,
|
||||
query,
|
||||
data: docs,
|
||||
});
|
||||
})
|
||||
|
||||
@ -9,7 +9,7 @@
|
||||
|
||||
import { Router, Request, Response } from "express";
|
||||
import { z } from "zod";
|
||||
import { apiKeyAuth } from "../middleware/auth.js";
|
||||
import { apiKeyAuth, AuthenticatedRequest } from "../middleware/auth.js";
|
||||
import { asyncHandler, Errors } from "../middleware/errors.js";
|
||||
import { logger } from "../lib/monitoring.js";
|
||||
import {
|
||||
@ -24,6 +24,11 @@ import {
|
||||
traceSymbols,
|
||||
shapeCheck,
|
||||
explainTaint,
|
||||
queryGraph,
|
||||
getSymbolContext,
|
||||
runCypher,
|
||||
structuralCheck,
|
||||
renameSymbol,
|
||||
} from "../services/gitNexusService.js";
|
||||
|
||||
const router = Router();
|
||||
@ -123,6 +128,74 @@ const explainQuerySchema = z.object({
|
||||
repo: optionalRepo,
|
||||
});
|
||||
|
||||
// query — natural-language, process-grouped graph-RAG retrieval.
|
||||
// Exposed as GET (query params) and POST (body) for caller convenience.
|
||||
const queryBodySchema = z.object({
|
||||
search_query: z
|
||||
.string({ required_error: "search_query is required" })
|
||||
.min(1, "search_query must not be empty")
|
||||
.max(2000, "search_query is too long"),
|
||||
task_context: z.string().min(1).max(2000).optional(),
|
||||
goal: z.string().min(1).max(2000).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(100).optional(),
|
||||
max_symbols: z.coerce.number().int().min(1).max(200).optional(),
|
||||
include_content: z.coerce.boolean().optional(),
|
||||
repo: optionalRepo,
|
||||
service: z.string().min(1).max(2048).optional(),
|
||||
});
|
||||
const queryQuerySchema = queryBodySchema;
|
||||
|
||||
// context — 360-degree view of one symbol. At least one of name|uid required.
|
||||
const contextBodySchema = z
|
||||
.object({
|
||||
name: z.string().min(1).max(512).optional(),
|
||||
uid: z.string().min(1).max(512).optional(),
|
||||
file_path: z.string().min(1).max(2048).optional(),
|
||||
kind: z.string().min(1).max(64).optional(),
|
||||
include_content: z.coerce.boolean().optional(),
|
||||
repo: optionalRepo,
|
||||
service: z.string().min(1).max(2048).optional(),
|
||||
})
|
||||
.refine((v) => Boolean(v.name) || Boolean(v.uid), {
|
||||
message: "at least one of 'name' or 'uid' is required",
|
||||
path: ["name"],
|
||||
});
|
||||
const contextQuerySchema = contextBodySchema;
|
||||
|
||||
// cypher — raw parameterized query against the knowledge graph.
|
||||
const cypherBodySchema = z.object({
|
||||
statement: z
|
||||
.string({ required_error: "statement is required" })
|
||||
.min(1, "statement must not be empty")
|
||||
.max(20000, "statement is too long"),
|
||||
params: z.record(z.unknown()).optional(),
|
||||
repo: optionalRepo,
|
||||
});
|
||||
|
||||
// check — read-only structural CI check.
|
||||
const checkQuerySchema = z.object({
|
||||
cycles: z.coerce.boolean().optional(),
|
||||
repo: optionalRepo,
|
||||
});
|
||||
|
||||
// rename — graph-aware coordinated rename (DESTRUCTIVE; dry_run defaults true).
|
||||
const renameBodySchema = z
|
||||
.object({
|
||||
new_name: z
|
||||
.string({ required_error: "new_name is required" })
|
||||
.min(1, "new_name must not be empty")
|
||||
.max(512, "new_name is too long"),
|
||||
symbol_name: z.string().min(1).max(512).optional(),
|
||||
symbol_uid: z.string().min(1).max(512).optional(),
|
||||
file_path: z.string().min(1).max(2048).optional(),
|
||||
dry_run: z.boolean().optional(),
|
||||
repo: optionalRepo,
|
||||
})
|
||||
.refine((v) => Boolean(v.symbol_name) || Boolean(v.symbol_uid), {
|
||||
message: "at least one of 'symbol_name' or 'symbol_uid' is required",
|
||||
path: ["symbol_name"],
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// GET /gitnexus/status
|
||||
// ============================================================================
|
||||
@ -397,6 +470,244 @@ router.get(
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// query — natural-language, process-grouped graph-RAG retrieval.
|
||||
// The flagship "understand how code works" surface: returns execution flows
|
||||
// ranked by relevance (BM25 + vector, fused via RRF) rather than a flat symbol
|
||||
// list. Available as GET (query params) and POST (body).
|
||||
// ============================================================================
|
||||
|
||||
async function runQuery(
|
||||
data: z.infer<typeof queryBodySchema>,
|
||||
res: Response
|
||||
): Promise<Response> {
|
||||
logger.info("gitnexus: query", {
|
||||
searchQuery: data.search_query,
|
||||
repo: data.repo,
|
||||
});
|
||||
const result = await queryGraph({
|
||||
searchQuery: data.search_query,
|
||||
taskContext: data.task_context,
|
||||
goal: data.goal,
|
||||
limit: data.limit,
|
||||
maxSymbols: data.max_symbols,
|
||||
includeContent: data.include_content,
|
||||
repo: data.repo,
|
||||
service: data.service,
|
||||
});
|
||||
return res.json({ success: true, data: result });
|
||||
}
|
||||
|
||||
router.get(
|
||||
"/query",
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const parsed = queryQuerySchema.safeParse(req.query);
|
||||
if (!parsed.success) {
|
||||
const first = parsed.error.errors[0];
|
||||
throw Errors.invalidParameter(
|
||||
first?.path.join(".") || "query",
|
||||
first?.message ?? "Invalid query parameters"
|
||||
);
|
||||
}
|
||||
return runQuery(parsed.data, res);
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/query",
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const parsed = queryBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
const first = parsed.error.errors[0];
|
||||
throw Errors.invalidParameter(
|
||||
first?.path.join(".") || "body",
|
||||
first?.message ?? "Invalid request body"
|
||||
);
|
||||
}
|
||||
return runQuery(parsed.data, res);
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// context — 360-degree view of a single symbol (callers/callees, processes,
|
||||
// file location). Available as GET (query params) and POST (body).
|
||||
// ============================================================================
|
||||
|
||||
async function runContext(
|
||||
data: z.infer<typeof contextBodySchema>,
|
||||
res: Response
|
||||
): Promise<Response> {
|
||||
logger.info("gitnexus: context", {
|
||||
name: data.name ?? data.uid,
|
||||
repo: data.repo,
|
||||
});
|
||||
const result = await getSymbolContext({
|
||||
name: data.name,
|
||||
uid: data.uid,
|
||||
filePath: data.file_path,
|
||||
kind: data.kind,
|
||||
includeContent: data.include_content,
|
||||
repo: data.repo,
|
||||
service: data.service,
|
||||
});
|
||||
return res.json({ success: true, data: result });
|
||||
}
|
||||
|
||||
router.get(
|
||||
"/context",
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const parsed = contextQuerySchema.safeParse(req.query);
|
||||
if (!parsed.success) {
|
||||
const first = parsed.error.errors[0];
|
||||
throw Errors.invalidParameter(
|
||||
first?.path.join(".") || "query",
|
||||
first?.message ?? "Invalid query parameters"
|
||||
);
|
||||
}
|
||||
return runContext(parsed.data, res);
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/context",
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const parsed = contextBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
const first = parsed.error.errors[0];
|
||||
throw Errors.invalidParameter(
|
||||
first?.path.join(".") || "body",
|
||||
first?.message ?? "Invalid request body"
|
||||
);
|
||||
}
|
||||
return runContext(parsed.data, res);
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// cypher — arbitrary parameterized Cypher against the knowledge graph.
|
||||
// User values MUST be bound via `params` ($placeholders), never interpolated
|
||||
// into the statement, so the engine uses prepared-statement binding.
|
||||
// ============================================================================
|
||||
|
||||
router.post(
|
||||
"/cypher",
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const parsed = cypherBodySchema.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 { statement, params, repo } = parsed.data;
|
||||
logger.info("gitnexus: cypher", {
|
||||
statementLength: statement.length,
|
||||
paramKeys: params ? Object.keys(params) : [],
|
||||
repo,
|
||||
});
|
||||
const data = await runCypher({ statement, params, repo });
|
||||
|
||||
return res.json({ success: true, data });
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// check — read-only structural CI check (import cycles).
|
||||
// ============================================================================
|
||||
|
||||
router.get(
|
||||
"/check",
|
||||
asyncHandler(async (req: Request, res: Response) => {
|
||||
const parsed = checkQuerySchema.safeParse(req.query);
|
||||
if (!parsed.success) {
|
||||
const first = parsed.error.errors[0];
|
||||
throw Errors.invalidParameter(
|
||||
first?.path.join(".") || "query",
|
||||
first?.message ?? "Invalid query parameters"
|
||||
);
|
||||
}
|
||||
|
||||
const { cycles, repo } = parsed.data;
|
||||
logger.info("gitnexus: check", { cycles, repo });
|
||||
const data = await structuralCheck({ cycles, repo });
|
||||
|
||||
return res.json({ success: true, data });
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// rename — graph-aware coordinated rename (DESTRUCTIVE).
|
||||
//
|
||||
// Preview-by-default: dry_run defaults to TRUE. A non-preview rename (dry_run:
|
||||
// false) actually rewrites files, so it requires an authenticated user and is
|
||||
// recorded to the audit trail before and after execution.
|
||||
// ============================================================================
|
||||
|
||||
router.post(
|
||||
"/rename",
|
||||
asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
|
||||
const parsed = renameBodySchema.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 { new_name, symbol_name, symbol_uid, file_path, dry_run, repo } =
|
||||
parsed.data;
|
||||
const isWrite = dry_run === false;
|
||||
|
||||
// Write-path guard: a destructive (non-dry-run) rename requires an
|
||||
// authenticated user identity for the audit trail.
|
||||
if (isWrite && !req.user?.userId) {
|
||||
throw Errors.invalidParameter(
|
||||
"dry_run",
|
||||
"a non-preview rename (dry_run: false) requires an authenticated user"
|
||||
);
|
||||
}
|
||||
|
||||
if (isWrite) {
|
||||
logger.warn("gitnexus: rename write requested", {
|
||||
userId: req.user?.userId,
|
||||
symbol: symbol_name ?? symbol_uid,
|
||||
newName: new_name,
|
||||
repo,
|
||||
});
|
||||
} else {
|
||||
logger.info("gitnexus: rename preview", {
|
||||
symbol: symbol_name ?? symbol_uid,
|
||||
newName: new_name,
|
||||
repo,
|
||||
});
|
||||
}
|
||||
|
||||
const data = await renameSymbol({
|
||||
newName: new_name,
|
||||
symbolName: symbol_name,
|
||||
symbolUid: symbol_uid,
|
||||
filePath: file_path,
|
||||
dryRun: dry_run,
|
||||
repo,
|
||||
});
|
||||
|
||||
if (isWrite) {
|
||||
logger.warn("gitnexus: rename write completed", {
|
||||
userId: req.user?.userId,
|
||||
symbol: symbol_name ?? symbol_uid,
|
||||
newName: new_name,
|
||||
fileCount: data.fileCount,
|
||||
repo,
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({ success: true, data });
|
||||
})
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// Error handler — surface upstream GitNexus failures as 502
|
||||
// ============================================================================
|
||||
|
||||
@ -981,6 +981,364 @@ export async function explainTaint(params: {
|
||||
return { findings, totalFindings, truncated, noTaintLayer, raw: result };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Graph-RAG natural-language query (query tool)
|
||||
// ============================================================================
|
||||
|
||||
/** Options for {@link queryGraph}. */
|
||||
export interface QueryGraphOptions {
|
||||
/** Natural-language or keyword search query (required). */
|
||||
searchQuery: string;
|
||||
/** What the caller is working on — improves ranking. */
|
||||
taskContext?: string;
|
||||
/** What the caller wants to find — improves ranking. */
|
||||
goal?: string;
|
||||
/** Max processes (execution flows) to return. */
|
||||
limit?: number;
|
||||
/** Max symbols per process. */
|
||||
maxSymbols?: number;
|
||||
/** Include full symbol source code in results. */
|
||||
includeContent?: boolean;
|
||||
/** Repository name/path, or "@group" mode. Omit when one repo is indexed. */
|
||||
repo?: string;
|
||||
/** Optional monorepo service-root path prefix (group mode). */
|
||||
service?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Natural-language, process-grouped retrieval over the code knowledge graph via
|
||||
* the GitNexus `query` tool. Returns execution flows (processes) ranked by
|
||||
* relevance (BM25 keyword + semantic vector, fused via RRF), each with its
|
||||
* participating symbols and file locations, plus standalone definitions.
|
||||
*
|
||||
* The backend payload shape is rich and intentionally preserved verbatim under
|
||||
* {@link GraphQueryResult.raw} for callers that need full detail; a small set of
|
||||
* top-level arrays are surfaced when present.
|
||||
*/
|
||||
export interface GraphQueryResult {
|
||||
processes: unknown[];
|
||||
processSymbols: unknown[];
|
||||
definitions: unknown[];
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
export async function queryGraph(
|
||||
options: QueryGraphOptions
|
||||
): Promise<GraphQueryResult> {
|
||||
const params: Record<string, unknown> = {
|
||||
search_query: options.searchQuery,
|
||||
};
|
||||
if (options.taskContext) params["task_context"] = options.taskContext;
|
||||
if (options.goal) params["goal"] = options.goal;
|
||||
if (typeof options.limit === "number") params["limit"] = options.limit;
|
||||
if (typeof options.maxSymbols === "number") {
|
||||
params["max_symbols"] = options.maxSymbols;
|
||||
}
|
||||
if (typeof options.includeContent === "boolean") {
|
||||
params["include_content"] = options.includeContent;
|
||||
}
|
||||
if (options.repo) params["repo"] = options.repo;
|
||||
if (options.service) params["service"] = options.service;
|
||||
|
||||
const result = await callGitNexus("query", params);
|
||||
|
||||
if (!isRecord(result)) {
|
||||
return { processes: [], processSymbols: [], definitions: [], raw: result };
|
||||
}
|
||||
|
||||
const asArray = (value: unknown): unknown[] =>
|
||||
Array.isArray(value) ? value : [];
|
||||
|
||||
return {
|
||||
processes: asArray(result["processes"]),
|
||||
processSymbols: asArray(
|
||||
result["process_symbols"] ?? result["processSymbols"]
|
||||
),
|
||||
definitions: asArray(result["definitions"]),
|
||||
raw: result,
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 360-degree symbol context (context tool)
|
||||
// ============================================================================
|
||||
|
||||
/** Options for {@link getSymbolContext}. At least one of name/uid is required. */
|
||||
export interface SymbolContextOptions {
|
||||
/** Symbol name (e.g. "validateUser"). */
|
||||
name?: string;
|
||||
/** Zero-ambiguity symbol UID from a prior tool result. */
|
||||
uid?: string;
|
||||
/** File path to disambiguate common names. */
|
||||
filePath?: string;
|
||||
/** Kind filter (Function | Class | Method | Interface | …). */
|
||||
kind?: string;
|
||||
/** Include full symbol source code. */
|
||||
includeContent?: boolean;
|
||||
/** Repository name/path, or "@group" mode. */
|
||||
repo?: string;
|
||||
/** Optional monorepo service-root path prefix (group mode). */
|
||||
service?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 360-degree view of a single symbol via the GitNexus `context` tool:
|
||||
* categorized incoming/outgoing references, process participation, and file
|
||||
* location. When several symbols share a name and no uid is given, the backend
|
||||
* returns ranked disambiguation candidates — that payload is preserved under
|
||||
* {@link SymbolContextResult.raw}.
|
||||
*/
|
||||
export interface SymbolContextResult {
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
export async function getSymbolContext(
|
||||
options: SymbolContextOptions
|
||||
): Promise<SymbolContextResult> {
|
||||
const params: Record<string, unknown> = {};
|
||||
if (options.name) params["name"] = options.name;
|
||||
if (options.uid) params["uid"] = options.uid;
|
||||
if (options.filePath) params["file_path"] = options.filePath;
|
||||
if (options.kind) params["kind"] = options.kind;
|
||||
if (typeof options.includeContent === "boolean") {
|
||||
params["include_content"] = options.includeContent;
|
||||
}
|
||||
if (options.repo) params["repo"] = options.repo;
|
||||
if (options.service) params["service"] = options.service;
|
||||
|
||||
const result = await callGitNexus("context", params);
|
||||
return { raw: result };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Raw Cypher query (cypher tool)
|
||||
// ============================================================================
|
||||
|
||||
/** Options for {@link runCypher}. */
|
||||
export interface CypherOptions {
|
||||
/** Cypher statement to execute. */
|
||||
statement: string;
|
||||
/** Bound parameters for $placeholders (prepared-statement binding). */
|
||||
params?: Record<string, unknown>;
|
||||
/** Repository name/path. Omit when one repo is indexed. */
|
||||
repo?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of a {@link runCypher} call. The `cypher` tool returns a Markdown table
|
||||
* plus a row count; both are surfaced and the full payload kept under `raw`.
|
||||
*/
|
||||
export interface CypherResult {
|
||||
markdown: string | null;
|
||||
rowCount: number | null;
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes an arbitrary Cypher statement against the code knowledge graph via
|
||||
* the GitNexus `cypher` tool. Bound `params` are passed through to the engine's
|
||||
* prepared-statement binding ($placeholders) — callers should always bind user
|
||||
* values as params rather than interpolating them into the statement.
|
||||
*/
|
||||
export async function runCypher(options: CypherOptions): Promise<CypherResult> {
|
||||
const params: Record<string, unknown> = { statement: options.statement };
|
||||
if (options.params && Object.keys(options.params).length > 0) {
|
||||
params["params"] = options.params;
|
||||
}
|
||||
if (options.repo) params["repo"] = options.repo;
|
||||
|
||||
const result = await callGitNexus("cypher", params);
|
||||
|
||||
if (typeof result === "string") {
|
||||
return { markdown: result, rowCount: null, raw: result };
|
||||
}
|
||||
if (isRecord(result)) {
|
||||
return {
|
||||
markdown:
|
||||
typeof result["markdown"] === "string" ? result["markdown"] : null,
|
||||
rowCount:
|
||||
typeof result["row_count"] === "number"
|
||||
? result["row_count"]
|
||||
: typeof result["rowCount"] === "number"
|
||||
? result["rowCount"]
|
||||
: null,
|
||||
raw: result,
|
||||
};
|
||||
}
|
||||
return { markdown: null, rowCount: null, raw: result };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Structural checks for CI (check tool)
|
||||
// ============================================================================
|
||||
|
||||
/** Options for {@link structuralCheck}. */
|
||||
export interface StructuralCheckOptions {
|
||||
/** Detect circular file imports (default true). */
|
||||
cycles?: boolean;
|
||||
/** Repository name/path. Omit when one repo is indexed. */
|
||||
repo?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only structural check via the GitNexus `check` tool. Currently detects
|
||||
* directed cycles between File nodes connected by IMPORTS edges, returning
|
||||
* deterministic cycle paths and a count suitable for CI gating.
|
||||
*/
|
||||
export interface StructuralCheckResult {
|
||||
/** Detected cycle paths (each an ordered list of file identifiers). */
|
||||
cycles: unknown[];
|
||||
/** Number of distinct cycles detected. */
|
||||
cycleCount: number;
|
||||
/** True when no cycles were found. */
|
||||
ok: boolean;
|
||||
/** The unnormalised backend payload. */
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
export async function structuralCheck(
|
||||
options: StructuralCheckOptions = {}
|
||||
): Promise<StructuralCheckResult> {
|
||||
const params: Record<string, unknown> = {
|
||||
cycles: options.cycles ?? true,
|
||||
};
|
||||
if (options.repo) params["repo"] = options.repo;
|
||||
|
||||
const result = await callGitNexus("check", params);
|
||||
|
||||
const empty: StructuralCheckResult = {
|
||||
cycles: [],
|
||||
cycleCount: 0,
|
||||
ok: true,
|
||||
raw: result,
|
||||
};
|
||||
|
||||
if (!isRecord(result)) {
|
||||
if (typeof result === "string") {
|
||||
// Some backends return a textual "no cycles" note; treat as clean.
|
||||
return { ...empty, raw: result };
|
||||
}
|
||||
logger.error("gitNexus: unexpected shape from check", undefined, {
|
||||
result: String(result),
|
||||
});
|
||||
return empty;
|
||||
}
|
||||
|
||||
const cycles = Array.isArray(result["cycles"])
|
||||
? (result["cycles"] as unknown[])
|
||||
: [];
|
||||
const cycleCount =
|
||||
typeof result["cycleCount"] === "number"
|
||||
? result["cycleCount"]
|
||||
: typeof result["cycle_count"] === "number"
|
||||
? result["cycle_count"]
|
||||
: cycles.length;
|
||||
const ok =
|
||||
typeof result["ok"] === "boolean" ? result["ok"] : cycleCount === 0;
|
||||
|
||||
return { cycles, cycleCount, ok, raw: result };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Graph-aware coordinated rename (rename tool — DESTRUCTIVE)
|
||||
// ============================================================================
|
||||
|
||||
/** Options for {@link renameSymbol}. */
|
||||
export interface RenameOptions {
|
||||
/** New name for the symbol (required). */
|
||||
newName: string;
|
||||
/** Current symbol name to rename. */
|
||||
symbolName?: string;
|
||||
/** Zero-ambiguity symbol UID from a prior tool result. */
|
||||
symbolUid?: string;
|
||||
/** File path to disambiguate common names. */
|
||||
filePath?: string;
|
||||
/**
|
||||
* Preview edits without modifying files. Defaults to TRUE at the call site —
|
||||
* the route layer enforces an explicit opt-in before a write is performed.
|
||||
*/
|
||||
dryRun?: boolean;
|
||||
/** Repository name/path. Omit when one repo is indexed. */
|
||||
repo?: string;
|
||||
}
|
||||
|
||||
/** A single planned/applied edit in a {@link RenameResult}. */
|
||||
export interface RenameEdit {
|
||||
file: string;
|
||||
/** "graph" (high confidence) or "text_search" (review carefully). */
|
||||
confidence: string;
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of a graph-aware coordinated rename via the GitNexus `rename` tool.
|
||||
* Each edit is tagged with the source that found it ("graph" vs "text_search").
|
||||
* The full backend payload (including any per-file diff detail) is preserved
|
||||
* under `raw`.
|
||||
*/
|
||||
export interface RenameResult {
|
||||
/** Whether this was a preview (no files written) or an applied rename. */
|
||||
dryRun: boolean;
|
||||
/** Planned/applied edits across files. */
|
||||
edits: RenameEdit[];
|
||||
/** Number of distinct files touched. */
|
||||
fileCount: number;
|
||||
/** The unnormalised backend payload. */
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
export async function renameSymbol(
|
||||
options: RenameOptions
|
||||
): Promise<RenameResult> {
|
||||
const dryRun = options.dryRun ?? true;
|
||||
const params: Record<string, unknown> = {
|
||||
new_name: options.newName,
|
||||
dry_run: dryRun,
|
||||
};
|
||||
if (options.symbolName) params["symbol_name"] = options.symbolName;
|
||||
if (options.symbolUid) params["symbol_uid"] = options.symbolUid;
|
||||
if (options.filePath) params["file_path"] = options.filePath;
|
||||
if (options.repo) params["repo"] = options.repo;
|
||||
|
||||
const result = await callGitNexus("rename", params);
|
||||
|
||||
const rows = Array.isArray(result)
|
||||
? result
|
||||
: isRecord(result) && Array.isArray(result["edits"])
|
||||
? (result["edits"] as unknown[])
|
||||
: [];
|
||||
|
||||
const edits: RenameEdit[] = rows.filter(isRecord).map((edit) => ({
|
||||
file:
|
||||
typeof edit["file"] === "string"
|
||||
? edit["file"]
|
||||
: typeof edit["path"] === "string"
|
||||
? edit["path"]
|
||||
: typeof edit["filePath"] === "string"
|
||||
? edit["filePath"]
|
||||
: "",
|
||||
confidence:
|
||||
typeof edit["confidence"] === "string"
|
||||
? edit["confidence"]
|
||||
: typeof edit["source"] === "string"
|
||||
? edit["source"]
|
||||
: "",
|
||||
raw: edit,
|
||||
}));
|
||||
|
||||
const fileCount = new Set(edits.map((e) => e.file).filter((f) => f.length > 0))
|
||||
.size;
|
||||
|
||||
const resolvedDryRun =
|
||||
isRecord(result) && typeof result["dry_run"] === "boolean"
|
||||
? (result["dry_run"] as boolean)
|
||||
: isRecord(result) && typeof result["dryRun"] === "boolean"
|
||||
? (result["dryRun"] as boolean)
|
||||
: dryRun;
|
||||
|
||||
return { dryRun: resolvedDryRun, edits, fileCount, raw: result };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Availability probe
|
||||
// ============================================================================
|
||||
|
||||
@ -12,6 +12,8 @@ import {
|
||||
projectBeadsPayload,
|
||||
unwrapBeadsData,
|
||||
toBrief,
|
||||
toBriefDep,
|
||||
collapseDepEdges,
|
||||
truncateDescription,
|
||||
filterFields,
|
||||
type CompactedBeadsResult,
|
||||
@ -71,6 +73,58 @@ describe('beads-projection helpers', () => {
|
||||
status: 'open',
|
||||
});
|
||||
});
|
||||
|
||||
it('toBriefDep collapses an edge to id/title/status/priority/dependencyType', () => {
|
||||
expect(
|
||||
toBriefDep({
|
||||
id: 'bd-2',
|
||||
title: 'Task bd-2',
|
||||
status: 'open',
|
||||
priority: 0,
|
||||
description: 'x'.repeat(50),
|
||||
dependency_type: 'blocks',
|
||||
})
|
||||
).toEqual({
|
||||
id: 'bd-2',
|
||||
title: 'Task bd-2',
|
||||
status: 'open',
|
||||
priority: 0,
|
||||
dependencyType: 'blocks',
|
||||
});
|
||||
});
|
||||
|
||||
it('toBriefDep reads either dependencyType or dependency_type', () => {
|
||||
expect(toBriefDep({ id: 'bd-3', dependencyType: 'related' }).dependencyType).toBe(
|
||||
'related'
|
||||
);
|
||||
expect(toBriefDep({ id: 'bd-4', dependency_type: 'parent-child' }).dependencyType).toBe(
|
||||
'parent-child'
|
||||
);
|
||||
});
|
||||
|
||||
it('collapseDepEdges compacts edges while keeping the task body, immutably', () => {
|
||||
const original = task('bd-1', {
|
||||
dependencies: [task('bd-2', { dependency_type: 'blocks' })],
|
||||
dependents: [task('bd-3', { dependency_type: 'discovered-from' })],
|
||||
});
|
||||
const collapsed = collapseDepEdges(original);
|
||||
expect(collapsed.title).toBe('Task bd-1');
|
||||
expect(collapsed.dependencies).toEqual([
|
||||
{ id: 'bd-2', title: 'Task bd-2', status: 'open', priority: 1, dependencyType: 'blocks' },
|
||||
]);
|
||||
expect(collapsed.dependents).toEqual([
|
||||
{ id: 'bd-3', title: 'Task bd-3', status: 'open', priority: 1, dependencyType: 'discovered-from' },
|
||||
]);
|
||||
// input untouched: still the full nested task
|
||||
expect((original.dependencies as Array<Record<string, unknown>>)[0].description).toBe(
|
||||
'x'.repeat(50)
|
||||
);
|
||||
});
|
||||
|
||||
it('collapseDepEdges leaves tasks without edge arrays untouched', () => {
|
||||
const plain = task('bd-1');
|
||||
expect(collapseDepEdges(plain)).toBe(plain);
|
||||
});
|
||||
});
|
||||
|
||||
describe('projectBeadsPayload', () => {
|
||||
@ -118,6 +172,42 @@ describe('projectBeadsPayload', () => {
|
||||
expect(result.hint).toContain('ready tasks');
|
||||
});
|
||||
|
||||
it('briefDeps keeps the full task but collapses its dependency edges', () => {
|
||||
const payload = ENVELOPE(
|
||||
task('bd-1', {
|
||||
dependencies: [task('bd-2', { dependency_type: 'blocks' })],
|
||||
dependents: [task('bd-3', { dependency_type: 'related' })],
|
||||
})
|
||||
);
|
||||
const result = projectBeadsPayload(payload, { briefDeps: true }) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
// full task body retained
|
||||
expect(result.title).toBe('Task bd-1');
|
||||
expect(result.description).toBe('x'.repeat(50));
|
||||
// edges collapsed to the brief dep shape
|
||||
expect(result.dependencies).toEqual([
|
||||
{ id: 'bd-2', title: 'Task bd-2', status: 'open', priority: 1, dependencyType: 'blocks' },
|
||||
]);
|
||||
expect(result.dependents).toEqual([
|
||||
{ id: 'bd-3', title: 'Task bd-3', status: 'open', priority: 1, dependencyType: 'related' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('brief takes precedence over briefDeps (edges dropped entirely)', () => {
|
||||
const result = projectBeadsPayload(
|
||||
ENVELOPE(task('bd-1', { dependencies: [task('bd-2')] })),
|
||||
{ brief: true, briefDeps: true }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
id: 'bd-1',
|
||||
title: 'Task bd-1',
|
||||
status: 'open',
|
||||
priority: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('passes stats-style payloads (non-list, non-record) through', () => {
|
||||
expect(projectBeadsPayload(ENVELOPE(42), { brief: true })).toBe(42);
|
||||
});
|
||||
@ -162,6 +252,37 @@ describe('beads tools wiring (projection args)', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('beads_claim issues a PUT to /beads/tasks/:id/claim', async () => {
|
||||
const claimed = task('bd-7', { assignee: 'aitm', status: 'in_progress' });
|
||||
fetchMock.mockResolvedValueOnce(jsonOk(ENVELOPE(claimed)));
|
||||
const { call } = captureTools(registerBeadsTools, stubRuntime);
|
||||
const result = parseJsonResponse<{ success: boolean; data: unknown }>(
|
||||
await call('beads_claim', { id: 'bd-7' })
|
||||
);
|
||||
// round-trips the claimed task envelope back to the caller
|
||||
expect(result).toEqual(ENVELOPE(claimed));
|
||||
// verify the request shape: PUT to the claim endpoint
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toContain('/beads/tasks/bd-7/claim');
|
||||
expect(init.method).toBe('PUT');
|
||||
});
|
||||
|
||||
it('beads_claim with brief trims the claimed task', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
jsonOk(ENVELOPE(task('bd-8', { assignee: 'aitm', status: 'in_progress' })))
|
||||
);
|
||||
const { call } = captureTools(registerBeadsTools, stubRuntime);
|
||||
const result = parseJsonResponse<unknown>(
|
||||
await call('beads_claim', { id: 'bd-8', brief: true })
|
||||
);
|
||||
expect(result).toEqual({
|
||||
id: 'bd-8',
|
||||
title: 'Task bd-8',
|
||||
status: 'in_progress',
|
||||
priority: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('beads_list_tasks without args preserves the full envelope', async () => {
|
||||
const payload = ENVELOPE([task('bd-1')]);
|
||||
fetchMock.mockResolvedValueOnce(jsonOk(payload));
|
||||
|
||||
@ -365,6 +365,7 @@ describe('Beads tools registration', () => {
|
||||
'beads_list_tasks',
|
||||
'beads_create_task',
|
||||
'beads_mark_ready',
|
||||
'beads_claim',
|
||||
'beads_mark_done',
|
||||
'beads_get_task',
|
||||
] as const;
|
||||
@ -388,6 +389,10 @@ describe('Beads tools registration', () => {
|
||||
expect(requiredFields(server, 'beads_mark_ready')).toContain('id');
|
||||
});
|
||||
|
||||
it('beads_claim requires "id"', () => {
|
||||
expect(requiredFields(server, 'beads_claim')).toContain('id');
|
||||
});
|
||||
|
||||
it('beads_mark_done requires "id"', () => {
|
||||
expect(requiredFields(server, 'beads_mark_done')).toContain('id');
|
||||
});
|
||||
|
||||
@ -37,6 +37,10 @@ const projectionSchema = {
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe('When true, return only {id, title, status, priority} per task (smallest output).'),
|
||||
briefDeps: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe('When true, return the FULL task but collapse each dependency/dependent edge to {id, title, status, priority, dependencyType}. Ideal for inspecting a DAG node with many edges without a context blow-out. Ignored when brief is set.'),
|
||||
fields: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
@ -70,6 +74,7 @@ const listProjectionSchema = {
|
||||
function pickProjection(
|
||||
args: Partial<{
|
||||
brief: boolean;
|
||||
briefDeps: boolean;
|
||||
fields: string[];
|
||||
maxDescriptionLength: number;
|
||||
compactionThreshold: number;
|
||||
@ -79,6 +84,7 @@ function pickProjection(
|
||||
): BeadsProjectionOptions {
|
||||
return {
|
||||
brief: args.brief,
|
||||
briefDeps: args.briefDeps,
|
||||
fields: args.fields,
|
||||
maxDescriptionLength: args.maxDescriptionLength,
|
||||
compactionThreshold: args.compactionThreshold,
|
||||
@ -203,6 +209,23 @@ export const registerBeadsTools = createToolRegistrar([
|
||||
),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_claim',
|
||||
description:
|
||||
'Atomically claim a Beads task for work: set the assignee to the configured actor AND move it to in_progress in one compare-and-swap step. This is the multi-agent-safe "grab the next piece of work" primitive — two agents racing on the same task cannot both win. The claim is idempotent when the task is already claimed by the same actor; when another actor already holds it the AITM API returns 409 (surfaced here as an error) so the agent should retry a different ready task. Pair with beads_ready to find candidates, then beads_claim to lock one in.',
|
||||
schema: {
|
||||
id: z.string().describe('The ID of the task to claim for work'),
|
||||
...projectionSchema,
|
||||
},
|
||||
annotations: idempotentMutationAnnotations(),
|
||||
run: async (args) =>
|
||||
beadsPut(
|
||||
`/tasks/${encodeURIComponent(args.id)}/claim`,
|
||||
undefined,
|
||||
pickProjection(args)
|
||||
),
|
||||
}),
|
||||
|
||||
defineTool({
|
||||
name: 'beads_mark_done',
|
||||
description: 'Mark a Beads task as done (completed). This will unblock any downstream tasks that depend on this task.',
|
||||
|
||||
@ -384,6 +384,13 @@ model Post {
|
||||
selfLabels String[] @default([]) // e.g. ["sexual", "graphic-media", "spoiler"]
|
||||
contentWarning String? // optional free-text warning shown alongside the label
|
||||
|
||||
// Detected spoken/natural language of the post body, as an ISO 639-1/639-2
|
||||
// code (e.g. "en", "es", "pt"). Distinct from programming-language fields on
|
||||
// Repository/Project. Used by the feed pipeline's preferredLangOnly tuner step
|
||||
// to filter content to a viewer's natural-language preferences. Null when the
|
||||
// language could not be detected; such posts are never filtered out.
|
||||
contentLanguage String?
|
||||
|
||||
// Optional geotagging for map / nearby discovery
|
||||
location String?
|
||||
latitude Float?
|
||||
@ -415,6 +422,7 @@ model Post {
|
||||
@@index([aitmProjectId])
|
||||
@@index([createdAt])
|
||||
@@index([isArchived])
|
||||
@@index([contentLanguage])
|
||||
}
|
||||
|
||||
model Comment {
|
||||
|
||||
77
gitgram/backend/src/controllers/feedFeedbackController.ts
Normal file
77
gitgram/backend/src/controllers/feedFeedbackController.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import { Response } from 'express';
|
||||
import { AuthRequest } from '../middleware/auth';
|
||||
import { asyncHandler, Errors } from '../middleware/errorHandler';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
/**
|
||||
* Feed-feedback signals, ported from Bluesky's feed-feedback interactions.
|
||||
* These are best-effort personalisation hints used to improve discover-feed
|
||||
* ranking over time.
|
||||
*/
|
||||
const VALID_SIGNALS = ['requestLess', 'requestMore', 'seen'] as const;
|
||||
type FeedSignal = (typeof VALID_SIGNALS)[number];
|
||||
|
||||
interface FeedSignalEvent {
|
||||
postId: string;
|
||||
signal: FeedSignal;
|
||||
feedContext?: string;
|
||||
}
|
||||
|
||||
const MAX_EVENTS = 50;
|
||||
|
||||
function isValidEvent(value: unknown): value is FeedSignalEvent {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const e = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof e.postId === 'string' &&
|
||||
e.postId.length > 0 &&
|
||||
e.postId.length <= 50 &&
|
||||
typeof e.signal === 'string' &&
|
||||
(VALID_SIGNALS as readonly string[]).includes(e.signal) &&
|
||||
(e.feedContext === undefined || typeof e.feedContext === 'string')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a batch of feed-feedback signals for the authenticated user.
|
||||
* POST /api/v1/posts/feedback { events: FeedSignalEvent[] }
|
||||
*/
|
||||
export const recordFeedFeedback = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const userId = req.user?.id;
|
||||
if (!userId) {
|
||||
throw Errors.unauthorized('Authentication required');
|
||||
}
|
||||
|
||||
const { events } = req.body as { events?: unknown };
|
||||
|
||||
if (!Array.isArray(events)) {
|
||||
throw Errors.badRequest('events must be an array');
|
||||
}
|
||||
|
||||
if (events.length === 0) {
|
||||
res.json({ success: true, recorded: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
if (events.length > MAX_EVENTS) {
|
||||
throw Errors.badRequest(`Maximum ${MAX_EVENTS} events per request`);
|
||||
}
|
||||
|
||||
const valid = events.filter(isValidEvent);
|
||||
|
||||
// Best-effort: surface these as structured ranking signals. Downstream
|
||||
// personalisation / analytics can consume the log stream without requiring a
|
||||
// schema migration in this change.
|
||||
for (const event of valid) {
|
||||
logger.info('feed-feedback signal', {
|
||||
userId,
|
||||
postId: event.postId,
|
||||
signal: event.signal,
|
||||
feedContext: event.feedContext,
|
||||
});
|
||||
}
|
||||
|
||||
res.json({ success: true, recorded: valid.length });
|
||||
});
|
||||
|
||||
export default { recordFeedFeedback };
|
||||
@ -15,6 +15,10 @@ import { getCachedComments, setCachedComments, invalidateCommentCache } from '..
|
||||
import { tuneFeed, type TunableFeedItem } from '../services/feedTuner';
|
||||
import { normalizeSelfLabels, decideSelfLabel } from '../services/selfLabels';
|
||||
import { computeMutedFeedFlags } from '../services/mutedWordsService';
|
||||
import {
|
||||
computePreferredLanguageFlags,
|
||||
getPreferredLanguagesForUser,
|
||||
} from '../services/languagePreferenceService';
|
||||
|
||||
export const createPost = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const {
|
||||
@ -250,6 +254,7 @@ function toTunableItem(post: Record<string, unknown>): TunableFeedItem {
|
||||
commentsCount: post.commentsCount as number | undefined,
|
||||
sharesCount: post.sharesCount as number | undefined,
|
||||
createdAt: post.createdAt as Date | string | undefined,
|
||||
contentLanguage: (post.contentLanguage as string | null | undefined) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@ -298,6 +303,49 @@ async function applyMutedWords(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark each feed item with `isPreferredLanguage` so `tuneFeed`'s
|
||||
* `preferredLangOnly` step can keep only posts in the viewer's preferred
|
||||
* natural languages (Bluesky `FeedTuner.preferredLangOnly` parity). The tuner's
|
||||
* never-empty-page fallback ensures the feed never goes blank.
|
||||
*
|
||||
* Returns the (possibly unchanged) items plus a `preferredLangOnly` flag telling
|
||||
* the caller whether the viewer has any natural-language preference at all; when
|
||||
* false the tuner step is left disabled (a no-op for the largely-English
|
||||
* audience) and no per-item flags are computed.
|
||||
*/
|
||||
async function applyPreferredLanguage(
|
||||
items: TunableFeedItem[],
|
||||
viewerId: string
|
||||
): Promise<{ items: TunableFeedItem[]; preferredLangOnly: boolean }> {
|
||||
if (items.length === 0) {
|
||||
return { items, preferredLangOnly: false };
|
||||
}
|
||||
|
||||
const preferred = await getPreferredLanguagesForUser(viewerId);
|
||||
if (preferred.size === 0) {
|
||||
// Viewer expressed no natural-language preference: skip filtering entirely.
|
||||
return { items, preferredLangOnly: false };
|
||||
}
|
||||
|
||||
const flags = await computePreferredLanguageFlags(
|
||||
viewerId,
|
||||
items.map(item => ({
|
||||
id: item.id,
|
||||
contentLanguage:
|
||||
typeof item.contentLanguage === 'string' ? item.contentLanguage : null,
|
||||
}))
|
||||
);
|
||||
|
||||
const marked = items.map(item =>
|
||||
flags.get(item.id) === false
|
||||
? { ...item, isPreferredLanguage: false }
|
||||
: { ...item, isPreferredLanguage: true }
|
||||
);
|
||||
|
||||
return { items: marked, preferredLangOnly: true };
|
||||
}
|
||||
|
||||
export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
const userId = req.userId!;
|
||||
const { page = 1, limit = 20, cursor } = req.query;
|
||||
@ -316,11 +364,16 @@ export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
cursor.trim(),
|
||||
Number(limit)
|
||||
);
|
||||
const markedCursorItems = await applyMutedWords(
|
||||
const mutedCursorItems = await applyMutedWords(
|
||||
(result.posts as Record<string, unknown>[]).map(toTunableItem),
|
||||
userId
|
||||
);
|
||||
const tunedPosts = applySelfLabelBehavior(tuneFeed(markedCursorItems), labelOpts);
|
||||
const { items: markedCursorItems, preferredLangOnly: cursorLangOnly } =
|
||||
await applyPreferredLanguage(mutedCursorItems, userId);
|
||||
const tunedPosts = applySelfLabelBehavior(
|
||||
tuneFeed(markedCursorItems, { preferredLangOnly: cursorLangOnly }),
|
||||
labelOpts
|
||||
);
|
||||
res.json({ ...result, posts: tunedPosts });
|
||||
return;
|
||||
}
|
||||
@ -338,11 +391,16 @@ export const getFeed = asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const markedItems = await applyMutedWords(
|
||||
const mutedItems = await applyMutedWords(
|
||||
(posts as Record<string, unknown>[]).map(toTunableItem),
|
||||
userId
|
||||
);
|
||||
const tunedPosts = applySelfLabelBehavior(tuneFeed(markedItems), labelOpts);
|
||||
const { items: markedItems, preferredLangOnly } =
|
||||
await applyPreferredLanguage(mutedItems, userId);
|
||||
const tunedPosts = applySelfLabelBehavior(
|
||||
tuneFeed(markedItems, { preferredLangOnly }),
|
||||
labelOpts
|
||||
);
|
||||
|
||||
res.json({ posts: tunedPosts, isDiscover: false });
|
||||
});
|
||||
|
||||
@ -138,6 +138,11 @@ router.get('/tagged/:userId', optionalAuth, postController.getTaggedPosts);
|
||||
import { getOptimalPostingTimes } from '../controllers/scheduledPostsController';
|
||||
router.get('/optimal-times', authenticate, getOptimalPostingTimes);
|
||||
|
||||
// Feed-feedback signals (not-interested / show-more / seen) for personalisation.
|
||||
// Registered before the '/:id' routes so 'feedback' is not parsed as an id.
|
||||
import { recordFeedFeedback } from '../controllers/feedFeedbackController';
|
||||
router.post('/feedback', authenticate, interactionLimiter, recordFeedFeedback);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/v1/posts/archived:
|
||||
|
||||
@ -72,6 +72,19 @@ export interface TunableFeedItem {
|
||||
* a dangling reply with no visible context.
|
||||
*/
|
||||
isOrphan?: boolean;
|
||||
/**
|
||||
* Detected spoken/natural-language code of this item's content (ISO 639-1 or
|
||||
* 639-2, e.g. "en"). Undefined/null when the language is unknown. Consumed by
|
||||
* the `preferredLangOnly` step, which keeps an item when this matches one of
|
||||
* the viewer's preferred languages. Items whose language is unknown are always
|
||||
* kept (never filtered out) so undetected posts are not silently hidden.
|
||||
*
|
||||
* Ported from Bluesky's `FeedTuner.preferredLangOnly` (which calls
|
||||
* `isPostInLanguage`); Gitgram precomputes the per-item match flag in
|
||||
* services/languagePreferenceService.ts before tuning, so the tuner stays
|
||||
* content-agnostic and does no language detection itself.
|
||||
*/
|
||||
isPreferredLanguage?: boolean;
|
||||
/** Pre-computed feed ranking score (higher = better). */
|
||||
score: number;
|
||||
/** Optional trending score override; computed on-the-fly when absent. */
|
||||
@ -183,6 +196,24 @@ export interface FeedTunerOptions {
|
||||
* @default true
|
||||
*/
|
||||
removeOrphans?: boolean;
|
||||
|
||||
/**
|
||||
* When true, keep only items whose detected content language matches one of
|
||||
* the viewer's preferred languages (`isPreferredLanguage === true`). Items
|
||||
* with an unknown language (`isPreferredLanguage === undefined`) are always
|
||||
* kept so undetected posts are never hidden.
|
||||
*
|
||||
* Ported from Bluesky's `FeedTuner.preferredLangOnly`. Crucially it carries
|
||||
* Bluesky's "never return an empty page" fallback: if the language filter
|
||||
* would clear out the entire page, the original (unfiltered) set is returned
|
||||
* so the feed never goes blank.
|
||||
*
|
||||
* Defaults to FALSE: filtering only happens when a caller opts in (typically
|
||||
* because the viewer has configured natural-language preferences). For the
|
||||
* largely-English, dev-centric default audience the step is a no-op.
|
||||
* @default false
|
||||
*/
|
||||
preferredLangOnly?: boolean;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -200,6 +231,7 @@ const DEFAULT_DEDUPE_THREADS = true;
|
||||
const DEFAULT_REMOVE_MUTED_THREADS = true;
|
||||
const DEFAULT_REMOVE_MUTED_WORDS = true;
|
||||
const DEFAULT_REMOVE_ORPHANS = true;
|
||||
const DEFAULT_PREFERRED_LANG_ONLY = false;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helpers (pure functions — no side-effects)
|
||||
@ -524,6 +556,35 @@ function dropMutedWords(items: ReadonlyArray<TunableFeedItem>): TunableFeedItem[
|
||||
return items.filter(item => item.isMutedWord !== true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep only items whose detected content language matches the viewer's
|
||||
* preferred languages. Ported from Bluesky's `FeedTuner.preferredLangOnly`.
|
||||
*
|
||||
* Semantics:
|
||||
* - An item with `isPreferredLanguage === true` is kept.
|
||||
* - An item with `isPreferredLanguage === undefined` (unknown language) is
|
||||
* kept, so undetected posts are never silently hidden.
|
||||
* - An item with `isPreferredLanguage === false` (known, non-preferred
|
||||
* language) is dropped.
|
||||
* - "Never return an empty page": if the filter clears out the ENTIRE input,
|
||||
* the original set is returned unchanged so the feed never goes blank.
|
||||
*
|
||||
* Returns a new array — input is not modified.
|
||||
*/
|
||||
function filterPreferredLanguage(
|
||||
items: ReadonlyArray<TunableFeedItem>
|
||||
): TunableFeedItem[] {
|
||||
const candidates = items.filter(item => item.isPreferredLanguage !== false);
|
||||
|
||||
// If the language filter cleared out the entire page, fall back to the
|
||||
// original set so that something always shows (Bluesky parity).
|
||||
if (candidates.length === 0) {
|
||||
return [...items];
|
||||
}
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FeedTuner class
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -554,6 +615,7 @@ export class FeedTuner {
|
||||
removeMutedThreads: options.removeMutedThreads ?? DEFAULT_REMOVE_MUTED_THREADS,
|
||||
removeMutedWords: options.removeMutedWords ?? DEFAULT_REMOVE_MUTED_WORDS,
|
||||
removeOrphans: options.removeOrphans ?? DEFAULT_REMOVE_ORPHANS,
|
||||
preferredLangOnly: options.preferredLangOnly ?? DEFAULT_PREFERRED_LANG_ONLY,
|
||||
};
|
||||
}
|
||||
|
||||
@ -565,13 +627,15 @@ export class FeedTuner {
|
||||
* 2. Drop orphaned replies (removeOrphans)
|
||||
* 3. Drop muted threads (removeMutedThreads)
|
||||
* 4. Drop muted words/tags (removeMutedWords)
|
||||
* 5. Apply score adjustments (trending boost + diversity penalty)
|
||||
* 6. Re-sort by adjusted score
|
||||
* 7. Collapse threads by root (dedupThreads) — keeps the highest-scoring
|
||||
* 5. Filter to preferred natural languages (preferredLangOnly), with a
|
||||
* never-empty-page fallback
|
||||
* 6. Apply score adjustments (trending boost + diversity penalty)
|
||||
* 7. Re-sort by adjusted score
|
||||
* 8. Collapse threads by root (dedupThreads) — keeps the highest-scoring
|
||||
* entry per thread, so it runs after the sort
|
||||
* 8. Enforce author run limit
|
||||
* 9. Interleave content types
|
||||
* 10. Inject sponsored items
|
||||
* 9. Enforce author run limit
|
||||
* 10. Interleave content types
|
||||
* 11. Inject sponsored items
|
||||
*
|
||||
* @param posts - Raw feed items (not mutated).
|
||||
* @returns New array of tuned feed items.
|
||||
@ -587,7 +651,10 @@ export class FeedTuner {
|
||||
const withoutMuted = this.options.removeMutedWords
|
||||
? dropMutedWords(withoutMutedThreads)
|
||||
: withoutMutedThreads;
|
||||
const adjusted = applyScoreAdjustments(withoutMuted, this.options);
|
||||
const langFiltered = this.options.preferredLangOnly
|
||||
? filterPreferredLanguage(withoutMuted)
|
||||
: withoutMuted;
|
||||
const adjusted = applyScoreAdjustments(langFiltered, this.options);
|
||||
const sorted = sortByScore(adjusted);
|
||||
const threadDeduped = this.options.dedupeThreads
|
||||
? deduplicateByThreadRoot(sorted)
|
||||
|
||||
180
gitgram/backend/src/services/languagePreferenceService.ts
Normal file
180
gitgram/backend/src/services/languagePreferenceService.ts
Normal file
@ -0,0 +1,180 @@
|
||||
/**
|
||||
* languagePreferenceService.ts
|
||||
*
|
||||
* Natural-language (spoken-language) feed preferences.
|
||||
*
|
||||
* Ported from Bluesky's `FeedTuner.preferredLangOnly` + the
|
||||
* `src/state/preferences/feed-tuners.tsx` wiring (which feeds the viewer's
|
||||
* `contentLanguages` into the tuner). Bluesky calls `isPostInLanguage(post,
|
||||
* preferredLangsCode2)` per post; Gitgram precomputes the same per-post match
|
||||
* flag here so the tuner (services/feedTuner.ts) stays content-agnostic.
|
||||
*
|
||||
* The list of preferred natural languages is read from the existing
|
||||
* `UserLanguagePreference` model. That table is ALSO populated with PROGRAMMING
|
||||
* languages by the recommendation/search subsystems (e.g. "TypeScript",
|
||||
* "Python"), so this service filters the rows down to recognised spoken-language
|
||||
* codes only. Programming-language rows are simply ignored — they never
|
||||
* participate in feed language filtering, and this service never writes to the
|
||||
* table, so the recommendation feature is unaffected.
|
||||
*
|
||||
* Every export is a PURE function or a thin Prisma data-access wrapper; the
|
||||
* matcher performs no I/O and never mutates its inputs.
|
||||
*/
|
||||
|
||||
import { prisma } from '../utils/prisma';
|
||||
|
||||
/**
|
||||
* Recognised spoken/natural-language codes (ISO 639-1, with a few common 639-2
|
||||
* codes). Used to distinguish a viewer's natural-language preferences from the
|
||||
* programming-language entries that share the `UserLanguagePreference` table.
|
||||
*
|
||||
* This is intentionally a curated allow-list rather than an exhaustive registry:
|
||||
* it covers the languages a content-language detector is realistically going to
|
||||
* emit, while reliably excluding programming-language names ("Go", "C", "R",
|
||||
* etc. are NOT spoken-language codes here).
|
||||
*/
|
||||
const SPOKEN_LANGUAGE_CODES: ReadonlySet<string> = new Set([
|
||||
'aa', 'ab', 'af', 'ak', 'am', 'ar', 'as', 'ay', 'az',
|
||||
'be', 'bg', 'bm', 'bn', 'bo', 'br', 'bs',
|
||||
'ca', 'cs', 'cy',
|
||||
'da', 'de', 'dv', 'dz',
|
||||
'ee', 'el', 'en', 'eo', 'es', 'et', 'eu',
|
||||
'fa', 'ff', 'fi', 'fo', 'fr', 'fy',
|
||||
'ga', 'gd', 'gl', 'gn', 'gu', 'gv',
|
||||
'ha', 'he', 'hi', 'hr', 'ht', 'hu', 'hy',
|
||||
'id', 'ig', 'is', 'it',
|
||||
'ja', 'jv',
|
||||
'ka', 'kk', 'km', 'kn', 'ko', 'ku', 'kw', 'ky',
|
||||
'la', 'lb', 'lo', 'lt', 'lv',
|
||||
'mg', 'mi', 'mk', 'ml', 'mn', 'mr', 'ms', 'mt', 'my',
|
||||
'nb', 'ne', 'nl', 'nn', 'no',
|
||||
'oc', 'om', 'or',
|
||||
'pa', 'pl', 'ps', 'pt',
|
||||
'qu',
|
||||
'rm', 'rn', 'ro', 'ru', 'rw',
|
||||
'sa', 'sd', 'se', 'sg', 'si', 'sk', 'sl', 'sn', 'so', 'sq', 'sr', 'su', 'sv', 'sw',
|
||||
'ta', 'te', 'tg', 'th', 'ti', 'tk', 'tl', 'tn', 'to', 'tr', 'ts', 'tt',
|
||||
'ug', 'uk', 'ur', 'uz',
|
||||
've', 'vi',
|
||||
'wo',
|
||||
'xh',
|
||||
'yi', 'yo',
|
||||
'zh', 'zu',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Normalise a language tag to its lowercase ISO 639-1/639-2 base code.
|
||||
*
|
||||
* Accepts BCP-47-ish tags ("en-US", "pt_BR", "zh-Hant") and reduces them to the
|
||||
* primary subtag ("en", "pt", "zh"). Returns '' when the input is unusable.
|
||||
* Mirrors Bluesky's `code3ToCode2`/`toCode2`-style normalisation at the
|
||||
* coarse-grained level the feed filter needs.
|
||||
*/
|
||||
export function normalizeLanguageCode(input: string | null | undefined): string {
|
||||
if (typeof input !== 'string') return '';
|
||||
const trimmed = input.trim().toLowerCase();
|
||||
if (trimmed.length === 0) return '';
|
||||
// Primary subtag only: split on '-' or '_'.
|
||||
const primary = trimmed.split(/[-_]/)[0];
|
||||
return primary;
|
||||
}
|
||||
|
||||
/** Is `code` a recognised spoken/natural-language code (after normalisation)? */
|
||||
export function isSpokenLanguageCode(code: string | null | undefined): boolean {
|
||||
const normalized = normalizeLanguageCode(code);
|
||||
return normalized.length > 0 && SPOKEN_LANGUAGE_CODES.has(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether a post's content language matches the viewer's preferred
|
||||
* natural languages. Pure; performs no I/O. Mirrors the boolean returned by
|
||||
* Bluesky's `isPostInLanguage`.
|
||||
*
|
||||
* Semantics:
|
||||
* - Empty `preferredLanguages` => no preference, everything matches (true).
|
||||
* - Unknown/undetected `contentLanguage` => true (never hide undetected posts).
|
||||
* - Otherwise => true iff the normalised content language is in the preferred
|
||||
* set.
|
||||
*
|
||||
* @returns true when the post should be considered in-language for this viewer.
|
||||
*/
|
||||
export function isPostInPreferredLanguage(
|
||||
contentLanguage: string | null | undefined,
|
||||
preferredLanguages: ReadonlySet<string>
|
||||
): boolean {
|
||||
if (preferredLanguages.size === 0) return true;
|
||||
const code = normalizeLanguageCode(contentLanguage);
|
||||
if (code.length === 0) return true; // unknown language: always keep
|
||||
return preferredLanguages.has(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the viewer's PREFERRED NATURAL languages from `UserLanguagePreference`,
|
||||
* filtered to recognised spoken-language codes and ordered by descending weight
|
||||
* then score. Programming-language rows are excluded. Returns a normalised,
|
||||
* de-duplicated set of ISO-639 base codes (empty when the viewer has no spoken
|
||||
* language preferences configured).
|
||||
*/
|
||||
export async function getPreferredLanguagesForUser(
|
||||
userId: string
|
||||
): Promise<Set<string>> {
|
||||
const rows = await prisma.userLanguagePreference.findMany({
|
||||
where: { userId },
|
||||
orderBy: [{ weight: 'desc' }, { score: 'desc' }],
|
||||
select: { language: true },
|
||||
});
|
||||
|
||||
const preferred = new Set<string>();
|
||||
for (const row of rows) {
|
||||
if (isSpokenLanguageCode(row.language)) {
|
||||
preferred.add(normalizeLanguageCode(row.language));
|
||||
}
|
||||
}
|
||||
return preferred;
|
||||
}
|
||||
|
||||
/** A feed post considered for preferred-language marking. */
|
||||
export interface FeedLanguageCandidate {
|
||||
id: string;
|
||||
/** Detected content language code, or null when unknown. */
|
||||
contentLanguage: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* For each feed post, decide whether it is in one of the viewer's preferred
|
||||
* natural languages. Returns a map of post id -> match flag where:
|
||||
*
|
||||
* - `true` the post is in a preferred language (or its language is
|
||||
* unknown, which is always kept).
|
||||
* - `false` the post has a known, non-preferred language and should be
|
||||
* dropped by the tuner's `preferredLangOnly` step.
|
||||
*
|
||||
* When the viewer has NO spoken-language preferences configured, every value is
|
||||
* `true` (no filtering) and no per-post work is needed. This mirrors the feed
|
||||
* read path's `computeMutedFeedFlags` shape so the controller can apply both
|
||||
* uniformly.
|
||||
*/
|
||||
export async function computePreferredLanguageFlags(
|
||||
userId: string,
|
||||
candidates: ReadonlyArray<FeedLanguageCandidate>
|
||||
): Promise<Map<string, boolean>> {
|
||||
const result = new Map<string, boolean>();
|
||||
for (const c of candidates) result.set(c.id, true);
|
||||
|
||||
if (candidates.length === 0) return result;
|
||||
|
||||
const preferred = await getPreferredLanguagesForUser(userId);
|
||||
if (preferred.size === 0) {
|
||||
// No preference => everything is "in language".
|
||||
return result;
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
result.set(
|
||||
candidate.id,
|
||||
isPostInPreferredLanguage(candidate.contentLanguage, preferred)
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@ -2,6 +2,7 @@ import { Tabs } from 'expo-router';
|
||||
import { Colors } from '../../constants/Colors';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
import { emitSoftReset } from '../../utils/events';
|
||||
import MinimalShellTabBar from '../../components/navigation/MinimalShellTabBar';
|
||||
|
||||
/**
|
||||
* Fires a soft reset (scroll-to-top + refresh) when the user taps the tab that
|
||||
@ -23,6 +24,7 @@ const softResetListeners = ({
|
||||
export default function TabsLayout() {
|
||||
return (
|
||||
<Tabs
|
||||
tabBar={(props) => <MinimalShellTabBar {...props} />}
|
||||
screenOptions={{
|
||||
headerShown: false,
|
||||
tabBarActiveTintColor: Colors.primary,
|
||||
|
||||
@ -12,6 +12,7 @@ import {
|
||||
FlatList,
|
||||
RefreshControl,
|
||||
TouchableOpacity,
|
||||
Animated,
|
||||
NativeSyntheticEvent,
|
||||
NativeScrollEvent,
|
||||
} from 'react-native';
|
||||
@ -31,6 +32,10 @@ import { adService } from '../../services/adService';
|
||||
import repositoryService from '../../services/repositoryService';
|
||||
import { storyService } from '../../services/storyService';
|
||||
import { usePostViewTracking } from '../../hooks/usePostViewTracking';
|
||||
import {
|
||||
useMinimalShell,
|
||||
useMinimalHeaderStyle,
|
||||
} from '../../hooks/useMinimalShell';
|
||||
import { listenSoftReset } from '../../utils/events';
|
||||
import { logger } from '../../utils/logger';
|
||||
import { useRouter } from 'expo-router';
|
||||
@ -40,6 +45,9 @@ type FeedItem = { type: 'post' | 'ad' | 'repo'; data: any; index: number };
|
||||
// Distance (px) the user must scroll down before the "load latest" pill appears.
|
||||
const LOAD_LATEST_OFFSET = 320;
|
||||
|
||||
// Height of the top app bar; the minimal-shell header collapses by this much.
|
||||
const HEADER_HEIGHT = 56;
|
||||
|
||||
interface TrendingRepo {
|
||||
fullName: string;
|
||||
description?: string;
|
||||
@ -117,6 +125,11 @@ export default function HomeScreen() {
|
||||
// a background poll surfaces fresher content.
|
||||
const newestPostIdRef = useRef<string | null>(null);
|
||||
|
||||
// Hide-on-scroll: collapse the header (and bottom tab bar) on downward
|
||||
// scroll, reveal on upward scroll. Shared with the tab bar via a singleton.
|
||||
const minimalShell = useMinimalShell();
|
||||
const headerAnimStyle = useMinimalHeaderStyle(HEADER_HEIGHT);
|
||||
|
||||
const { onViewableItemsChanged, reset: resetViewTracking } =
|
||||
usePostViewTracking<FeedItem>({
|
||||
logContext: 'home-feed',
|
||||
@ -240,8 +253,9 @@ export default function HomeScreen() {
|
||||
const scrollToTopAndRefresh = useCallback(() => {
|
||||
listRef.current?.scrollToOffset({ offset: 0, animated: true });
|
||||
setScrolledDown(false);
|
||||
minimalShell.reveal();
|
||||
handleRefresh();
|
||||
}, []);
|
||||
}, [minimalShell]);
|
||||
|
||||
// Soft reset: re-pressing the Home tab scrolls to top and reloads.
|
||||
useEffect(() => {
|
||||
@ -283,8 +297,10 @@ export default function HomeScreen() {
|
||||
const next = offsetY > LOAD_LATEST_OFFSET;
|
||||
return prev === next ? prev : next;
|
||||
});
|
||||
// Drive the collapsing header + tab bar.
|
||||
minimalShell.onScroll(event);
|
||||
},
|
||||
[],
|
||||
[minimalShell],
|
||||
);
|
||||
|
||||
if (loading && posts.length === 0) {
|
||||
@ -327,6 +343,12 @@ export default function HomeScreen() {
|
||||
return items;
|
||||
}, [posts, ads, trendingRepos]);
|
||||
|
||||
// Remove a post the viewer hid ("Not interested") or whose author they
|
||||
// blocked, so it disappears from the feed immediately.
|
||||
const handleHidePost = useCallback((postId: string) => {
|
||||
setPosts((prev) => prev.filter((p) => p?.id !== postId));
|
||||
}, []);
|
||||
|
||||
const renderItem = useCallback(({ item }: { item: FeedItem }) => {
|
||||
if (item.type === 'ad') {
|
||||
return <AdCard ad={item.data} />;
|
||||
@ -334,8 +356,8 @@ export default function HomeScreen() {
|
||||
if (item.type === 'repo') {
|
||||
return <TrendingRepoCard repo={toTrendingRepo(item.data as Record<string, unknown>)} />;
|
||||
}
|
||||
return <PostCard post={item.data} />;
|
||||
}, []);
|
||||
return <PostCard post={item.data} onHide={handleHidePost} />;
|
||||
}, [handleHidePost]);
|
||||
|
||||
const keyExtractor = useCallback((item: FeedItem) => {
|
||||
if (item.type === 'ad') return `ad-${item.data.id}`;
|
||||
@ -347,8 +369,8 @@ export default function HomeScreen() {
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['top']}>
|
||||
{/* Top App Bar */}
|
||||
<View style={styles.header}>
|
||||
{/* Top App Bar — collapses on downward scroll (minimal shell). */}
|
||||
<Animated.View style={[styles.header, styles.headerAbsolute, headerAnimStyle]}>
|
||||
<View style={styles.headerLeft}>
|
||||
<Text style={styles.headerIcon}>💻</Text>
|
||||
<Text style={styles.headerTitle}>Gitgram</Text>
|
||||
@ -374,7 +396,7 @@ export default function HomeScreen() {
|
||||
<Text style={styles.headerButtonIcon}>📤</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
|
||||
{/* Main Content Feed */}
|
||||
<View style={styles.feedContainer}>
|
||||
@ -468,12 +490,21 @@ const styles = StyleSheet.create({
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
height: 56,
|
||||
height: HEADER_HEIGHT,
|
||||
paddingHorizontal: 16,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: Colors.border,
|
||||
backgroundColor: Colors.background,
|
||||
},
|
||||
// Absolutely positioned so collapsing it reclaims vertical feed space; the
|
||||
// list compensates with matching top padding.
|
||||
headerAbsolute: {
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
zIndex: 10,
|
||||
},
|
||||
headerLeft: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
@ -511,6 +542,7 @@ const styles = StyleSheet.create({
|
||||
position: 'relative',
|
||||
},
|
||||
listContent: {
|
||||
paddingTop: HEADER_HEIGHT, // Clear the absolutely-positioned app bar
|
||||
paddingBottom: 80, // Space for bottom tab bar
|
||||
},
|
||||
skeletonList: {
|
||||
|
||||
@ -12,20 +12,16 @@ import { useRouter } from 'expo-router';
|
||||
import { Colors } from '../../constants/Colors';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import GestureActionView from '../../components/common/GestureActionView';
|
||||
import { notificationService } from '../../services/notificationService';
|
||||
import {
|
||||
notificationService,
|
||||
groupNotifications,
|
||||
type Notification,
|
||||
type GroupedNotification,
|
||||
} from '../../services/notificationService';
|
||||
import { userService } from '../../services/userService';
|
||||
import { useToast } from '../../hooks/useToast';
|
||||
import { listenSoftReset } from '../../utils/events';
|
||||
|
||||
interface Notification {
|
||||
id: string;
|
||||
type: string;
|
||||
title: string;
|
||||
body: string;
|
||||
isRead: boolean;
|
||||
createdAt: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
import { timeAgo } from '../../utils/timeAgo';
|
||||
|
||||
const getStringValue = (data: Record<string, unknown> | undefined, key: string): string | undefined => {
|
||||
const value = data?.[key];
|
||||
@ -40,7 +36,7 @@ export default function NotificationsScreen() {
|
||||
const [followingUsers, setFollowingUsers] = useState<Set<string>>(new Set());
|
||||
const [followLoading, setFollowLoading] = useState<Set<string>>(new Set());
|
||||
const { showToast, ToastComponent } = useToast();
|
||||
const listRef = useRef<FlatList<Notification>>(null);
|
||||
const listRef = useRef<FlatList<GroupedNotification>>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadNotifications();
|
||||
@ -217,69 +213,118 @@ export default function NotificationsScreen() {
|
||||
}
|
||||
};
|
||||
|
||||
const formatTime = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - date.getTime();
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
// Avatar entries for a grouped row's actor stack (deduped, base actor first).
|
||||
const getGroupActors = useCallback(
|
||||
(group: GroupedNotification): { username: string; avatar?: string }[] => {
|
||||
const all = [group.notification, ...group.additional];
|
||||
const seen = new Set<string>();
|
||||
const actors: { username: string; avatar?: string }[] = [];
|
||||
for (const n of all) {
|
||||
const username = getStringValue(n.data, 'username') || 'user';
|
||||
const userId = getStringValue(n.data, 'userId') || username;
|
||||
if (seen.has(userId)) continue;
|
||||
seen.add(userId);
|
||||
actors.push({ username, avatar: getStringValue(n.data, 'avatar') });
|
||||
}
|
||||
return actors;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
if (minutes < 1) return 'just now';
|
||||
if (minutes < 60) return `${minutes}m ago`;
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
if (days < 7) return `${days}d ago`;
|
||||
return date.toLocaleDateString();
|
||||
};
|
||||
// Builds the aggregated headline, e.g. "@alice and 5 others liked your post".
|
||||
const buildGroupText = useCallback(
|
||||
(group: GroupedNotification): { actorLabel: string; body: string } => {
|
||||
const actors = getGroupActors(group);
|
||||
const primary = actors[0]?.username ?? 'user';
|
||||
const extra = group.actorCount - 1;
|
||||
const actorLabel =
|
||||
extra <= 0
|
||||
? `@${primary}`
|
||||
: extra === 1 && actors[1]
|
||||
? `@${primary} and @${actors[1].username}`
|
||||
: `@${primary} and ${extra} ${extra === 1 ? 'other' : 'others'}`;
|
||||
return { actorLabel, body: group.notification.body };
|
||||
},
|
||||
[getGroupActors],
|
||||
);
|
||||
|
||||
const renderNotification = ({ item }: { item: Notification }) => {
|
||||
const { icon, color } = getNotificationIcon(item.type);
|
||||
const userId = getStringValue(item.data, 'userId');
|
||||
const username = getStringValue(item.data, 'username') || 'user';
|
||||
const thumbnail = getStringValue(item.data, 'thumbnail');
|
||||
const renderNotification = ({ item }: { item: GroupedNotification }) => {
|
||||
const base = item.notification;
|
||||
const { icon, color } = getNotificationIcon(base.type);
|
||||
const userId = getStringValue(base.data, 'userId');
|
||||
const thumbnail = getStringValue(base.data, 'thumbnail');
|
||||
const isFollowing = userId ? followingUsers.has(userId) : false;
|
||||
const isLoading = userId ? followLoading.has(userId) : false;
|
||||
const { actorLabel, body } = buildGroupText(item);
|
||||
const actors = getGroupActors(item);
|
||||
const isGroup = item.actorCount > 1;
|
||||
const ids = [base.id, ...item.additional.map((n) => n.id)];
|
||||
const allRead = base.isRead && item.additional.every((n) => n.isRead);
|
||||
|
||||
return (
|
||||
<GestureActionView
|
||||
actions={{
|
||||
left: item.isRead
|
||||
left: allRead
|
||||
? undefined
|
||||
: {
|
||||
color: Colors.info,
|
||||
icon: 'done',
|
||||
label: 'Read',
|
||||
action: () => handleMarkOneRead(item),
|
||||
action: () => ids.forEach((id) => handleMarkOneRead({ ...base, id })),
|
||||
},
|
||||
right: {
|
||||
color: Colors.error,
|
||||
icon: 'delete',
|
||||
label: 'Delete',
|
||||
action: () => handleDelete(item.id),
|
||||
action: () => ids.forEach((id) => handleDelete(id)),
|
||||
},
|
||||
}}
|
||||
>
|
||||
<TouchableOpacity
|
||||
style={[styles.notificationItem, !item.isRead && styles.unreadNotification]}
|
||||
onPress={() => handleNotificationPress(item)}
|
||||
style={[styles.notificationItem, !allRead && styles.unreadNotification]}
|
||||
onPress={() => handleNotificationPress(base)}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<View style={styles.avatarContainer}>
|
||||
<View style={[styles.iconBadge, { backgroundColor: color }]}>
|
||||
<Text style={styles.iconBadgeText}>{icon}</Text>
|
||||
</View>
|
||||
{isGroup ? (
|
||||
<View style={styles.avatarStack}>
|
||||
{actors.slice(0, 3).map((actor, idx) => (
|
||||
<View
|
||||
key={`${actor.username}-${idx}`}
|
||||
style={[styles.stackedAvatar, { left: idx * 18, zIndex: 3 - idx }]}
|
||||
>
|
||||
{actor.avatar ? (
|
||||
<Image source={{ uri: actor.avatar }} style={styles.stackedAvatarImg} />
|
||||
) : (
|
||||
<View style={[styles.stackedAvatarImg, styles.stackedAvatarFallback]}>
|
||||
<Text style={styles.stackedAvatarInitial}>
|
||||
{actor.username.charAt(0).toUpperCase()}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
))}
|
||||
<View style={[styles.miniBadge, { backgroundColor: color }]}>
|
||||
<Text style={styles.miniBadgeText}>{icon}</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<View style={[styles.iconBadge, { backgroundColor: color }]}>
|
||||
<Text style={styles.iconBadgeText}>{icon}</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
<View style={styles.notificationContent}>
|
||||
<Text style={styles.notificationText}>
|
||||
<Text style={styles.usernameText}>@{username}</Text>{' '}
|
||||
{item.body}
|
||||
<Text style={styles.usernameText}>{actorLabel}</Text>{' '}
|
||||
{body}
|
||||
</Text>
|
||||
<Text style={styles.notificationTime}>{formatTime(item.createdAt)}</Text>
|
||||
<Text style={styles.notificationTime}>{timeAgo(base.createdAt, { format: 'long' })} ago</Text>
|
||||
</View>
|
||||
{thumbnail && (
|
||||
<Image source={{ uri: thumbnail }} style={styles.thumbnail} />
|
||||
)}
|
||||
{item.type === 'follow' && userId && !isFollowing && (
|
||||
{!isGroup && base.type === 'follow' && userId && !isFollowing && (
|
||||
<TouchableOpacity
|
||||
style={styles.followButton}
|
||||
onPress={(e) => {
|
||||
@ -295,7 +340,7 @@ export default function NotificationsScreen() {
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
{item.type === 'follow' && userId && isFollowing && (
|
||||
{!isGroup && base.type === 'follow' && userId && isFollowing && (
|
||||
<View style={[styles.followButton, styles.followingButton]}>
|
||||
<Text style={styles.followButtonText}>Following</Text>
|
||||
</View>
|
||||
@ -313,6 +358,8 @@ export default function NotificationsScreen() {
|
||||
? notifications.filter(n => n.type !== 'following')
|
||||
: notifications.filter(n => n.type === 'following');
|
||||
|
||||
const groupedNotifications = groupNotifications(filteredNotifications);
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
{ToastComponent}
|
||||
@ -366,9 +413,9 @@ export default function NotificationsScreen() {
|
||||
{/* Notifications List */}
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={filteredNotifications}
|
||||
data={groupedNotifications}
|
||||
renderItem={renderNotification}
|
||||
keyExtractor={(item) => item.id}
|
||||
keyExtractor={(item) => item.key}
|
||||
ItemSeparatorComponent={() => <View style={styles.separator} />}
|
||||
ListEmptyComponent={
|
||||
<View style={styles.emptyState}>
|
||||
@ -471,6 +518,46 @@ const styles = StyleSheet.create({
|
||||
iconBadgeText: {
|
||||
fontSize: 20,
|
||||
},
|
||||
avatarStack: {
|
||||
width: 84,
|
||||
height: 48,
|
||||
justifyContent: 'center',
|
||||
},
|
||||
stackedAvatar: {
|
||||
position: 'absolute',
|
||||
},
|
||||
stackedAvatarImg: {
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 18,
|
||||
borderWidth: 2,
|
||||
borderColor: Colors.background,
|
||||
},
|
||||
stackedAvatarFallback: {
|
||||
backgroundColor: Colors.primary,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
stackedAvatarInitial: {
|
||||
color: Colors.text,
|
||||
fontSize: 14,
|
||||
fontWeight: '700',
|
||||
},
|
||||
miniBadge: {
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 28,
|
||||
width: 22,
|
||||
height: 22,
|
||||
borderRadius: 11,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
borderWidth: 2,
|
||||
borderColor: Colors.background,
|
||||
},
|
||||
miniBadgeText: {
|
||||
fontSize: 11,
|
||||
},
|
||||
notificationContent: {
|
||||
flex: 1,
|
||||
},
|
||||
|
||||
@ -4,14 +4,18 @@ import {
|
||||
Text,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
Alert,
|
||||
} from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Image } from 'expo-image';
|
||||
import { Colors } from '../../constants/Colors';
|
||||
import { postService } from '../../services/postService';
|
||||
import { userService } from '../../services/userService';
|
||||
import { logger } from '../../utils/logger';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useHaptics } from '../../hooks/useHaptics';
|
||||
import { useToast } from '../../hooks/useToast';
|
||||
import { timeAgo } from '../../utils/timeAgo';
|
||||
import PostOptionsModal from '../common/PostOptionsModal';
|
||||
import ReportModal from '../common/ReportModal';
|
||||
import CodeBlock from '../common/CodeBlock';
|
||||
@ -47,23 +51,88 @@ interface PostCardProps {
|
||||
onLike?: () => void;
|
||||
onPress?: () => void;
|
||||
showFullContent?: boolean;
|
||||
/**
|
||||
* Called when the viewer hides this post ("Not interested") or blocks its
|
||||
* author. The parent can drop the post from its feed list; if omitted the
|
||||
* card hides itself locally.
|
||||
*/
|
||||
onHide?: (postId: string) => void;
|
||||
}
|
||||
|
||||
export default function PostCard({ post, onLike, showFullContent = false }: PostCardProps) {
|
||||
export default function PostCard({ post, onLike, showFullContent = false, onHide }: PostCardProps) {
|
||||
const router = useRouter();
|
||||
const { user } = useAuthStore();
|
||||
const haptics = useHaptics();
|
||||
const openLightbox = useLightbox();
|
||||
const { showToast, ToastComponent } = useToast();
|
||||
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 [hidden, setHidden] = useState(false);
|
||||
const [isBlocked, setIsBlocked] = useState(false);
|
||||
const [blocking, setBlocking] = useState(false);
|
||||
const likeBounceRef = useRef<LikeBounceAnimationHandle>(null);
|
||||
const lastTapRef = useRef(0);
|
||||
|
||||
const isOwner = user?.id === post.user.id;
|
||||
|
||||
// Hide this post from the viewer's feed ("Not interested"). Purely
|
||||
// client-side: the parent feed can prune it, otherwise we self-hide.
|
||||
const handleHidePost = () => {
|
||||
haptics('Light');
|
||||
if (onHide) {
|
||||
onHide(post.id);
|
||||
} else {
|
||||
setHidden(true);
|
||||
}
|
||||
showToast('Post hidden', 'success');
|
||||
};
|
||||
|
||||
const handleBlockUser = () => {
|
||||
if (blocking) return;
|
||||
const action = isBlocked ? 'Unblock' : 'Block';
|
||||
Alert.alert(
|
||||
`${action} @${post.user.username}?`,
|
||||
isBlocked
|
||||
? 'They will be able to see your content and interact with you again.'
|
||||
: "You won't see their posts and they won't be able to interact with you.",
|
||||
[
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{
|
||||
text: action,
|
||||
style: isBlocked ? 'default' : 'destructive',
|
||||
onPress: async () => {
|
||||
setBlocking(true);
|
||||
try {
|
||||
if (isBlocked) {
|
||||
await userService.unblockUser(post.user.id);
|
||||
setIsBlocked(false);
|
||||
showToast(`Unblocked @${post.user.username}`, 'success');
|
||||
} else {
|
||||
await userService.blockUser(post.user.id);
|
||||
setIsBlocked(true);
|
||||
showToast(`Blocked @${post.user.username}`, 'success');
|
||||
// A blocked author's post should leave the feed immediately.
|
||||
if (onHide) {
|
||||
onHide(post.id);
|
||||
} else {
|
||||
setHidden(true);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Block user error:', error);
|
||||
showToast(`Failed to ${action.toLowerCase()} user`, 'error');
|
||||
} finally {
|
||||
setBlocking(false);
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
// 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') => {
|
||||
@ -116,8 +185,13 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post
|
||||
openLightbox([{ uri: post.mediaUrl, alt: post.content || undefined }], 0);
|
||||
};
|
||||
|
||||
if (hidden) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
{ToastComponent}
|
||||
{/* Card Header */}
|
||||
<View style={styles.header}>
|
||||
<TouchableOpacity
|
||||
@ -131,7 +205,10 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post
|
||||
<Text style={styles.avatarText}>{post.user.username[0].toUpperCase()}</Text>
|
||||
</View>
|
||||
)}
|
||||
<Text style={styles.username}>{post.user.username}</Text>
|
||||
<View style={styles.headerTextWrap}>
|
||||
<Text style={styles.username}>{post.user.username}</Text>
|
||||
<Text style={styles.timestamp}>{timeAgo(post.createdAt)}</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={styles.moreButton} onPress={() => setShowOptionsModal(true)}>
|
||||
<Text style={styles.moreIcon}>⋯</Text>
|
||||
@ -232,6 +309,10 @@ export default function PostCard({ post, onLike, showFullContent = false }: Post
|
||||
onClose={() => setShowOptionsModal(false)}
|
||||
onReport={() => setShowReportModal(true)}
|
||||
onShare={() => router.push(`/post/${post.id}/share`)}
|
||||
onHidePost={handleHidePost}
|
||||
onBlockUser={handleBlockUser}
|
||||
authorUsername={post.user.username}
|
||||
isBlocked={isBlocked}
|
||||
isOwner={isOwner}
|
||||
/>
|
||||
|
||||
@ -284,11 +365,19 @@ const styles = StyleSheet.create({
|
||||
fontWeight: 'bold',
|
||||
fontSize: 16,
|
||||
},
|
||||
headerTextWrap: {
|
||||
flexShrink: 1,
|
||||
},
|
||||
username: {
|
||||
color: Colors.text,
|
||||
fontWeight: 'bold',
|
||||
fontSize: 14,
|
||||
},
|
||||
timestamp: {
|
||||
color: Colors.textSecondary,
|
||||
fontSize: 12,
|
||||
marginTop: 1,
|
||||
},
|
||||
moreButton: {
|
||||
width: 32,
|
||||
height: 32,
|
||||
|
||||
@ -18,6 +18,14 @@ interface PostOptionsModalProps {
|
||||
isOwner?: boolean;
|
||||
onEdit?: () => void;
|
||||
onDelete?: () => void;
|
||||
/** Hide this post / "Not interested" — client-side feed filter. */
|
||||
onHidePost?: () => void;
|
||||
/** Block the post's author. */
|
||||
onBlockUser?: () => void;
|
||||
/** Username shown in the block/hide labels for clarity. */
|
||||
authorUsername?: string;
|
||||
/** Whether the author is already blocked (toggles label to Unblock). */
|
||||
isBlocked?: boolean;
|
||||
}
|
||||
|
||||
interface OptionItem {
|
||||
@ -38,6 +46,10 @@ export default function PostOptionsModal({
|
||||
isOwner = false,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onHidePost,
|
||||
onBlockUser,
|
||||
authorUsername,
|
||||
isBlocked = false,
|
||||
}: PostOptionsModalProps) {
|
||||
const handleOptionPress = (onPress: () => void) => {
|
||||
onClose();
|
||||
@ -70,6 +82,22 @@ export default function PostOptionsModal({
|
||||
onPress: () => onEdit?.(),
|
||||
hidden: !isOwner || !onEdit,
|
||||
},
|
||||
{
|
||||
// Client-side "not interested" filter — hides the post from the feed.
|
||||
label: 'Hide this post',
|
||||
icon: '🙈',
|
||||
onPress: () => onHidePost?.(),
|
||||
hidden: isOwner || !onHidePost,
|
||||
},
|
||||
{
|
||||
label: isBlocked
|
||||
? `Unblock${authorUsername ? ` @${authorUsername}` : ''}`
|
||||
: `Block${authorUsername ? ` @${authorUsername}` : ''}`,
|
||||
icon: '🚫',
|
||||
onPress: () => onBlockUser && handleOptionPress(onBlockUser),
|
||||
destructive: !isBlocked,
|
||||
hidden: isOwner || !onBlockUser,
|
||||
},
|
||||
{
|
||||
label: 'Report',
|
||||
icon: '🚩',
|
||||
|
||||
33
gitgram/mobile/components/navigation/MinimalShellTabBar.tsx
Normal file
33
gitgram/mobile/components/navigation/MinimalShellTabBar.tsx
Normal file
@ -0,0 +1,33 @@
|
||||
import React from 'react';
|
||||
import { Animated } from 'react-native';
|
||||
import {
|
||||
BottomTabBar,
|
||||
type BottomTabBarProps,
|
||||
} from '@react-navigation/bottom-tabs';
|
||||
|
||||
import { useMinimalFooterStyle } from '../../hooks/useMinimalShell';
|
||||
|
||||
/** Height of the tab bar; the footer collapses by this much when hidden. */
|
||||
const TAB_BAR_HEIGHT = 80;
|
||||
|
||||
/**
|
||||
* Bottom tab bar that participates in the "minimal shell" hide-on-scroll:
|
||||
* it slides down and fades out as the shared shell collapses (driven by the
|
||||
* feed's scroll via `useMinimalShell`), and reveals on upward scroll.
|
||||
*
|
||||
* Wraps the default `BottomTabBar` in an `Animated.View` so we keep all the
|
||||
* stock tab behavior (icons, labels, accessibility, soft-reset listeners)
|
||||
* while animating the container. The bar stays in normal layout flow so other
|
||||
* tab screens keep their existing bottom spacing — it slides off-screen on
|
||||
* collapse rather than being absolutely positioned, avoiding any cross-tab
|
||||
* content-overlap regression.
|
||||
*/
|
||||
export default function MinimalShellTabBar(props: BottomTabBarProps) {
|
||||
const footerStyle = useMinimalFooterStyle(TAB_BAR_HEIGHT);
|
||||
|
||||
return (
|
||||
<Animated.View style={footerStyle}>
|
||||
<BottomTabBar {...props} />
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
@ -9,6 +9,7 @@ import {
|
||||
import { Image } from 'expo-image';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { logger } from '../../utils/logger';
|
||||
import { timeAgo } from '../../utils/timeAgo';
|
||||
import { postService } from '../../services/postService';
|
||||
|
||||
interface PostAuthor {
|
||||
@ -29,18 +30,6 @@ interface PostCardProps {
|
||||
post: Post;
|
||||
}
|
||||
|
||||
function formatTimestamp(iso: string): string {
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
const minutes = Math.floor(diff / 60_000);
|
||||
if (minutes < 1) return 'just now';
|
||||
if (minutes < 60) return `${minutes}m ago`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return `${hours}h ago`;
|
||||
const days = Math.floor(hours / 24);
|
||||
if (days < 7) return `${days}d ago`;
|
||||
return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
export default function PostCard({ post }: PostCardProps) {
|
||||
const router = useRouter();
|
||||
const [likes, setLikes] = useState(post.likes);
|
||||
@ -111,7 +100,7 @@ export default function PostCard({ post }: PostCardProps) {
|
||||
{post.author.username}
|
||||
</Text>
|
||||
<Text style={styles.timestamp}>
|
||||
{formatTimestamp(post.createdAt)}
|
||||
{timeAgo(post.createdAt)}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
151
gitgram/mobile/hooks/useMinimalShell.ts
Normal file
151
gitgram/mobile/hooks/useMinimalShell.ts
Normal file
@ -0,0 +1,151 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import {
|
||||
Animated,
|
||||
Easing,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
} from 'react-native';
|
||||
|
||||
/**
|
||||
* "Minimal shell" hide-on-scroll, reimplemented from Bluesky's
|
||||
* useMinimalShellTransform + ScrollContext + minimal-mode state
|
||||
* (src/lib/hooks/useMinimalShellTransform.ts).
|
||||
*
|
||||
* Bluesky drives this with reanimated shared values; we reimplement on the RN
|
||||
* `Animated` API the product already uses (LoadLatestButton, GestureActionView)
|
||||
* so no new dependency is pulled in.
|
||||
*
|
||||
* `mode` is a single shared Animated.Value in [0, 1]:
|
||||
* 0 = shell fully visible, 1 = shell fully hidden (collapsed).
|
||||
*
|
||||
* The value is a module-level singleton so the feed header and the bottom tab
|
||||
* bar (which live in different component trees) collapse and reveal in sync.
|
||||
*/
|
||||
|
||||
// Singleton: shared by every consumer (header + tab bar) so they animate as one.
|
||||
const sharedMode = new Animated.Value(0);
|
||||
|
||||
// Distance (px) the user must scroll in a direction before we flip the shell.
|
||||
const SCROLL_THRESHOLD = 12;
|
||||
// Don't react to scrolls near the very top — the header should always be shown.
|
||||
const TOP_REVEAL_OFFSET = 24;
|
||||
const ANIM_DURATION = 200;
|
||||
|
||||
function setMode(target: 0 | 1): void {
|
||||
Animated.timing(sharedMode, {
|
||||
toValue: target,
|
||||
duration: ANIM_DURATION,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
// translate/opacity are native-driver safe.
|
||||
useNativeDriver: true,
|
||||
}).start();
|
||||
}
|
||||
|
||||
export interface MinimalShellScroll {
|
||||
/** Attach to a scrollable's `onScroll`. Pair with `scrollEventThrottle`. */
|
||||
onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
|
||||
/** Force the shell back to fully-visible (e.g. on tab focus / soft reset). */
|
||||
reveal: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a scroll handler that collapses the shell on downward scroll and
|
||||
* reveals it on upward scroll. Call once per scrollable feed.
|
||||
*/
|
||||
export function useMinimalShell(): MinimalShellScroll {
|
||||
const lastOffset = useRef(0);
|
||||
const lastMode = useRef<0 | 1>(0);
|
||||
|
||||
const onScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const offsetY = event.nativeEvent.contentOffset.y;
|
||||
const delta = offsetY - lastOffset.current;
|
||||
|
||||
// Always reveal near the top regardless of direction.
|
||||
if (offsetY <= TOP_REVEAL_OFFSET) {
|
||||
if (lastMode.current !== 0) {
|
||||
lastMode.current = 0;
|
||||
setMode(0);
|
||||
}
|
||||
lastOffset.current = offsetY;
|
||||
return;
|
||||
}
|
||||
|
||||
if (Math.abs(delta) < SCROLL_THRESHOLD) {
|
||||
return;
|
||||
}
|
||||
|
||||
const next: 0 | 1 = delta > 0 ? 1 : 0; // scrolling down hides, up reveals
|
||||
if (next !== lastMode.current) {
|
||||
lastMode.current = next;
|
||||
setMode(next);
|
||||
}
|
||||
lastOffset.current = offsetY;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const reveal = useCallback(() => {
|
||||
lastMode.current = 0;
|
||||
lastOffset.current = 0;
|
||||
setMode(0);
|
||||
}, []);
|
||||
|
||||
// Reset the shared shell when the consuming screen unmounts so a collapsed
|
||||
// header never leaks into a screen without a scroll handler.
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setMode(0);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { onScroll, reveal };
|
||||
}
|
||||
|
||||
/**
|
||||
* Animated style for a top header: slides up and fades out as the shell
|
||||
* collapses. `height` is the header's pixel height (the collapse distance).
|
||||
*/
|
||||
export function useMinimalHeaderStyle(height: number): {
|
||||
opacity: Animated.AnimatedInterpolation<number>;
|
||||
transform: { translateY: Animated.AnimatedInterpolation<number> }[];
|
||||
} {
|
||||
return {
|
||||
opacity: sharedMode.interpolate({
|
||||
inputRange: [0, 1],
|
||||
outputRange: [1, 0],
|
||||
}),
|
||||
transform: [
|
||||
{
|
||||
translateY: sharedMode.interpolate({
|
||||
inputRange: [0, 1],
|
||||
outputRange: [0, -height],
|
||||
}),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Animated style for the bottom tab bar: slides down and fades out as the
|
||||
* shell collapses. `height` is the tab bar's pixel height.
|
||||
*/
|
||||
export function useMinimalFooterStyle(height: number): {
|
||||
opacity: Animated.AnimatedInterpolation<number>;
|
||||
transform: { translateY: Animated.AnimatedInterpolation<number> }[];
|
||||
} {
|
||||
return {
|
||||
opacity: sharedMode.interpolate({
|
||||
inputRange: [0, 1],
|
||||
outputRange: [1, 0],
|
||||
}),
|
||||
transform: [
|
||||
{
|
||||
translateY: sharedMode.interpolate({
|
||||
inputRange: [0, 1],
|
||||
outputRange: [0, height],
|
||||
}),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
@ -1,5 +1,137 @@
|
||||
import api from './api';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Notification types + grouping
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** A single notification as returned by GET /notifications. */
|
||||
export interface Notification {
|
||||
id: string;
|
||||
type: string;
|
||||
title: string;
|
||||
body: string;
|
||||
isRead: boolean;
|
||||
createdAt: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A notification row after grouping. `additional` holds same-reason,
|
||||
* same-subject events that were collapsed into this row (newest-first base
|
||||
* notification, oldest collapsed events appended). `actorCount` is the total
|
||||
* number of distinct events represented (1 + additional.length).
|
||||
*/
|
||||
export interface GroupedNotification {
|
||||
/** Stable key for list rendering. */
|
||||
key: string;
|
||||
/** The representative (most recent) notification for this group. */
|
||||
notification: Notification;
|
||||
/** Other notifications merged into this group, if any. */
|
||||
additional: Notification[];
|
||||
/** Total number of events represented by this row. */
|
||||
actorCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reasons whose events are safe to collapse into a single row. Ported from
|
||||
* Bluesky's GROUPABLE_REASONS (src/state/queries/notifications/util.ts) and
|
||||
* mapped to the product's notification `type` vocabulary. Comment/mention-style
|
||||
* events are intentionally excluded so each carries its own context.
|
||||
*/
|
||||
const GROUPABLE_TYPES = new Set(['like', 'follow', 'star', 'repost', 'fork']);
|
||||
|
||||
/** 48h window (in ms) within which same-subject events are grouped. */
|
||||
const GROUP_WINDOW_MS = 1000 * 60 * 60 * 48;
|
||||
|
||||
const getStringField = (
|
||||
data: Record<string, unknown> | undefined,
|
||||
key: string,
|
||||
): string | undefined => {
|
||||
const value = data?.[key];
|
||||
return typeof value === 'string' ? value : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* The subject a notification refers to (post/repo/etc). Two events group only
|
||||
* when they share a type AND a subject, so we derive a stable subject key from
|
||||
* the notification payload.
|
||||
*/
|
||||
function getSubjectKey(notif: Notification): string | undefined {
|
||||
const data = notif.data;
|
||||
return (
|
||||
getStringField(data, 'postId') ??
|
||||
getStringField(data, 'repoFullName') ??
|
||||
(getStringField(data, 'repoOwner') && getStringField(data, 'repoName')
|
||||
? `${getStringField(data, 'repoOwner')}/${getStringField(data, 'repoName')}`
|
||||
: undefined) ??
|
||||
getStringField(data, 'targetId')
|
||||
);
|
||||
}
|
||||
|
||||
/** The actor (user) responsible for a notification, if identifiable. */
|
||||
function getActorKey(notif: Notification): string | undefined {
|
||||
return getStringField(notif.data, 'userId');
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapses same-type, same-subject notifications that occur within a 48h
|
||||
* window into single grouped rows ("Alice and 5 others liked your post").
|
||||
*
|
||||
* Pure function, ported from Bluesky's `groupNotifications` and adapted to the
|
||||
* product's flat Notification shape (no atproto dependency). Input order is
|
||||
* preserved for the resulting representative rows; distinct actors only are
|
||||
* grouped (an actor never groups with themselves on the same subject).
|
||||
*/
|
||||
export function groupNotifications(
|
||||
notifs: Notification[],
|
||||
): GroupedNotification[] {
|
||||
const grouped: GroupedNotification[] = [];
|
||||
|
||||
for (const notif of notifs) {
|
||||
const ts = new Date(notif.createdAt).getTime();
|
||||
let didGroup = false;
|
||||
|
||||
if (GROUPABLE_TYPES.has(notif.type)) {
|
||||
const subject = getSubjectKey(notif);
|
||||
const actor = getActorKey(notif);
|
||||
|
||||
for (const group of grouped) {
|
||||
const base = group.notification;
|
||||
if (base.type !== notif.type) continue;
|
||||
if (getSubjectKey(base) !== subject) continue;
|
||||
|
||||
const baseTs = new Date(base.createdAt).getTime();
|
||||
if (Math.abs(baseTs - ts) >= GROUP_WINDOW_MS) continue;
|
||||
|
||||
// Don't group an actor with themselves (avoids "Alice and Alice").
|
||||
const baseActor = getActorKey(base);
|
||||
const groupActors = new Set(
|
||||
[baseActor, ...group.additional.map(getActorKey)].filter(
|
||||
(a): a is string => typeof a === 'string',
|
||||
),
|
||||
);
|
||||
if (actor && groupActors.has(actor)) continue;
|
||||
|
||||
group.additional.push(notif);
|
||||
group.actorCount += 1;
|
||||
didGroup = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!didGroup) {
|
||||
grouped.push({
|
||||
key: `notif-${notif.id}-${notif.type}`,
|
||||
notification: notif,
|
||||
additional: [],
|
||||
actorCount: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return grouped;
|
||||
}
|
||||
|
||||
export const notificationService = {
|
||||
getNotifications: async (page = 1, limit = 20, unreadOnly = false) => {
|
||||
const response = await api.get('/notifications', {
|
||||
|
||||
158
gitgram/mobile/utils/timeAgo.ts
Normal file
158
gitgram/mobile/utils/timeAgo.ts
Normal file
@ -0,0 +1,158 @@
|
||||
import { differenceInSeconds } from 'date-fns';
|
||||
|
||||
/**
|
||||
* Relative-time ("time ago") helpers, ported from Bluesky's `useTimeAgo`
|
||||
* (src/lib/hooks/useTimeAgo.ts) and adapted to the product's plain-function /
|
||||
* no-i18n-framework conventions.
|
||||
*
|
||||
* The opinionated ruleset is preserved verbatim:
|
||||
* - All months are considered exactly 30 days.
|
||||
* - `earlier` is assumed to be <= `later`; otherwise the result is 'now'.
|
||||
* - Differences under the `NOW` threshold collapse to 'now'.
|
||||
* - All values round down (configurable to round up for future timestamps).
|
||||
* - Differences of >= 12 months fall back to a localized date string.
|
||||
*
|
||||
* Consolidating this here removes the per-screen drift from the ~15 inline
|
||||
* timestamp formatters scattered across the app (PostCard variants,
|
||||
* notifications, reading-list, scheduled posts, messages, story/archive, ...).
|
||||
*/
|
||||
|
||||
export type DateInput = number | string | Date;
|
||||
|
||||
export type DateDiffFormat = 'long' | 'short';
|
||||
|
||||
export type DateDiffUnit = 'now' | 'second' | 'minute' | 'hour' | 'day' | 'month';
|
||||
|
||||
export interface DateDiff {
|
||||
value: number;
|
||||
unit: DateDiffUnit;
|
||||
earlier: Date;
|
||||
later: Date;
|
||||
}
|
||||
|
||||
/** Below this many seconds the difference is reported as "now". */
|
||||
const NOW = 5;
|
||||
const MINUTE = 60;
|
||||
const HOUR = MINUTE * 60;
|
||||
const DAY = HOUR * 24;
|
||||
const MONTH_30 = DAY * 30;
|
||||
|
||||
/**
|
||||
* Returns the difference between `earlier` and `later`, based on the
|
||||
* opinionated rules described in the module header.
|
||||
*/
|
||||
export function dateDiff(
|
||||
earlier: DateInput,
|
||||
later: DateInput,
|
||||
rounding: 'up' | 'down' = 'down',
|
||||
): DateDiff {
|
||||
const e = new Date(earlier);
|
||||
const l = new Date(later);
|
||||
const diffSeconds = differenceInSeconds(l, e);
|
||||
|
||||
const round = (seconds: number, per: number): number =>
|
||||
rounding === 'up' ? Math.ceil(seconds / per) : Math.floor(seconds / per);
|
||||
|
||||
let value = 0;
|
||||
let unit: DateDiffUnit = 'now';
|
||||
|
||||
if (diffSeconds < NOW) {
|
||||
value = 0;
|
||||
unit = 'now';
|
||||
} else if (diffSeconds < MINUTE) {
|
||||
value = diffSeconds;
|
||||
unit = 'second';
|
||||
} else if (diffSeconds < HOUR) {
|
||||
value = round(diffSeconds, MINUTE);
|
||||
unit = 'minute';
|
||||
} else if (diffSeconds < DAY) {
|
||||
value = round(diffSeconds, HOUR);
|
||||
unit = 'hour';
|
||||
} else if (diffSeconds < MONTH_30) {
|
||||
value = round(diffSeconds, DAY);
|
||||
unit = 'day';
|
||||
} else {
|
||||
value = round(diffSeconds, MONTH_30);
|
||||
unit = 'month';
|
||||
}
|
||||
|
||||
return { value, unit, earlier: e, later: l };
|
||||
}
|
||||
|
||||
const NARROW_SUFFIX: Record<Exclude<DateDiffUnit, 'now' | 'month'>, string> = {
|
||||
second: 's',
|
||||
minute: 'm',
|
||||
hour: 'h',
|
||||
day: 'd',
|
||||
};
|
||||
|
||||
const LONG_LABEL: Record<Exclude<DateDiffUnit, 'now' | 'month'>, string> = {
|
||||
second: 'second',
|
||||
minute: 'minute',
|
||||
hour: 'hour',
|
||||
day: 'day',
|
||||
};
|
||||
|
||||
function pluralize(value: number, label: string): string {
|
||||
return `${value} ${label}${value === 1 ? '' : 's'}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a `DateDiff` as a natural-language string.
|
||||
*
|
||||
* - `short` (default): narrow form, e.g. `5m`, `3h`, `2d`, `4mo`, `now`.
|
||||
* - `long`: spelled out, e.g. `5 minutes`, `1 hour`, `now`.
|
||||
* - Differences >= 12 months render as a localized date string.
|
||||
*/
|
||||
export function formatDateDiff(
|
||||
diff: DateDiff,
|
||||
format: DateDiffFormat = 'short',
|
||||
): string {
|
||||
const long = format === 'long';
|
||||
|
||||
switch (diff.unit) {
|
||||
case 'now':
|
||||
return 'now';
|
||||
case 'second':
|
||||
case 'minute':
|
||||
case 'hour':
|
||||
case 'day':
|
||||
return long
|
||||
? pluralize(diff.value, LONG_LABEL[diff.unit])
|
||||
: `${diff.value}${NARROW_SUFFIX[diff.unit]}`;
|
||||
case 'month':
|
||||
if (diff.value < 12) {
|
||||
return long ? pluralize(diff.value, 'month') : `${diff.value}mo`;
|
||||
}
|
||||
return diff.earlier.toLocaleDateString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience helper: difference between `earlier` and now (or an explicit
|
||||
* `later`), formatted in one call. This is the function most screens want.
|
||||
*
|
||||
* @example timeAgo(post.createdAt) // "5m"
|
||||
* @example timeAgo(post.createdAt, { format: 'long' }) // "5 minutes"
|
||||
*/
|
||||
export function timeAgo(
|
||||
earlier: DateInput,
|
||||
options?: { later?: DateInput; format?: DateDiffFormat },
|
||||
): string {
|
||||
const later = options?.later ?? Date.now();
|
||||
return formatDateDiff(dateDiff(earlier, later, 'down'), options?.format);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant for future timestamps (e.g. scheduled posts): rounds up and measures
|
||||
* from now to the (later) target.
|
||||
*
|
||||
* @example timeUntil(scheduledFor) // "3d"
|
||||
*/
|
||||
export function timeUntil(
|
||||
later: DateInput,
|
||||
options?: { earlier?: DateInput; format?: DateDiffFormat },
|
||||
): string {
|
||||
const earlier = options?.earlier ?? Date.now();
|
||||
return formatDateDiff(dateDiff(earlier, later, 'up'), options?.format);
|
||||
}
|
||||
91
gitgram/web/components/EmbedPlayer.tsx
Normal file
91
gitgram/web/components/EmbedPlayer.tsx
Normal file
@ -0,0 +1,91 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
EMBED_PLAYER_LABELS,
|
||||
getEmbedPlayerAspect,
|
||||
type EmbedPlayerParams,
|
||||
} from '@/utils/embedPlayer'
|
||||
|
||||
interface EmbedPlayerProps {
|
||||
params: EmbedPlayerParams
|
||||
/** Original URL, used for the "open externally" affordance and alt text. */
|
||||
url: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders an inline media player for a recognised provider (YouTube, Twitch,
|
||||
* Spotify, Vimeo, SoundCloud, Apple Music, Giphy).
|
||||
*
|
||||
* To avoid auto-loading third-party iframes (and the privacy / performance
|
||||
* cost that entails), non-GIF embeds start as a click-to-load facade showing
|
||||
* the provider name. Only after the user opts in do we mount the iframe.
|
||||
* GIFs render directly as images since they carry no autoplay-with-audio cost.
|
||||
*/
|
||||
export default function EmbedPlayer({ params, url, className = '' }: EmbedPlayerProps) {
|
||||
const [activated, setActivated] = useState(false)
|
||||
const aspect = getEmbedPlayerAspect(params.type)
|
||||
const label = EMBED_PLAYER_LABELS[params.source]
|
||||
|
||||
const frameStyle: React.CSSProperties = aspect.aspectRatio
|
||||
? { aspectRatio: String(aspect.aspectRatio) }
|
||||
: { height: aspect.height }
|
||||
|
||||
// GIFs: render as a plain image, no iframe, no facade.
|
||||
if (params.isGif) {
|
||||
return (
|
||||
<div
|
||||
className={`overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--surface)] ${className}`}
|
||||
style={frameStyle}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={params.playerUri}
|
||||
alt={`${label} GIF`}
|
||||
loading="lazy"
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!activated) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setActivated(true)}
|
||||
aria-label={`Load ${label} player`}
|
||||
className={`group relative flex w-full items-center justify-center overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--surface)] transition-colors hover:border-[var(--primary)] ${className}`}
|
||||
style={frameStyle}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-2 text-[var(--foreground-secondary)] group-hover:text-[var(--foreground)]">
|
||||
<span className="flex h-12 w-12 items-center justify-center rounded-full bg-[var(--surface-secondary)] transition-colors group-hover:bg-[var(--primary)]/15">
|
||||
<svg className="h-6 w-6 text-[var(--primary)]" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</span>
|
||||
<span className="text-sm font-medium">Play on {label}</span>
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`overflow-hidden rounded-xl border border-[var(--border)] bg-black ${className}`}
|
||||
style={frameStyle}
|
||||
>
|
||||
<iframe
|
||||
src={params.playerUri}
|
||||
title={`${label} player`}
|
||||
className="h-full w-full"
|
||||
allow="autoplay; encrypted-media; fullscreen; picture-in-picture; clipboard-write"
|
||||
allowFullScreen
|
||||
loading="lazy"
|
||||
referrerPolicy="strict-origin-when-cross-origin"
|
||||
sandbox="allow-scripts allow-same-origin allow-presentation allow-popups"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -13,6 +13,9 @@ import ContentHider from './moderation/ContentHider';
|
||||
import { useModeration } from '@/hooks/useModeration';
|
||||
import { isPostMuted, parseSelfLabel } from '@/utils/moderation';
|
||||
import { realtimeService } from '@/services/realtimeService';
|
||||
import { useFeedFeedback } from '@/hooks/useFeedFeedback';
|
||||
import PostFeedbackMenu from './PostFeedbackMenu';
|
||||
import SeenTracker from './SeenTracker';
|
||||
import api from '@/services/api';
|
||||
|
||||
interface Post {
|
||||
@ -87,6 +90,7 @@ export default function Feed() {
|
||||
const queryClient = useQueryClient();
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
const moderation = useModeration();
|
||||
const feedback = useFeedFeedback();
|
||||
|
||||
// ── Infinite feed query ────────────────────────────────────────────────────
|
||||
const {
|
||||
@ -106,9 +110,11 @@ export default function Feed() {
|
||||
const allPosts = data?.pages.flatMap((p) => p.posts) ?? [];
|
||||
const isDiscover = data?.pages[0]?.isDiscover;
|
||||
|
||||
// Apply client-side moderation (muted words / accounts / threads).
|
||||
// Apply client-side moderation (muted words / accounts / threads) and hide
|
||||
// posts the viewer marked "not interested".
|
||||
const posts = allPosts.filter(
|
||||
(post) =>
|
||||
!feedback.isHidden(post.id) &&
|
||||
!isPostMuted(
|
||||
{ id: post.id, content: post.content ?? '', username: post.account.username },
|
||||
moderation,
|
||||
@ -320,8 +326,8 @@ export default function Feed() {
|
||||
const { label: selfLabel, cleanContent: labelledContent } = parseSelfLabel(post.content || '');
|
||||
const { story, cleanContent } = parseAitmChangeStoryBlock(labelledContent);
|
||||
return (
|
||||
<SeenTracker key={post.id} onSeen={() => feedback.markSeen(post.id)}>
|
||||
<article
|
||||
key={post.id}
|
||||
className="bg-white dark:bg-gray-800 rounded-lg p-6 border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 transition"
|
||||
>
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
@ -330,7 +336,7 @@ export default function Feed() {
|
||||
{post.account.username[0].toUpperCase()}
|
||||
</div>
|
||||
</Link>
|
||||
<div className="flex-1">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href={`/${post.account.username}`} className="font-medium hover:underline">
|
||||
@{post.account.username}
|
||||
@ -343,6 +349,10 @@ export default function Feed() {
|
||||
{new Date(post.createdAt).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
<PostFeedbackMenu
|
||||
onNotInterested={() => feedback.requestLess(post.id)}
|
||||
onShowMore={() => feedback.requestMore(post.id)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="text-gray-800 dark:text-gray-200 mb-4">
|
||||
@ -377,6 +387,7 @@ export default function Feed() {
|
||||
<BookmarkButton postId={post.id} initialSaved={false} className="ml-auto" />
|
||||
</div>
|
||||
</article>
|
||||
</SeenTracker>
|
||||
);
|
||||
})}
|
||||
|
||||
|
||||
132
gitgram/web/components/LinkCard.tsx
Normal file
132
gitgram/web/components/LinkCard.tsx
Normal file
@ -0,0 +1,132 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { linkPreviewService, type LinkPreview } from '@/services/linkPreviewService'
|
||||
|
||||
interface LinkCardProps {
|
||||
url: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
function getDomain(url: string): string {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, '')
|
||||
} catch {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a rich preview card (title / description / image / domain) for an
|
||||
* external URL by fetching unfurl metadata from the backend `/v1/link-preview`
|
||||
* proxy. Shows a skeleton while loading and silently falls back to a plain
|
||||
* clickable link if no preview is available.
|
||||
*/
|
||||
export default function LinkCard({ url, className = '' }: LinkCardProps) {
|
||||
const [preview, setPreview] = useState<LinkPreview | null>(null)
|
||||
const [status, setStatus] = useState<'loading' | 'loaded' | 'failed'>('loading')
|
||||
const [imageBroken, setImageBroken] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setStatus('loading')
|
||||
setImageBroken(false)
|
||||
|
||||
linkPreviewService
|
||||
.getPreview(url)
|
||||
.then((result) => {
|
||||
if (cancelled) return
|
||||
if (result && (result.title || result.description || result.image)) {
|
||||
setPreview(result)
|
||||
setStatus('loaded')
|
||||
} else {
|
||||
setStatus('failed')
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setStatus('failed')
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [url])
|
||||
|
||||
const domain = getDomain(url)
|
||||
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
<div
|
||||
className={`flex animate-pulse overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--surface)] ${className}`}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<div className="h-24 w-24 shrink-0 bg-[var(--surface-secondary)]" />
|
||||
<div className="flex flex-1 flex-col justify-center gap-2 p-3">
|
||||
<div className="h-3 w-1/3 rounded bg-[var(--surface-secondary)]" />
|
||||
<div className="h-3 w-3/4 rounded bg-[var(--surface-secondary)]" />
|
||||
<div className="h-3 w-2/3 rounded bg-[var(--surface-secondary)]" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// No metadata available — degrade to a plain, safe external link.
|
||||
if (status === 'failed' || !preview) {
|
||||
return (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow ugc"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={`inline-flex max-w-full items-center gap-1.5 truncate text-sm text-[var(--primary)] hover:underline ${className}`}
|
||||
>
|
||||
<svg className="h-3.5 w-3.5 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M13.828 10.172a4 4 0 010 5.656l-3 3a4 4 0 11-5.656-5.656l1.5-1.5m6.656-1.328a4 4 0 010-5.656l3-3a4 4 0 115.656 5.656l-1.5 1.5" />
|
||||
</svg>
|
||||
<span className="truncate">{url}</span>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
const showImage = Boolean(preview.image) && !imageBroken
|
||||
|
||||
return (
|
||||
<a
|
||||
href={preview.url || url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow ugc"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={`group flex overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--surface)] transition-colors hover:border-[var(--primary)] ${className}`}
|
||||
>
|
||||
{showImage && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={preview.image as string}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
onError={() => setImageBroken(true)}
|
||||
className="h-auto w-28 shrink-0 self-stretch object-cover sm:w-36"
|
||||
/>
|
||||
)}
|
||||
<div className="flex min-w-0 flex-1 flex-col justify-center gap-1 p-3">
|
||||
<span className="flex items-center gap-1.5 text-xs text-[var(--foreground-secondary)]">
|
||||
{preview.favicon && !imageBroken && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={preview.favicon} alt="" className="h-3.5 w-3.5 rounded-sm" loading="lazy" />
|
||||
)}
|
||||
<span className="truncate">{preview.siteName || domain}</span>
|
||||
</span>
|
||||
{preview.title && (
|
||||
<span className="line-clamp-2 text-sm font-semibold text-[var(--foreground)] group-hover:text-[var(--primary)]">
|
||||
{preview.title}
|
||||
</span>
|
||||
)}
|
||||
{preview.description && (
|
||||
<span className="line-clamp-2 text-xs text-[var(--foreground-secondary)]">
|
||||
{preview.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
@ -4,6 +4,7 @@ import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { linkifyText } from '@/utils/linkify'
|
||||
import ImageCarousel from './ImageCarousel'
|
||||
import RichEmbeds from './RichEmbeds'
|
||||
import ContentHider from './moderation/ContentHider'
|
||||
import { parseSelfLabel } from '@/utils/moderation'
|
||||
|
||||
@ -322,6 +323,7 @@ export default function PostCard({ post, onLike }: PostCardProps) {
|
||||
<ContentHider label={selfLabel}>
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<RenderedContent content={cleanContent} />
|
||||
<RichEmbeds content={cleanContent} />
|
||||
</div>
|
||||
|
||||
{post.images && post.images.length > 0 && (
|
||||
|
||||
120
gitgram/web/components/PostFeedbackMenu.tsx
Normal file
120
gitgram/web/components/PostFeedbackMenu.tsx
Normal file
@ -0,0 +1,120 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
interface PostFeedbackMenuProps {
|
||||
/** "Not interested" — hide and send a negative ranking signal. */
|
||||
onNotInterested: () => void
|
||||
/** "Show more like this" — positive ranking signal. */
|
||||
onShowMore: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-post overflow ("...") menu exposing negative/positive feed-feedback
|
||||
* actions ("Not interested" / "Show more like this"). Adapted from Bluesky's
|
||||
* requestLess/requestMore affordance into a self-contained dropdown matching
|
||||
* this product's ShareMenu pattern (outside-click + Escape to close).
|
||||
*/
|
||||
export function PostFeedbackMenu({
|
||||
onNotInterested,
|
||||
onShowMore,
|
||||
className = '',
|
||||
}: PostFeedbackMenuProps) {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
const buttonRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
const handleOutside = (event: MouseEvent) => {
|
||||
const target = event.target as Node
|
||||
if (
|
||||
menuRef.current &&
|
||||
!menuRef.current.contains(target) &&
|
||||
buttonRef.current &&
|
||||
!buttonRef.current.contains(target)
|
||||
) {
|
||||
setIsOpen(false)
|
||||
}
|
||||
}
|
||||
const handleKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') setIsOpen(false)
|
||||
}
|
||||
document.addEventListener('mousedown', handleOutside)
|
||||
document.addEventListener('keydown', handleKey)
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleOutside)
|
||||
document.removeEventListener('keydown', handleKey)
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
const handleSelect = (action: () => void) => {
|
||||
setIsOpen(false)
|
||||
action()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`relative inline-block ${className}`}>
|
||||
<button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setIsOpen((prev) => !prev)
|
||||
}}
|
||||
aria-label="Post options"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={isOpen}
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full text-[var(--foreground-secondary)] transition-colors hover:bg-[var(--surface-secondary)] hover:text-[var(--foreground)]"
|
||||
>
|
||||
<svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<circle cx="5" cy="12" r="2" />
|
||||
<circle cx="12" cy="12" r="2" />
|
||||
<circle cx="19" cy="12" r="2" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div
|
||||
ref={menuRef}
|
||||
role="menu"
|
||||
aria-label="Feed feedback"
|
||||
className="absolute right-0 top-full z-50 mt-1.5 w-56 overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--surface)] shadow-xl"
|
||||
>
|
||||
<button
|
||||
role="menuitem"
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleSelect(onNotInterested)
|
||||
}}
|
||||
className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-sm text-[var(--foreground-secondary)] transition-colors hover:bg-[var(--surface-secondary)] hover:text-[var(--foreground)]"
|
||||
>
|
||||
<svg className="h-4 w-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path strokeLinecap="round" d="M5.6 5.6l12.8 12.8" />
|
||||
</svg>
|
||||
Not interested
|
||||
</button>
|
||||
<button
|
||||
role="menuitem"
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleSelect(onShowMore)
|
||||
}}
|
||||
className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-sm text-[var(--foreground-secondary)] transition-colors hover:bg-[var(--surface-secondary)] hover:text-[var(--foreground)]"
|
||||
>
|
||||
<svg className="h-4 w-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M14 9V5a3 3 0 00-3-3l-4 9v11h11.28a2 2 0 002-1.7l1.38-9a2 2 0 00-2-2.3zM7 22H4a2 2 0 01-2-2v-7a2 2 0 012-2h3" />
|
||||
</svg>
|
||||
Show more like this
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PostFeedbackMenu
|
||||
@ -4,23 +4,34 @@ import { useMemo } from 'react';
|
||||
import { parseCodeContent, ContentSegment, hasCode } from '@/utils/codeParser';
|
||||
import { linkifyText } from '@/utils/linkify';
|
||||
import CodeBlock, { InlineCode } from './CodeBlock';
|
||||
import RichEmbeds from './RichEmbeds';
|
||||
|
||||
interface RichContentProps {
|
||||
content: string;
|
||||
className?: string;
|
||||
/**
|
||||
* When true (default), external URLs in the content are rendered as inline
|
||||
* media players (YouTube/Spotify/etc.) or link-preview cards below the text.
|
||||
* Set false in compact contexts (e.g. comment previews) where embeds would
|
||||
* be visually heavy.
|
||||
*/
|
||||
embeds?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders text content with syntax-highlighted code blocks and inline code
|
||||
* Renders text content with syntax-highlighted code blocks, inline code, and
|
||||
* (optionally) rich embeds — inline media players and link-preview cards — for
|
||||
* any external URLs detected in the text.
|
||||
*/
|
||||
export default function RichContent({ content, className = '' }: RichContentProps) {
|
||||
export default function RichContent({ content, className = '', embeds = true }: RichContentProps) {
|
||||
const segments = useMemo(() => parseCodeContent(content), [content]);
|
||||
|
||||
// If no code, just render linkified plain text for better performance
|
||||
if (!hasCode(content)) {
|
||||
return (
|
||||
<div className={`whitespace-pre-wrap ${className}`}>
|
||||
{linkifyText(content)}
|
||||
<div className={className}>
|
||||
<div className="whitespace-pre-wrap">{linkifyText(content)}</div>
|
||||
{embeds && <RichEmbeds content={content} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -30,6 +41,7 @@ export default function RichContent({ content, className = '' }: RichContentProp
|
||||
{segments.map((segment, index) => (
|
||||
<RenderSegment key={index} segment={segment} />
|
||||
))}
|
||||
{embeds && <RichEmbeds content={content} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
43
gitgram/web/components/RichEmbeds.tsx
Normal file
43
gitgram/web/components/RichEmbeds.tsx
Normal file
@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { extractUrls } from '@/utils/extractUrls'
|
||||
import { getEmbedPlayerSource } from '@/utils/embedPlayer'
|
||||
import EmbedPlayer from './EmbedPlayer'
|
||||
import LinkCard from './LinkCard'
|
||||
|
||||
interface RichEmbedsProps {
|
||||
/** Raw post content to scan for embeddable / unfurlable URLs. */
|
||||
content: string
|
||||
/** Maximum number of embeds to render below the text (default 2). */
|
||||
max?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans post content for external URLs and renders, for each:
|
||||
* - an inline media player (YouTube/Twitch/Spotify/Vimeo/SoundCloud/Apple
|
||||
* Music/Giphy) when the URL maps to a known provider, or
|
||||
* - a link-preview / unfurl card (title, description, image, domain) for any
|
||||
* other external URL.
|
||||
*
|
||||
* Renders nothing when the content has no external URLs, so it is safe to mount
|
||||
* unconditionally after any post body.
|
||||
*/
|
||||
export default function RichEmbeds({ content, max = 2, className = '' }: RichEmbedsProps) {
|
||||
const urls = useMemo(() => extractUrls(content, { limit: max }), [content, max])
|
||||
|
||||
if (urls.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className={`mt-3 flex flex-col gap-3 ${className}`}>
|
||||
{urls.map((url) => {
|
||||
const player = getEmbedPlayerSource(url)
|
||||
if (player) {
|
||||
return <EmbedPlayer key={url} params={player} url={url} />
|
||||
}
|
||||
return <LinkCard key={url} url={url} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
50
gitgram/web/components/SeenTracker.tsx
Normal file
50
gitgram/web/components/SeenTracker.tsx
Normal file
@ -0,0 +1,50 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
interface SeenTrackerProps {
|
||||
/** Called once when the element has been sufficiently visible. */
|
||||
onSeen: () => void
|
||||
children: React.ReactNode
|
||||
className?: string
|
||||
/** Fraction of the element that must be visible to count as seen (0-1). */
|
||||
threshold?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps feed content and fires `onSeen` once when it scrolls into view, using
|
||||
* an IntersectionObserver. Used to emit the "seen" feed-feedback signal so the
|
||||
* ranker can learn which posts the viewer actually looked at.
|
||||
*/
|
||||
export function SeenTracker({ onSeen, children, className, threshold = 0.5 }: SeenTrackerProps) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const firedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current
|
||||
if (!el || firedRef.current) return
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting && !firedRef.current) {
|
||||
firedRef.current = true
|
||||
onSeen()
|
||||
observer.disconnect()
|
||||
}
|
||||
}
|
||||
},
|
||||
{ threshold },
|
||||
)
|
||||
observer.observe(el)
|
||||
return () => observer.disconnect()
|
||||
}, [onSeen, threshold])
|
||||
|
||||
return (
|
||||
<div ref={ref} className={className}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SeenTracker
|
||||
@ -3,6 +3,7 @@
|
||||
import { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import { UserHoverCard } from './UserHoverCard';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@ -142,20 +143,22 @@ export function UserCard({ user, variant = 'full', onFollowChange }: UserCardPro
|
||||
<div className="rounded-xl border border-[var(--border)] bg-[var(--surface)] p-4 flex flex-col gap-3">
|
||||
{/* Header row */}
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<Link
|
||||
href={`/profile/${user.username}`}
|
||||
className="flex items-center gap-3 group min-w-0"
|
||||
>
|
||||
<Avatar user={user} size="lg" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold text-[var(--foreground)] truncate group-hover:text-[var(--primary)] transition-colors">
|
||||
{user.displayName ?? user.username}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--foreground-secondary)] truncate">
|
||||
@{user.username}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
<UserHoverCard username={user.username}>
|
||||
<Link
|
||||
href={`/profile/${user.username}`}
|
||||
className="flex items-center gap-3 group min-w-0"
|
||||
>
|
||||
<Avatar user={user} size="lg" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-semibold text-[var(--foreground)] truncate group-hover:text-[var(--primary)] transition-colors">
|
||||
{user.displayName ?? user.username}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--foreground-secondary)] truncate">
|
||||
@{user.username}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
</UserHoverCard>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
|
||||
172
gitgram/web/components/UserHoverCard.tsx
Normal file
172
gitgram/web/components/UserHoverCard.tsx
Normal file
@ -0,0 +1,172 @@
|
||||
'use client'
|
||||
|
||||
import { type ReactElement } from 'react'
|
||||
import Link from 'next/link'
|
||||
import Image from 'next/image'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { userService } from '@/services/userService'
|
||||
import { useAuthStore } from '@/store/authStore'
|
||||
import { Tooltip } from './ui/tooltip'
|
||||
import { FollowButton } from './FollowButton'
|
||||
|
||||
interface HoverProfile {
|
||||
id: string
|
||||
username: string
|
||||
displayName?: string
|
||||
bio?: string
|
||||
avatar?: string
|
||||
followersCount: number
|
||||
followingCount: number
|
||||
isFollowing: boolean
|
||||
githubUsername?: string
|
||||
}
|
||||
|
||||
function normalize(raw: unknown): HoverProfile {
|
||||
const r = (raw ?? {}) as Record<string, unknown>
|
||||
return {
|
||||
id: String(r.id ?? ''),
|
||||
username: String(r.username ?? ''),
|
||||
displayName: (r.displayName as string) ?? (r.fullName as string) ?? undefined,
|
||||
bio: r.bio ? String(r.bio) : undefined,
|
||||
avatar: (r.avatar as string) ?? (r.avatarUrl as string) ?? undefined,
|
||||
followersCount: typeof r.followersCount === 'number' ? r.followersCount : 0,
|
||||
followingCount: typeof r.followingCount === 'number' ? r.followingCount : 0,
|
||||
isFollowing: Boolean(r.isFollowing),
|
||||
githubUsername: r.githubUsername ? String(r.githubUsername) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function formatCount(count: number): string {
|
||||
if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`
|
||||
if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`
|
||||
return String(count)
|
||||
}
|
||||
|
||||
interface UserHoverCardProps {
|
||||
/** Username to preview. The card lazily fetches the full profile on hover. */
|
||||
username: string
|
||||
/** Trigger element (a link, avatar, etc.). */
|
||||
children: ReactElement
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a trigger element with a profile-preview hover card showing the user's
|
||||
* avatar, display name, bio, follower/following counts, and a follow button.
|
||||
*
|
||||
* Adapted from the source UserTooltip/UserLinkWithTooltip pair onto the
|
||||
* gitgram-web stack: data comes from `userService.getProfile` via React Query
|
||||
* (fetched lazily once on first hover and cached), the popover uses this
|
||||
* product's `ui/tooltip` primitive, and follow state reuses the existing
|
||||
* `FollowButton`.
|
||||
*/
|
||||
export function UserHoverCard({ username, children }: UserHoverCardProps) {
|
||||
const { user: currentUser } = useAuthStore()
|
||||
|
||||
const { data, status } = useQuery({
|
||||
queryKey: ['hover-profile', username],
|
||||
queryFn: async () => normalize(await userService.getProfile(username)),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
enabled: Boolean(username),
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const isSelf = Boolean(currentUser?.username && currentUser.username === username)
|
||||
|
||||
const card = (
|
||||
<span className="block w-72 rounded-xl border border-[var(--border)] bg-[var(--surface)] p-4 shadow-xl">
|
||||
{status === 'pending' && (
|
||||
<span className="flex animate-pulse flex-col gap-3" aria-hidden="true">
|
||||
<span className="flex items-center justify-between">
|
||||
<span className="h-14 w-14 rounded-full bg-[var(--surface-secondary)]" />
|
||||
</span>
|
||||
<span className="h-3 w-1/2 rounded bg-[var(--surface-secondary)]" />
|
||||
<span className="h-3 w-3/4 rounded bg-[var(--surface-secondary)]" />
|
||||
</span>
|
||||
)}
|
||||
|
||||
{status === 'error' && (
|
||||
<span className="block text-sm text-[var(--foreground-secondary)]">
|
||||
Couldn't load @{username}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{status === 'success' && data && (
|
||||
<span className="flex flex-col gap-3">
|
||||
<span className="flex items-start justify-between gap-2">
|
||||
<Link
|
||||
href={`/${data.username}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
aria-label={`View @${data.username}`}
|
||||
>
|
||||
{data.avatar ? (
|
||||
<Image
|
||||
src={data.avatar}
|
||||
alt={data.username}
|
||||
width={56}
|
||||
height={56}
|
||||
unoptimized
|
||||
className="h-14 w-14 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="flex h-14 w-14 items-center justify-center rounded-full bg-gradient-to-br from-[var(--primary)]/60 to-purple-600/60 text-lg font-semibold text-white">
|
||||
{data.username.slice(0, 2).toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
|
||||
{!isSelf && data.id && (
|
||||
<FollowButton
|
||||
userId={data.id}
|
||||
username={data.username}
|
||||
initialFollowing={data.isFollowing}
|
||||
githubUsername={data.githubUsername}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
|
||||
<Link
|
||||
href={`/${data.username}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="block min-w-0"
|
||||
>
|
||||
<span className="block truncate text-base font-semibold text-[var(--foreground)] hover:underline">
|
||||
{data.displayName ?? data.username}
|
||||
</span>
|
||||
<span className="block truncate text-sm text-[var(--foreground-secondary)]">
|
||||
@{data.username}
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
{data.bio && (
|
||||
<span className="block whitespace-pre-line text-sm text-[var(--foreground)] [overflow-wrap:anywhere] line-clamp-4">
|
||||
{data.bio}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<span className="flex items-center gap-4 text-sm text-[var(--foreground-secondary)]">
|
||||
<span>
|
||||
<span className="font-semibold text-[var(--foreground)]">
|
||||
{formatCount(data.followingCount)}
|
||||
</span>{' '}
|
||||
Following
|
||||
</span>
|
||||
<span>
|
||||
<span className="font-semibold text-[var(--foreground)]">
|
||||
{formatCount(data.followersCount)}
|
||||
</span>{' '}
|
||||
Followers
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
|
||||
return (
|
||||
<Tooltip content={card} openDelay={350}>
|
||||
{children}
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
export default UserHoverCard
|
||||
125
gitgram/web/components/ui/tooltip.tsx
Normal file
125
gitgram/web/components/ui/tooltip.tsx
Normal file
@ -0,0 +1,125 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
cloneElement,
|
||||
isValidElement,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
|
||||
interface TooltipProps {
|
||||
/** The element that triggers the tooltip on hover / focus. */
|
||||
children: ReactElement
|
||||
/** Floating content rendered in the popover. */
|
||||
content: ReactNode
|
||||
/** Delay before showing, in ms (default 400). */
|
||||
openDelay?: number
|
||||
/** Delay before hiding, in ms (default 150) — lets the pointer cross the gap. */
|
||||
closeDelay?: number
|
||||
/** Disable the tooltip entirely (renders only the trigger). */
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight, dependency-free hover/focus tooltip primitive.
|
||||
*
|
||||
* Adapted from the Radix-based `ui/tooltip` used by the source
|
||||
* nextjs-15-social-media-app, reimplemented with plain React so it matches the
|
||||
* gitgram-web convention of hand-rolled `components/ui` primitives (no Radix
|
||||
* dependency in the product). Supports keyboard focus, pointer hover with an
|
||||
* intent delay, and stays open while the pointer is over the content so it can
|
||||
* host interactive controls (e.g. a follow button).
|
||||
*/
|
||||
export function Tooltip({
|
||||
children,
|
||||
content,
|
||||
openDelay = 400,
|
||||
closeDelay = 150,
|
||||
disabled = false,
|
||||
className = '',
|
||||
}: TooltipProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const tooltipId = useId()
|
||||
const showTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
const clearTimers = () => {
|
||||
if (showTimer.current) clearTimeout(showTimer.current)
|
||||
if (hideTimer.current) clearTimeout(hideTimer.current)
|
||||
}
|
||||
|
||||
useEffect(() => clearTimers, [])
|
||||
|
||||
const scheduleOpen = () => {
|
||||
if (disabled) return
|
||||
clearTimers()
|
||||
showTimer.current = setTimeout(() => setOpen(true), openDelay)
|
||||
}
|
||||
|
||||
const scheduleClose = () => {
|
||||
clearTimers()
|
||||
hideTimer.current = setTimeout(() => setOpen(false), closeDelay)
|
||||
}
|
||||
|
||||
if (!isValidElement(children)) {
|
||||
throw new Error('Tooltip expects a single React element child')
|
||||
}
|
||||
|
||||
const triggerProps = children.props as Record<string, unknown> & {
|
||||
onMouseEnter?: (e: unknown) => void
|
||||
onMouseLeave?: (e: unknown) => void
|
||||
onFocus?: (e: unknown) => void
|
||||
onBlur?: (e: unknown) => void
|
||||
}
|
||||
|
||||
const trigger = cloneElement(children, {
|
||||
'aria-describedby': open ? tooltipId : undefined,
|
||||
onMouseEnter: (e: unknown) => {
|
||||
triggerProps.onMouseEnter?.(e)
|
||||
scheduleOpen()
|
||||
},
|
||||
onMouseLeave: (e: unknown) => {
|
||||
triggerProps.onMouseLeave?.(e)
|
||||
scheduleClose()
|
||||
},
|
||||
onFocus: (e: unknown) => {
|
||||
triggerProps.onFocus?.(e)
|
||||
if (!disabled) {
|
||||
clearTimers()
|
||||
setOpen(true)
|
||||
}
|
||||
},
|
||||
onBlur: (e: unknown) => {
|
||||
triggerProps.onBlur?.(e)
|
||||
scheduleClose()
|
||||
},
|
||||
} as Partial<typeof triggerProps>)
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`relative inline-flex ${className}`}
|
||||
onMouseEnter={() => !disabled && clearTimers()}
|
||||
onMouseLeave={scheduleClose}
|
||||
>
|
||||
{trigger}
|
||||
{open && !disabled && (
|
||||
<span
|
||||
role="tooltip"
|
||||
id={tooltipId}
|
||||
className="absolute left-1/2 top-full z-50 mt-2 -translate-x-1/2"
|
||||
onMouseEnter={clearTimers}
|
||||
onMouseLeave={scheduleClose}
|
||||
>
|
||||
{content}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export default Tooltip
|
||||
150
gitgram/web/hooks/useFeedFeedback.ts
Normal file
150
gitgram/web/hooks/useFeedFeedback.ts
Normal file
@ -0,0 +1,150 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
postService,
|
||||
type FeedSignal,
|
||||
type FeedSignalEvent,
|
||||
} from '@/services/postService'
|
||||
|
||||
const FLUSH_INTERVAL_MS = 10_000
|
||||
const HISTORY_STORAGE_KEY = 'gitgram:feed-feedback:hidden'
|
||||
const MAX_HISTORY = 200
|
||||
|
||||
/**
|
||||
* Loads the locally-persisted set of "not interested" post ids.
|
||||
*
|
||||
* Persisting client-side means the negative signal is honoured immediately on
|
||||
* the next render (and across reloads) even before/without the backend ranker
|
||||
* acting on it — mirroring Bluesky's userActionHistory recency tracking, scoped
|
||||
* here to the hide-from-feed use case.
|
||||
*/
|
||||
function loadHidden(): Set<string> {
|
||||
if (typeof window === 'undefined') return new Set()
|
||||
try {
|
||||
const raw = window.localStorage.getItem(HISTORY_STORAGE_KEY)
|
||||
if (!raw) return new Set()
|
||||
const parsed: unknown = JSON.parse(raw)
|
||||
if (Array.isArray(parsed)) {
|
||||
return new Set(parsed.filter((v): v is string => typeof v === 'string'))
|
||||
}
|
||||
} catch {
|
||||
// Corrupt storage — start fresh.
|
||||
}
|
||||
return new Set()
|
||||
}
|
||||
|
||||
function persistHidden(ids: Set<string>): void {
|
||||
if (typeof window === 'undefined') return
|
||||
try {
|
||||
// Keep only the most recent N to bound storage growth.
|
||||
const trimmed = Array.from(ids).slice(-MAX_HISTORY)
|
||||
window.localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(trimmed))
|
||||
} catch {
|
||||
// Storage full / unavailable — non-fatal.
|
||||
}
|
||||
}
|
||||
|
||||
export interface UseFeedFeedback {
|
||||
/** Set of post ids the viewer marked "not interested" — hide these. */
|
||||
hiddenIds: Set<string>
|
||||
/** True if the given post has been hidden via "not interested". */
|
||||
isHidden: (postId: string) => boolean
|
||||
/** Mark a post seen (deduped per session; queued + batched). */
|
||||
markSeen: (postId: string, feedContext?: string) => void
|
||||
/** "Show more like this" — positive ranking signal. */
|
||||
requestMore: (postId: string, feedContext?: string) => void
|
||||
/** "Not interested / show less" — hides locally and sends a negative signal. */
|
||||
requestLess: (postId: string, feedContext?: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Feed-feedback controller, ported from Bluesky's `feed-feedback.tsx` and
|
||||
* `userActionHistory.ts` onto the gitgram-web stack.
|
||||
*
|
||||
* - De-duplicates and batches signals, flushing on an interval, on unmount, and
|
||||
* when the tab is hidden.
|
||||
* - Persists "not interested" posts locally so they vanish from the feed
|
||||
* immediately and stay hidden across reloads.
|
||||
* - All network writes are best-effort: failures never surface to the user.
|
||||
*
|
||||
* @param enabled Disable on non-personalised feeds (e.g. a profile grid).
|
||||
*/
|
||||
export function useFeedFeedback(enabled = true): UseFeedFeedback {
|
||||
const [hiddenIds, setHiddenIds] = useState<Set<string>>(() => loadHidden())
|
||||
|
||||
const queue = useRef<Map<string, FeedSignalEvent>>(new Map())
|
||||
const seenHistory = useRef<Set<string>>(new Set())
|
||||
|
||||
const flush = useCallback(() => {
|
||||
if (queue.current.size === 0) return
|
||||
const events = Array.from(queue.current.values())
|
||||
queue.current.clear()
|
||||
// Best-effort: drop on failure, do not retry or surface.
|
||||
void postService.sendFeedSignal(events).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const enqueue = useCallback(
|
||||
(postId: string, signal: FeedSignal, feedContext?: string) => {
|
||||
if (!enabled || !postId) return
|
||||
// Key dedupes repeated identical signals for the same post.
|
||||
queue.current.set(`${postId}:${signal}`, { postId, signal, feedContext })
|
||||
},
|
||||
[enabled],
|
||||
)
|
||||
|
||||
const markSeen = useCallback(
|
||||
(postId: string, feedContext?: string) => {
|
||||
if (!enabled || !postId || seenHistory.current.has(postId)) return
|
||||
seenHistory.current.add(postId)
|
||||
enqueue(postId, 'seen', feedContext)
|
||||
},
|
||||
[enabled, enqueue],
|
||||
)
|
||||
|
||||
const requestMore = useCallback(
|
||||
(postId: string, feedContext?: string) => {
|
||||
enqueue(postId, 'requestMore', feedContext)
|
||||
flush()
|
||||
},
|
||||
[enqueue, flush],
|
||||
)
|
||||
|
||||
const requestLess = useCallback(
|
||||
(postId: string, feedContext?: string) => {
|
||||
if (!postId) return
|
||||
setHiddenIds((prev) => {
|
||||
if (prev.has(postId)) return prev
|
||||
const next = new Set(prev)
|
||||
next.add(postId)
|
||||
persistHidden(next)
|
||||
return next
|
||||
})
|
||||
enqueue(postId, 'requestLess', feedContext)
|
||||
flush()
|
||||
},
|
||||
[enqueue, flush],
|
||||
)
|
||||
|
||||
const isHidden = useCallback((postId: string) => hiddenIds.has(postId), [hiddenIds])
|
||||
|
||||
// Periodic flush + flush on tab-hide and unmount so queued "seen" signals
|
||||
// are not lost.
|
||||
useEffect(() => {
|
||||
if (!enabled) return
|
||||
const interval = setInterval(flush, FLUSH_INTERVAL_MS)
|
||||
|
||||
const onVisibility = () => {
|
||||
if (document.visibilityState === 'hidden') flush()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisibility)
|
||||
|
||||
return () => {
|
||||
clearInterval(interval)
|
||||
document.removeEventListener('visibilitychange', onVisibility)
|
||||
flush()
|
||||
}
|
||||
}, [enabled, flush])
|
||||
|
||||
return { hiddenIds, isHidden, markSeen, requestMore, requestLess }
|
||||
}
|
||||
73
gitgram/web/services/linkPreviewService.ts
Normal file
73
gitgram/web/services/linkPreviewService.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import api from './api'
|
||||
|
||||
/**
|
||||
* Link preview / unfurl card metadata.
|
||||
*
|
||||
* Mirrors the gitgram backend `LinkPreviewData` shape returned by the
|
||||
* `/v1/link-preview` proxy endpoint, which resolves OpenGraph
|
||||
* title/description/image server-side (avoiding browser CORS and centralising
|
||||
* caching). Ported in spirit from Bluesky's `getLinkMeta`, adapted to this
|
||||
* product's axios service convention.
|
||||
*/
|
||||
export interface LinkPreview {
|
||||
url: string
|
||||
title: string | null
|
||||
description: string | null
|
||||
image: string | null
|
||||
siteName: string | null
|
||||
favicon: string | null
|
||||
domain: string
|
||||
}
|
||||
|
||||
interface LinkPreviewResponse {
|
||||
success: boolean
|
||||
preview?: LinkPreview
|
||||
}
|
||||
|
||||
/** Module-scoped in-flight + result cache so the same URL is fetched once. */
|
||||
const previewCache = new Map<string, Promise<LinkPreview | null>>()
|
||||
|
||||
function isHttpUrl(value: string): boolean {
|
||||
try {
|
||||
const u = new URL(value)
|
||||
return u.protocol === 'http:' || u.protocol === 'https:'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export const linkPreviewService = {
|
||||
/**
|
||||
* Fetch unfurl metadata for a single external URL.
|
||||
* Returns `null` when the URL is invalid or no preview could be generated;
|
||||
* never throws, so callers can render a graceful fallback.
|
||||
*/
|
||||
getPreview: async (url: string): Promise<LinkPreview | null> => {
|
||||
if (!isHttpUrl(url)) return null
|
||||
|
||||
const cached = previewCache.get(url)
|
||||
if (cached) return cached
|
||||
|
||||
const request = (async (): Promise<LinkPreview | null> => {
|
||||
try {
|
||||
const { data } = await api.get<LinkPreviewResponse>('/v1/link-preview', {
|
||||
params: { url },
|
||||
})
|
||||
if (data?.success && data.preview) {
|
||||
return data.preview
|
||||
}
|
||||
return null
|
||||
} catch {
|
||||
// Unfurl failures are non-fatal — the caller falls back to a plain link.
|
||||
return null
|
||||
}
|
||||
})()
|
||||
|
||||
previewCache.set(url, request)
|
||||
// Evict failed lookups so a transient error can be retried later.
|
||||
request.then((result) => {
|
||||
if (result === null) previewCache.delete(url)
|
||||
})
|
||||
return request
|
||||
},
|
||||
}
|
||||
@ -42,6 +42,23 @@ export function normalizeReplyPermission(value: unknown): ReplyPermission {
|
||||
return isReplyPermission(value) ? value : 'everyone'
|
||||
}
|
||||
|
||||
/**
|
||||
* Negative / personalisation feed-feedback signals, ported from Bluesky's
|
||||
* feed-feedback interactions (requestLess/requestMore/seen). These let the feed
|
||||
* ranker learn from explicit "not interested" / "show more" actions and from
|
||||
* which posts the viewer actually saw.
|
||||
*/
|
||||
export type FeedSignal = 'requestLess' | 'requestMore' | 'seen'
|
||||
|
||||
export const FEED_SIGNALS: readonly FeedSignal[] = ['requestLess', 'requestMore', 'seen'] as const
|
||||
|
||||
export interface FeedSignalEvent {
|
||||
postId: string
|
||||
signal: FeedSignal
|
||||
/** Opaque feed/ranking context echoed back from the feed response, if any. */
|
||||
feedContext?: string
|
||||
}
|
||||
|
||||
export const postService = {
|
||||
getFeed: async (page = 1, limit = 10) => {
|
||||
const { data } = await api.get('/posts/feed', { params: { page, limit } })
|
||||
@ -150,6 +167,16 @@ export const postService = {
|
||||
return data
|
||||
},
|
||||
|
||||
/**
|
||||
* Send one or more feed-feedback signals (not-interested / show-more / seen)
|
||||
* to the personalisation endpoint. Batched by the caller; failures are
|
||||
* swallowed by the hook since these are best-effort ranking hints.
|
||||
*/
|
||||
sendFeedSignal: async (events: FeedSignalEvent[]) => {
|
||||
if (events.length === 0) return
|
||||
await api.post('/posts/feedback', { events })
|
||||
},
|
||||
|
||||
retweetPost: async (id: string, comment?: string) => {
|
||||
const { data } = await api.post(`/posts/${id}/retweet`, { comment })
|
||||
return data
|
||||
|
||||
File diff suppressed because one or more lines are too long
305
gitgram/web/utils/embedPlayer.ts
Normal file
305
gitgram/web/utils/embedPlayer.ts
Normal file
@ -0,0 +1,305 @@
|
||||
/**
|
||||
* Rich inline embed-player detection.
|
||||
*
|
||||
* Ported from Bluesky's `src/lib/strings/embed-player.ts` and adapted to the
|
||||
* gitgram-web stack: this is a pure, framework-agnostic URL -> embed mapping
|
||||
* with no React Native / iframe-host dependencies. Given an arbitrary URL it
|
||||
* returns the parameters needed to render an inline player (YouTube, YouTube
|
||||
* Shorts, Twitch, Spotify, Vimeo, SoundCloud, Apple Music, Giphy) or
|
||||
* `undefined` when the URL is not a recognised media provider.
|
||||
*
|
||||
* The detection is intentionally a flat, well-tested table of host/path rules
|
||||
* so new providers can be added without touching the rendering layer.
|
||||
*/
|
||||
|
||||
export const embedPlayerSources = [
|
||||
'youtube',
|
||||
'youtubeShorts',
|
||||
'twitch',
|
||||
'spotify',
|
||||
'soundcloud',
|
||||
'appleMusic',
|
||||
'vimeo',
|
||||
'giphy',
|
||||
] as const
|
||||
|
||||
export type EmbedPlayerSource = (typeof embedPlayerSources)[number]
|
||||
|
||||
export type EmbedPlayerType =
|
||||
| 'youtube_video'
|
||||
| 'youtube_short'
|
||||
| 'twitch_video'
|
||||
| 'spotify_album'
|
||||
| 'spotify_playlist'
|
||||
| 'spotify_song'
|
||||
| 'soundcloud_track'
|
||||
| 'soundcloud_set'
|
||||
| 'apple_music_playlist'
|
||||
| 'apple_music_album'
|
||||
| 'apple_music_song'
|
||||
| 'vimeo_video'
|
||||
| 'giphy_gif'
|
||||
|
||||
/** Human-readable provider labels, used for accessibility / fallbacks. */
|
||||
export const EMBED_PLAYER_LABELS: Record<EmbedPlayerSource, string> = {
|
||||
youtube: 'YouTube',
|
||||
youtubeShorts: 'YouTube Shorts',
|
||||
vimeo: 'Vimeo',
|
||||
twitch: 'Twitch',
|
||||
giphy: 'GIPHY',
|
||||
spotify: 'Spotify',
|
||||
appleMusic: 'Apple Music',
|
||||
soundcloud: 'SoundCloud',
|
||||
}
|
||||
|
||||
export interface EmbedPlayerParams {
|
||||
type: EmbedPlayerType
|
||||
/** The iframe / image `src` to render. */
|
||||
playerUri: string
|
||||
source: EmbedPlayerSource
|
||||
/** GIFs render as `<img>` rather than `<iframe>`. */
|
||||
isGif?: boolean
|
||||
/** Hide provider chrome (used for shorts / gifs). */
|
||||
hideDetails?: boolean
|
||||
}
|
||||
|
||||
const giphyRegex = /media(?:[0-4]\.giphy\.com|\.giphy\.com)/i
|
||||
const gifFilenameRegex = /^(\S+)\.(webp|gif|mp4)$/i
|
||||
|
||||
/**
|
||||
* The `parent` query param Twitch requires for its embed to load. On the
|
||||
* server (SSR) there is no `window`, so we fall back to `localhost`; the
|
||||
* embed is only ever rendered client-side, where the real hostname is used.
|
||||
*/
|
||||
function getEmbedParentHost(): string {
|
||||
if (typeof window !== 'undefined' && window.location?.hostname) {
|
||||
return window.location.hostname
|
||||
}
|
||||
return 'localhost'
|
||||
}
|
||||
|
||||
/**
|
||||
* Aspect-ratio / fixed-height hint for a given embed type, so the caller can
|
||||
* reserve layout space and avoid cumulative layout shift.
|
||||
*/
|
||||
export function getEmbedPlayerAspect(
|
||||
type: EmbedPlayerType,
|
||||
): { aspectRatio?: number; height?: number } {
|
||||
switch (type) {
|
||||
case 'youtube_video':
|
||||
case 'twitch_video':
|
||||
case 'vimeo_video':
|
||||
return { aspectRatio: 16 / 9 }
|
||||
case 'youtube_short':
|
||||
return { aspectRatio: 9 / 16 }
|
||||
case 'spotify_album':
|
||||
case 'apple_music_album':
|
||||
case 'apple_music_playlist':
|
||||
case 'spotify_playlist':
|
||||
case 'soundcloud_set':
|
||||
return { height: 380 }
|
||||
case 'spotify_song':
|
||||
return { height: 152 }
|
||||
case 'soundcloud_track':
|
||||
return { height: 165 }
|
||||
case 'apple_music_song':
|
||||
return { height: 150 }
|
||||
case 'giphy_gif':
|
||||
return { aspectRatio: 1 }
|
||||
default:
|
||||
return { aspectRatio: 16 / 9 }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a URL into inline-player embed parameters, or `undefined` if the URL
|
||||
* is not a recognised media provider. Never throws on malformed input.
|
||||
*/
|
||||
export function getEmbedPlayerSource(url: string): EmbedPlayerParams | undefined {
|
||||
let urlp: URL
|
||||
try {
|
||||
urlp = new URL(url)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
|
||||
// ── YouTube (youtu.be short links) ────────────────────────────────────────
|
||||
if (urlp.hostname === 'youtu.be') {
|
||||
const videoId = urlp.pathname.split('/')[1]
|
||||
const seek = encodeURIComponent((urlp.searchParams.get('t') ?? '0').replace(/s$/, ''))
|
||||
if (videoId) {
|
||||
return {
|
||||
type: 'youtube_video',
|
||||
source: 'youtube',
|
||||
playerUri: `https://www.youtube.com/embed/${encodeURIComponent(videoId)}?start=${seek}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── YouTube (full links, shorts, live) ────────────────────────────────────
|
||||
if (
|
||||
urlp.hostname === 'www.youtube.com' ||
|
||||
urlp.hostname === 'youtube.com' ||
|
||||
urlp.hostname === 'm.youtube.com' ||
|
||||
urlp.hostname === 'music.youtube.com'
|
||||
) {
|
||||
const [, page, shortOrLiveVideoId] = urlp.pathname.split('/')
|
||||
const isShorts = page === 'shorts'
|
||||
const isLive = page === 'live'
|
||||
const videoId = isShorts || isLive ? shortOrLiveVideoId : urlp.searchParams.get('v') ?? ''
|
||||
const seek = encodeURIComponent((urlp.searchParams.get('t') ?? '0').replace(/s$/, ''))
|
||||
|
||||
if (videoId) {
|
||||
return {
|
||||
type: isShorts ? 'youtube_short' : 'youtube_video',
|
||||
source: isShorts ? 'youtubeShorts' : 'youtube',
|
||||
hideDetails: isShorts || undefined,
|
||||
playerUri: `https://www.youtube.com/embed/${encodeURIComponent(videoId)}?start=${seek}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Twitch ────────────────────────────────────────────────────────────────
|
||||
if (
|
||||
urlp.hostname === 'twitch.tv' ||
|
||||
urlp.hostname === 'www.twitch.tv' ||
|
||||
urlp.hostname === 'm.twitch.tv'
|
||||
) {
|
||||
const parent = getEmbedParentHost()
|
||||
const [, channelOrVideo, clipOrId, id] = urlp.pathname.split('/')
|
||||
|
||||
if (channelOrVideo === 'videos') {
|
||||
return {
|
||||
type: 'twitch_video',
|
||||
source: 'twitch',
|
||||
playerUri: `https://player.twitch.tv/?volume=0.5&!muted&video=${encodeURIComponent(clipOrId)}&parent=${parent}`,
|
||||
}
|
||||
}
|
||||
if (clipOrId === 'clip') {
|
||||
return {
|
||||
type: 'twitch_video',
|
||||
source: 'twitch',
|
||||
playerUri: `https://clips.twitch.tv/embed?volume=0.5&clip=${encodeURIComponent(id)}&parent=${parent}`,
|
||||
}
|
||||
}
|
||||
if (channelOrVideo) {
|
||||
return {
|
||||
type: 'twitch_video',
|
||||
source: 'twitch',
|
||||
playerUri: `https://player.twitch.tv/?volume=0.5&!muted&channel=${encodeURIComponent(channelOrVideo)}&parent=${parent}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Spotify ───────────────────────────────────────────────────────────────
|
||||
if (urlp.hostname === 'open.spotify.com') {
|
||||
const [, typeOrLocale, idOrType, id] = urlp.pathname.split('/')
|
||||
if (idOrType) {
|
||||
const resolvedId = encodeURIComponent(id ?? idOrType)
|
||||
if (typeOrLocale === 'playlist' || idOrType === 'playlist') {
|
||||
return { type: 'spotify_playlist', source: 'spotify', playerUri: `https://open.spotify.com/embed/playlist/${resolvedId}` }
|
||||
}
|
||||
if (typeOrLocale === 'album' || idOrType === 'album') {
|
||||
return { type: 'spotify_album', source: 'spotify', playerUri: `https://open.spotify.com/embed/album/${resolvedId}` }
|
||||
}
|
||||
if (typeOrLocale === 'track' || idOrType === 'track') {
|
||||
return { type: 'spotify_song', source: 'spotify', playerUri: `https://open.spotify.com/embed/track/${resolvedId}` }
|
||||
}
|
||||
if (typeOrLocale === 'episode' || idOrType === 'episode') {
|
||||
return { type: 'spotify_song', source: 'spotify', playerUri: `https://open.spotify.com/embed/episode/${resolvedId}` }
|
||||
}
|
||||
if (typeOrLocale === 'show' || idOrType === 'show') {
|
||||
return { type: 'spotify_song', source: 'spotify', playerUri: `https://open.spotify.com/embed/show/${resolvedId}` }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── SoundCloud ────────────────────────────────────────────────────────────
|
||||
if (urlp.hostname === 'soundcloud.com' || urlp.hostname === 'www.soundcloud.com') {
|
||||
const [, user, trackOrSets, set] = urlp.pathname.split('/')
|
||||
if (user && trackOrSets) {
|
||||
const playerUri = `https://w.soundcloud.com/player/?url=${encodeURIComponent(url)}&visual=false&hide_related=true`
|
||||
if (trackOrSets === 'sets' && set) {
|
||||
return { type: 'soundcloud_set', source: 'soundcloud', playerUri }
|
||||
}
|
||||
return { type: 'soundcloud_track', source: 'soundcloud', playerUri }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Apple Music ───────────────────────────────────────────────────────────
|
||||
if (urlp.hostname === 'music.apple.com') {
|
||||
const pathParams = urlp.pathname.split('/')
|
||||
const type = pathParams[2]
|
||||
const songId = urlp.searchParams.get('i')
|
||||
if (pathParams.length === 5 && (type === 'playlist' || type === 'album' || type === 'song')) {
|
||||
const embedUri = `https://embed.music.apple.com${urlp.pathname}${songId ? `?i=${encodeURIComponent(songId)}` : ''}`
|
||||
if (type === 'playlist') {
|
||||
return { type: 'apple_music_playlist', source: 'appleMusic', playerUri: embedUri }
|
||||
}
|
||||
if (type === 'album') {
|
||||
return songId
|
||||
? { type: 'apple_music_song', source: 'appleMusic', playerUri: embedUri }
|
||||
: { type: 'apple_music_album', source: 'appleMusic', playerUri: embedUri }
|
||||
}
|
||||
return { type: 'apple_music_song', source: 'appleMusic', playerUri: embedUri }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Vimeo ─────────────────────────────────────────────────────────────────
|
||||
if (urlp.hostname === 'vimeo.com' || urlp.hostname === 'www.vimeo.com') {
|
||||
const [, videoId] = urlp.pathname.split('/')
|
||||
if (videoId && /^\d+$/.test(videoId)) {
|
||||
return { type: 'vimeo_video', source: 'vimeo', playerUri: `https://player.vimeo.com/video/${videoId}` }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Giphy (page links) ────────────────────────────────────────────────────
|
||||
if (urlp.hostname === 'giphy.com' || urlp.hostname === 'www.giphy.com') {
|
||||
const [, gifs, nameAndId] = urlp.pathname.split('/')
|
||||
if (gifs === 'gifs' && nameAndId) {
|
||||
const gifId = nameAndId.split('-').pop()
|
||||
if (gifId) {
|
||||
return {
|
||||
type: 'giphy_gif',
|
||||
source: 'giphy',
|
||||
isGif: true,
|
||||
hideDetails: true,
|
||||
playerUri: `https://i.giphy.com/media/${encodeURIComponent(gifId)}/200.webp`,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Giphy (direct media links: media.giphy.com / media0-4.giphy.com) ──────
|
||||
if (giphyRegex.test(urlp.hostname)) {
|
||||
const [, media, trackingOrId, idOrFilename, filename] = urlp.pathname.split('/')
|
||||
if (media === 'media') {
|
||||
if (idOrFilename && gifFilenameRegex.test(idOrFilename)) {
|
||||
return { type: 'giphy_gif', source: 'giphy', isGif: true, hideDetails: true, playerUri: `https://i.giphy.com/media/${encodeURIComponent(trackingOrId)}/200.webp` }
|
||||
}
|
||||
if (filename && gifFilenameRegex.test(filename)) {
|
||||
return { type: 'giphy_gif', source: 'giphy', isGif: true, hideDetails: true, playerUri: `https://i.giphy.com/media/${encodeURIComponent(idOrFilename)}/200.webp` }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Giphy (i.giphy.com) ───────────────────────────────────────────────────
|
||||
if (urlp.hostname === 'i.giphy.com' || urlp.hostname === 'www.i.giphy.com') {
|
||||
const [, mediaOrFilename, filename] = urlp.pathname.split('/')
|
||||
if (mediaOrFilename === 'media' && filename) {
|
||||
const gifId = filename.split('.')[0]
|
||||
return { type: 'giphy_gif', source: 'giphy', isGif: true, hideDetails: true, playerUri: `https://i.giphy.com/media/${encodeURIComponent(gifId)}/200.webp` }
|
||||
}
|
||||
if (mediaOrFilename) {
|
||||
const gifId = mediaOrFilename.split('.')[0]
|
||||
return { type: 'giphy_gif', source: 'giphy', isGif: true, hideDetails: true, playerUri: `https://i.giphy.com/media/${encodeURIComponent(gifId)}/200.webp` }
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Convenience predicate: does this URL map to an inline player? */
|
||||
export function isEmbedPlayerUrl(url: string): boolean {
|
||||
return getEmbedPlayerSource(url) !== undefined
|
||||
}
|
||||
46
gitgram/web/utils/extractUrls.ts
Normal file
46
gitgram/web/utils/extractUrls.ts
Normal file
@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Extracts bare http(s) URLs from free text.
|
||||
*
|
||||
* Used by RichContent to detect external links worth turning into an inline
|
||||
* embed player or a link-preview card. Only the first few unique URLs are
|
||||
* surfaced to keep the feed light. Trailing punctuation commonly adjacent to a
|
||||
* URL in prose (`,`, `.`, `)`, etc.) is trimmed off.
|
||||
*/
|
||||
|
||||
const URL_PATTERN = /\bhttps?:\/\/[^\s<>()]+/gi
|
||||
const TRAILING_PUNCTUATION = /[.,!?;:'")\]]+$/
|
||||
|
||||
export interface ExtractUrlsOptions {
|
||||
/** Maximum number of unique URLs to return (default 3). */
|
||||
limit?: number
|
||||
}
|
||||
|
||||
export function extractUrls(text: string, options: ExtractUrlsOptions = {}): string[] {
|
||||
const limit = options.limit ?? 3
|
||||
if (!text) return []
|
||||
|
||||
const seen = new Set<string>()
|
||||
const result: string[] = []
|
||||
|
||||
const matches = text.match(URL_PATTERN)
|
||||
if (!matches) return result
|
||||
|
||||
for (const raw of matches) {
|
||||
const cleaned = raw.replace(TRAILING_PUNCTUATION, '')
|
||||
if (!cleaned || seen.has(cleaned)) continue
|
||||
|
||||
// Validate it's a real, well-formed URL before surfacing it.
|
||||
try {
|
||||
const u = new URL(cleaned)
|
||||
if (u.protocol !== 'http:' && u.protocol !== 'https:') continue
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
|
||||
seen.add(cleaned)
|
||||
result.push(cleaned)
|
||||
if (result.length >= limit) break
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
import { Fragment, type ReactNode } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { UserHoverCard } from '@/components/UserHoverCard';
|
||||
|
||||
/**
|
||||
* Matches @mentions and #hashtags in free text.
|
||||
@ -61,9 +62,8 @@ export function linkifyText(text: string, options: LinkifyOptions = {}): ReactNo
|
||||
nodes.push(<Fragment key={`t-${keyCounter++}`}>{precedingText}</Fragment>);
|
||||
}
|
||||
|
||||
nodes.push(
|
||||
const link = (
|
||||
<Link
|
||||
key={`l-${keyCounter++}`}
|
||||
href={hrefForToken(char, word)}
|
||||
className={linkClassName}
|
||||
// Stop the click from bubbling to parent post/card click handlers.
|
||||
@ -71,7 +71,18 @@ export function linkifyText(text: string, options: LinkifyOptions = {}): ReactNo
|
||||
>
|
||||
{char}
|
||||
{word}
|
||||
</Link>,
|
||||
</Link>
|
||||
);
|
||||
|
||||
// Mentions get a profile-preview hover card; hashtags stay as plain links.
|
||||
nodes.push(
|
||||
char === '@' ? (
|
||||
<UserHoverCard key={`l-${keyCounter++}`} username={word}>
|
||||
{link}
|
||||
</UserHoverCard>
|
||||
) : (
|
||||
<Fragment key={`l-${keyCounter++}`}>{link}</Fragment>
|
||||
),
|
||||
);
|
||||
|
||||
lastIndex = tokenStart + char.length + word.length;
|
||||
|
||||
Reference in New Issue
Block a user