v3: added emoji picker, various bug and layout fixes
This commit is contained in:
16
api/main.ts
16
api/main.ts
@@ -16,6 +16,8 @@ import invitesRouter from "./routes/invites.ts";
|
|||||||
import { BASE_URL, HOSTNAME, PORT } from "./config.ts";
|
import { BASE_URL, HOSTNAME, PORT } from "./config.ts";
|
||||||
import { errorMiddleware } from "./middleware/error.ts";
|
import { errorMiddleware } from "./middleware/error.ts";
|
||||||
import routeStaticFilesFrom from "./lib/static.ts";
|
import routeStaticFilesFrom from "./lib/static.ts";
|
||||||
|
import { DUMPS_DIR, UPLOADS_DIR } from "./utils/upload.ts";
|
||||||
|
import { UUID_RE } from "./lib/slugify.ts";
|
||||||
|
|
||||||
const app = new Application();
|
const app = new Application();
|
||||||
|
|
||||||
@@ -80,7 +82,21 @@ app.addEventListener(
|
|||||||
(e) => console.log(`Uncaught error: ${e.message}`),
|
(e) => console.log(`Uncaught error: ${e.message}`),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Migrate dump files from uploads root to uploads/dumps subfolder
|
||||||
|
async function migrateDumpFiles() {
|
||||||
|
await Deno.mkdir(DUMPS_DIR, { recursive: true });
|
||||||
|
for await (const entry of Deno.readDir(UPLOADS_DIR)) {
|
||||||
|
if (entry.isFile && UUID_RE.test(entry.name)) {
|
||||||
|
await Deno.rename(
|
||||||
|
`${UPLOADS_DIR}/${entry.name}`,
|
||||||
|
`${DUMPS_DIR}/${entry.name}`,
|
||||||
|
).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (import.meta.main) {
|
if (import.meta.main) {
|
||||||
|
await migrateDumpFiles();
|
||||||
await app.listen({ hostname: HOSTNAME, port: PORT });
|
await app.listen({ hostname: HOSTNAME, port: PORT });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,41 +8,10 @@ import {
|
|||||||
type RichContent,
|
type RichContent,
|
||||||
type User,
|
type User,
|
||||||
} from "./interfaces.ts";
|
} from "./interfaces.ts";
|
||||||
import { makeSlug } from "../lib/slugify.ts";
|
|
||||||
|
|
||||||
export const db = new DatabaseSync("api/sql/gerbeur.db");
|
export const db = new DatabaseSync("api/sql/gerbeur.db");
|
||||||
db.exec("PRAGMA foreign_keys = ON;");
|
db.exec("PRAGMA foreign_keys = ON;");
|
||||||
|
|
||||||
// Add columns to existing tables if missing (idempotent migrations)
|
|
||||||
for (
|
|
||||||
const [table, col, def] of [
|
|
||||||
["dumps", "updated_at", "TEXT"],
|
|
||||||
["users", "updated_at", "TEXT"],
|
|
||||||
["playlists", "updated_at", "TEXT"],
|
|
||||||
["comments", "updated_at", "TEXT"],
|
|
||||||
["dumps", "slug", "TEXT"],
|
|
||||||
["playlists", "slug", "TEXT"],
|
|
||||||
] as [string, string, string][]
|
|
||||||
) {
|
|
||||||
const cols = db.prepare(`PRAGMA table_info(${table})`).all() as {
|
|
||||||
name: string;
|
|
||||||
}[];
|
|
||||||
if (!cols.some((c) => c.name === col)) {
|
|
||||||
db.exec(`ALTER TABLE ${table} ADD COLUMN ${col} ${def};`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backfill slugs for any records created before this migration
|
|
||||||
for (const table of ["dumps", "playlists"] as const) {
|
|
||||||
const rows = db.prepare(
|
|
||||||
`SELECT id, title FROM ${table} WHERE slug IS NULL;`,
|
|
||||||
).all() as { id: string; title: string }[];
|
|
||||||
const update = db.prepare(`UPDATE ${table} SET slug = ? WHERE id = ?;`);
|
|
||||||
for (const row of rows) {
|
|
||||||
update.run(makeSlug(row.title, row.id), row.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Purge expired unused invites on startup
|
// Purge expired unused invites on startup
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`DELETE FROM invites WHERE used_at IS NULL AND created_at < datetime('now', '-7 days');`,
|
`DELETE FROM invites WHERE used_at IS NULL AND created_at < datetime('now', '-7 days');`,
|
||||||
|
|||||||
@@ -363,6 +363,7 @@ export interface OnlineUser {
|
|||||||
userId: string;
|
userId: string;
|
||||||
username: string;
|
username: string;
|
||||||
hasAvatar: boolean;
|
hasAvatar: boolean;
|
||||||
|
avatarVersion?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WelcomeMessage {
|
export interface WelcomeMessage {
|
||||||
|
|||||||
@@ -3,35 +3,12 @@ import { authMiddleware } from "../middleware/auth.ts";
|
|||||||
import { getUserById, updateUserAvatar } from "../services/user-service.ts";
|
import { getUserById, updateUserAvatar } from "../services/user-service.ts";
|
||||||
import { updateClientAvatar } from "../services/ws-service.ts";
|
import { updateClientAvatar } from "../services/ws-service.ts";
|
||||||
import { APIErrorCode, APIException } from "../model/interfaces.ts";
|
import { APIErrorCode, APIException } from "../model/interfaces.ts";
|
||||||
|
import {
|
||||||
const AVATARS_DIR = "api/uploads/avatars";
|
AVATARS_DIR,
|
||||||
const MAX_AVATAR_SIZE = 5 * 1024 * 1024; // 5 MB
|
detectImageMime,
|
||||||
const ALLOWED_AVATAR_MIMES = new Set([
|
MAX_IMAGE_SIZE,
|
||||||
"image/jpeg",
|
serveUploadedFile,
|
||||||
"image/png",
|
} from "../utils/upload.ts";
|
||||||
"image/gif",
|
|
||||||
"image/webp",
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Magic bytes for image validation
|
|
||||||
const MAGIC: Array<{ mime: string; bytes: number[]; offset?: number }> = [
|
|
||||||
{ mime: "image/jpeg", bytes: [0xFF, 0xD8, 0xFF] },
|
|
||||||
{ mime: "image/png", bytes: [0x89, 0x50, 0x4E, 0x47] },
|
|
||||||
{ mime: "image/gif", bytes: [0x47, 0x49, 0x46, 0x38] },
|
|
||||||
{ mime: "image/webp", bytes: [0x52, 0x49, 0x46, 0x46], offset: 0 }, // RIFF
|
|
||||||
];
|
|
||||||
|
|
||||||
function checkMagicBytes(data: Uint8Array, mime: string): boolean {
|
|
||||||
if (mime === "image/webp") {
|
|
||||||
// RIFF....WEBP
|
|
||||||
return data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 &&
|
|
||||||
data[3] === 0x46 && data[8] === 0x57 && data[9] === 0x45 &&
|
|
||||||
data[10] === 0x42 && data[11] === 0x50;
|
|
||||||
}
|
|
||||||
const entry = MAGIC.find((m) => m.mime === mime);
|
|
||||||
if (!entry) return false;
|
|
||||||
return entry.bytes.every((b, i) => data[i] === b);
|
|
||||||
}
|
|
||||||
|
|
||||||
const router = new Router();
|
const router = new Router();
|
||||||
|
|
||||||
@@ -53,15 +30,7 @@ router.post("/api/avatars/me", authMiddleware, async (ctx) => {
|
|||||||
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
|
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ALLOWED_AVATAR_MIMES.has(file.type)) {
|
if (file.size > MAX_IMAGE_SIZE) {
|
||||||
throw new APIException(
|
|
||||||
APIErrorCode.BAD_REQUEST,
|
|
||||||
400,
|
|
||||||
"Only JPEG, PNG, GIF, WebP images are allowed",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (file.size > MAX_AVATAR_SIZE) {
|
|
||||||
throw new APIException(
|
throw new APIException(
|
||||||
APIErrorCode.BAD_REQUEST,
|
APIErrorCode.BAD_REQUEST,
|
||||||
400,
|
400,
|
||||||
@@ -71,18 +40,19 @@ router.post("/api/avatars/me", authMiddleware, async (ctx) => {
|
|||||||
|
|
||||||
const data = new Uint8Array(await file.arrayBuffer());
|
const data = new Uint8Array(await file.arrayBuffer());
|
||||||
|
|
||||||
if (!checkMagicBytes(data, file.type)) {
|
const mime = detectImageMime(data);
|
||||||
|
if (!mime) {
|
||||||
throw new APIException(
|
throw new APIException(
|
||||||
APIErrorCode.BAD_REQUEST,
|
APIErrorCode.BAD_REQUEST,
|
||||||
400,
|
400,
|
||||||
"File content does not match declared type",
|
"File content is not a recognised image (JPEG, PNG, GIF, WebP)",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await Deno.mkdir(AVATARS_DIR, { recursive: true });
|
await Deno.mkdir(AVATARS_DIR, { recursive: true });
|
||||||
await Deno.writeFile(`${AVATARS_DIR}/${authPayload.userId}`, data);
|
await Deno.writeFile(`${AVATARS_DIR}/${authPayload.userId}`, data);
|
||||||
updateUserAvatar(authPayload.userId, file.type);
|
updateUserAvatar(authPayload.userId, mime);
|
||||||
updateClientAvatar(authPayload.userId, file.type);
|
updateClientAvatar(authPayload.userId, mime);
|
||||||
|
|
||||||
const user = getUserById(authPayload.userId);
|
const user = getUserById(authPayload.userId);
|
||||||
ctx.response.status = 200;
|
ctx.response.status = 200;
|
||||||
@@ -105,18 +75,7 @@ router.get("/api/avatars/:userId", async (ctx) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let data: Uint8Array;
|
await serveUploadedFile(ctx, `${AVATARS_DIR}/${userId}`, user.avatarMime);
|
||||||
try {
|
|
||||||
data = await Deno.readFile(`${AVATARS_DIR}/${userId}`);
|
|
||||||
} catch {
|
|
||||||
ctx.response.status = 404;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.response.headers.set("Content-Type", user.avatarMime);
|
|
||||||
ctx.response.headers.set("Content-Disposition", "inline");
|
|
||||||
ctx.response.headers.set("Cache-Control", "public, max-age=3600");
|
|
||||||
ctx.response.body = data;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Router } from "@oak/oak";
|
import { Router } from "@oak/oak";
|
||||||
import { APIErrorCode, APIException } from "../model/interfaces.ts";
|
import { APIErrorCode, APIException } from "../model/interfaces.ts";
|
||||||
import { getDump } from "../services/dump-service.ts";
|
import { getDump } from "../services/dump-service.ts";
|
||||||
|
import { DUMPS_DIR } from "../utils/upload.ts";
|
||||||
|
|
||||||
const router = new Router({ prefix: "/api/files" });
|
const router = new Router({ prefix: "/api/files" });
|
||||||
|
|
||||||
@@ -22,7 +23,7 @@ router.get("/:dumpId", async (ctx) => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const path = `api/uploads/${dumpId}`;
|
const path = `${DUMPS_DIR}/${dumpId}`;
|
||||||
|
|
||||||
let data: Uint8Array;
|
let data: Uint8Array;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -13,36 +13,19 @@ import {
|
|||||||
createPlaylist,
|
createPlaylist,
|
||||||
deletePlaylist,
|
deletePlaylist,
|
||||||
getPlaylist,
|
getPlaylist,
|
||||||
getPlaylistImageMime,
|
getPlaylistImageInfo,
|
||||||
getPlaylistMembershipsForDump,
|
getPlaylistMembershipsForDump,
|
||||||
removeDumpFromPlaylist,
|
removeDumpFromPlaylist,
|
||||||
reorderPlaylist,
|
reorderPlaylist,
|
||||||
setPlaylistImage,
|
setPlaylistImage,
|
||||||
updatePlaylist,
|
updatePlaylist,
|
||||||
} from "../services/playlist-service.ts";
|
} from "../services/playlist-service.ts";
|
||||||
|
import {
|
||||||
const PLAYLIST_IMAGES_DIR = "api/uploads/playlist-images";
|
detectImageMime,
|
||||||
const MAX_IMAGE_SIZE = 5 * 1024 * 1024;
|
MAX_IMAGE_SIZE,
|
||||||
const ALLOWED_IMAGE_MIMES = new Set([
|
PLAYLIST_IMAGES_DIR,
|
||||||
"image/jpeg",
|
serveUploadedFile,
|
||||||
"image/png",
|
} from "../utils/upload.ts";
|
||||||
"image/gif",
|
|
||||||
"image/webp",
|
|
||||||
]);
|
|
||||||
|
|
||||||
function checkImageMagicBytes(data: Uint8Array, mime: string): boolean {
|
|
||||||
if (mime === "image/webp") {
|
|
||||||
return data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 &&
|
|
||||||
data[3] === 0x46 && data[8] === 0x57 && data[9] === 0x45 &&
|
|
||||||
data[10] === 0x42 && data[11] === 0x50;
|
|
||||||
}
|
|
||||||
const magic: Record<string, number[]> = {
|
|
||||||
"image/jpeg": [0xFF, 0xD8, 0xFF],
|
|
||||||
"image/png": [0x89, 0x50, 0x4E, 0x47],
|
|
||||||
"image/gif": [0x47, 0x49, 0x46, 0x38],
|
|
||||||
};
|
|
||||||
return (magic[mime] ?? []).every((b, i) => data[i] === b);
|
|
||||||
}
|
|
||||||
|
|
||||||
const router = new Router<AuthState>({ prefix: "/api/playlists" });
|
const router = new Router<AuthState>({ prefix: "/api/playlists" });
|
||||||
|
|
||||||
@@ -143,14 +126,6 @@ router.post("/:playlistId/image", authMiddleware, async (ctx) => {
|
|||||||
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
|
throw new APIException(APIErrorCode.BAD_REQUEST, 400, "Missing file field");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ALLOWED_IMAGE_MIMES.has(file.type)) {
|
|
||||||
throw new APIException(
|
|
||||||
APIErrorCode.BAD_REQUEST,
|
|
||||||
400,
|
|
||||||
"Only JPEG, PNG, GIF, WebP images are allowed",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (file.size > MAX_IMAGE_SIZE) {
|
if (file.size > MAX_IMAGE_SIZE) {
|
||||||
throw new APIException(
|
throw new APIException(
|
||||||
APIErrorCode.BAD_REQUEST,
|
APIErrorCode.BAD_REQUEST,
|
||||||
@@ -160,46 +135,38 @@ router.post("/:playlistId/image", authMiddleware, async (ctx) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = new Uint8Array(await file.arrayBuffer());
|
const data = new Uint8Array(await file.arrayBuffer());
|
||||||
if (!checkImageMagicBytes(data, file.type)) {
|
const mime = detectImageMime(data);
|
||||||
|
if (!mime) {
|
||||||
throw new APIException(
|
throw new APIException(
|
||||||
APIErrorCode.BAD_REQUEST,
|
APIErrorCode.BAD_REQUEST,
|
||||||
400,
|
400,
|
||||||
"File content does not match declared type",
|
"File content is not a recognised image (JPEG, PNG, GIF, WebP)",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await Deno.mkdir(PLAYLIST_IMAGES_DIR, { recursive: true });
|
// Resolve slug → UUID via service (validates ownership too), then write file
|
||||||
await Deno.writeFile(`${PLAYLIST_IMAGES_DIR}/${ctx.params.playlistId}`, data);
|
|
||||||
const playlist = setPlaylistImage(
|
const playlist = setPlaylistImage(
|
||||||
ctx.params.playlistId,
|
ctx.params.playlistId,
|
||||||
file.type,
|
mime,
|
||||||
ctx.state.user.userId,
|
ctx.state.user.userId,
|
||||||
);
|
);
|
||||||
|
await Deno.mkdir(PLAYLIST_IMAGES_DIR, { recursive: true });
|
||||||
|
await Deno.writeFile(`${PLAYLIST_IMAGES_DIR}/${playlist.id}`, data);
|
||||||
ctx.response.body = { success: true, data: playlist };
|
ctx.response.body = { success: true, data: playlist };
|
||||||
});
|
});
|
||||||
|
|
||||||
// GET /api/playlists/:playlistId/image — serve playlist image
|
// GET /api/playlists/:playlistId/image — serve playlist image
|
||||||
router.get("/:playlistId/image", async (ctx) => {
|
router.get("/:playlistId/image", async (ctx) => {
|
||||||
const imageMime = getPlaylistImageMime(ctx.params.playlistId);
|
const info = getPlaylistImageInfo(ctx.params.playlistId);
|
||||||
if (!imageMime) {
|
if (!info) {
|
||||||
ctx.response.status = 404;
|
ctx.response.status = 404;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
await serveUploadedFile(
|
||||||
let data: Uint8Array;
|
ctx,
|
||||||
try {
|
`${PLAYLIST_IMAGES_DIR}/${info.id}`,
|
||||||
data = await Deno.readFile(
|
info.imageMime,
|
||||||
`${PLAYLIST_IMAGES_DIR}/${ctx.params.playlistId}`,
|
|
||||||
);
|
);
|
||||||
} catch {
|
|
||||||
ctx.response.status = 404;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.response.headers.set("Content-Type", imageMime);
|
|
||||||
ctx.response.headers.set("Content-Disposition", "inline");
|
|
||||||
ctx.response.headers.set("Cache-Control", "public, max-age=3600");
|
|
||||||
ctx.response.body = data;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// PUT /api/playlists/:playlistId/order — reorder
|
// PUT /api/playlists/:playlistId/order — reorder
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ import {
|
|||||||
notifyUserFollowersNewDump,
|
notifyUserFollowersNewDump,
|
||||||
} from "./notification-service.ts";
|
} from "./notification-service.ts";
|
||||||
import { makeSlug, UUID_RE } from "../lib/slugify.ts";
|
import { makeSlug, UUID_RE } from "../lib/slugify.ts";
|
||||||
|
import { DUMPS_DIR } from "../utils/upload.ts";
|
||||||
|
|
||||||
const UPLOADS_DIR = "api/uploads";
|
|
||||||
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
|
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
|
||||||
|
|
||||||
const ALLOWED_MIME_PREFIXES = ["text/", "image/", "video/", "audio/"];
|
const ALLOWED_MIME_PREFIXES = ["text/", "image/", "video/", "audio/"];
|
||||||
@@ -138,11 +138,11 @@ export async function createFileDump(
|
|||||||
const createdAt = new Date();
|
const createdAt = new Date();
|
||||||
const slug = makeSlug(file.name, dumpId);
|
const slug = makeSlug(file.name, dumpId);
|
||||||
|
|
||||||
await Deno.mkdir(UPLOADS_DIR, { recursive: true });
|
await Deno.mkdir(DUMPS_DIR, { recursive: true });
|
||||||
const data = new Uint8Array(await file.arrayBuffer());
|
const data = new Uint8Array(await file.arrayBuffer());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Deno.writeFile(`${UPLOADS_DIR}/${dumpId}`, data);
|
await Deno.writeFile(`${DUMPS_DIR}/${dumpId}`, data);
|
||||||
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`INSERT INTO dumps (id, kind, title, slug, comment, user_id, created_at, file_name, file_mime, file_size, is_private)
|
`INSERT INTO dumps (id, kind, title, slug, comment, user_id, created_at, file_name, file_mime, file_size, is_private)
|
||||||
@@ -162,7 +162,7 @@ export async function createFileDump(
|
|||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Roll back the file if DB insert fails
|
// Roll back the file if DB insert fails
|
||||||
await Deno.remove(`${UPLOADS_DIR}/${dumpId}`).catch(() => {});
|
await Deno.remove(`${DUMPS_DIR}/${dumpId}`).catch(() => {});
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -374,7 +374,7 @@ export async function replaceFileDump(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = new Uint8Array(await file.arrayBuffer());
|
const data = new Uint8Array(await file.arrayBuffer());
|
||||||
await Deno.writeFile(`${UPLOADS_DIR}/${dumpId}`, data);
|
await Deno.writeFile(`${DUMPS_DIR}/${dumpId}`, data);
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const newSlug = makeSlug(file.name, dumpId);
|
const newSlug = makeSlug(file.name, dumpId);
|
||||||
@@ -513,7 +513,7 @@ export async function deleteDump(dumpId: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (dump.kind === "file") {
|
if (dump.kind === "file") {
|
||||||
await Deno.remove(`${UPLOADS_DIR}/${dumpId}`).catch(() => {});
|
await Deno.remove(`${DUMPS_DIR}/${dumpId}`).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
broadcastDumpDeleted(dumpId);
|
broadcastDumpDeleted(dumpId);
|
||||||
|
|||||||
@@ -356,13 +356,13 @@ export function getPlaylistMembershipsForDump(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getPlaylistImageMime(playlistId: string): string | undefined {
|
export function getPlaylistImageInfo(
|
||||||
const row = db.prepare(`SELECT image_mime FROM playlists WHERE id = ?;`).get(
|
idOrSlug: string,
|
||||||
playlistId,
|
): { id: string; imageMime: string } | undefined {
|
||||||
) as
|
const playlist = getPlaylistById(idOrSlug);
|
||||||
| { image_mime: string | null }
|
return playlist.imageMime
|
||||||
| undefined;
|
? { id: playlist.id, imageMime: playlist.imageMime }
|
||||||
return row?.image_mime ?? undefined;
|
: undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getCurrentDumpIds(playlistId: string): string[] {
|
function getCurrentDumpIds(playlistId: string): string[] {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { db, isUserRow, userApiToRow, userRowToApi } from "../model/db.ts";
|
|||||||
import { hashPassword } from "../lib/jwt.ts";
|
import { hashPassword } from "../lib/jwt.ts";
|
||||||
|
|
||||||
const USER_SELECT =
|
const USER_SELECT =
|
||||||
`SELECT u.id, u.username, u.password_hash, u.is_admin, u.created_at, u.avatar_mime, u.invited_by,
|
`SELECT u.id, u.username, u.password_hash, u.is_admin, u.created_at, u.updated_at, u.avatar_mime, u.invited_by,
|
||||||
i.username as invited_by_username
|
i.username as invited_by_username
|
||||||
FROM users u
|
FROM users u
|
||||||
LEFT JOIN users i ON i.id = u.invited_by`;
|
LEFT JOIN users i ON i.id = u.invited_by`;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export interface WsClient {
|
|||||||
userId?: string;
|
userId?: string;
|
||||||
username?: string;
|
username?: string;
|
||||||
avatarMime?: string;
|
avatarMime?: string;
|
||||||
|
avatarVersion?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const clients = new Set<WsClient>();
|
const clients = new Set<WsClient>();
|
||||||
@@ -23,9 +24,11 @@ export function unregister(client: WsClient): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function updateClientAvatar(userId: string, avatarMime: string): void {
|
export function updateClientAvatar(userId: string, avatarMime: string): void {
|
||||||
|
const version = Date.now();
|
||||||
for (const client of clients) {
|
for (const client of clients) {
|
||||||
if (client.userId === userId) {
|
if (client.userId === userId) {
|
||||||
client.avatarMime = avatarMime;
|
client.avatarMime = avatarMime;
|
||||||
|
client.avatarVersion = version;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
broadcastPresence();
|
broadcastPresence();
|
||||||
@@ -39,6 +42,7 @@ export function getOnlineUsers(): OnlineUser[] {
|
|||||||
userId: client.userId,
|
userId: client.userId,
|
||||||
username: client.username!,
|
username: client.username!,
|
||||||
hasAvatar: !!client.avatarMime,
|
hasAvatar: !!client.avatarMime,
|
||||||
|
avatarVersion: client.avatarVersion,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
57
api/utils/upload.ts
Normal file
57
api/utils/upload.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import type { Context } from "@oak/oak";
|
||||||
|
|
||||||
|
export const UPLOADS_DIR = "api/uploads";
|
||||||
|
export const DUMPS_DIR = `${UPLOADS_DIR}/dumps`;
|
||||||
|
export const AVATARS_DIR = `${UPLOADS_DIR}/avatars`;
|
||||||
|
export const PLAYLIST_IMAGES_DIR = `${UPLOADS_DIR}/playlist-images`;
|
||||||
|
|
||||||
|
export const MAX_IMAGE_SIZE = 5 * 1024 * 1024; // 5 MB
|
||||||
|
|
||||||
|
export const ALLOWED_IMAGE_MIMES = new Set([
|
||||||
|
"image/jpeg",
|
||||||
|
"image/png",
|
||||||
|
"image/gif",
|
||||||
|
"image/webp",
|
||||||
|
]);
|
||||||
|
|
||||||
|
/** Detect image MIME type from magic bytes, ignoring the browser-declared type. */
|
||||||
|
export function detectImageMime(data: Uint8Array): string | null {
|
||||||
|
if (data[0] === 0xFF && data[1] === 0xD8 && data[2] === 0xFF) {
|
||||||
|
return "image/jpeg";
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4E && data[3] === 0x47
|
||||||
|
) return "image/png";
|
||||||
|
if (
|
||||||
|
data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x38
|
||||||
|
) return "image/gif";
|
||||||
|
// RIFF....WEBP
|
||||||
|
if (
|
||||||
|
data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 &&
|
||||||
|
data[3] === 0x46 &&
|
||||||
|
data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 &&
|
||||||
|
data[11] === 0x50
|
||||||
|
) return "image/webp";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function serveUploadedFile(
|
||||||
|
ctx: Context,
|
||||||
|
filePath: string,
|
||||||
|
mime: string,
|
||||||
|
cacheMaxAge = 3600,
|
||||||
|
): Promise<boolean> {
|
||||||
|
let data: Uint8Array;
|
||||||
|
try {
|
||||||
|
data = await Deno.readFile(filePath);
|
||||||
|
} catch {
|
||||||
|
ctx.response.status = 404;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
ctx.response.headers.set("Content-Type", mime);
|
||||||
|
ctx.response.headers.set("Content-Disposition", "inline");
|
||||||
|
ctx.response.headers.set("Cache-Control", `public, max-age=${cacheMaxAge}`);
|
||||||
|
ctx.response.headers.set("Cross-Origin-Resource-Policy", "cross-origin");
|
||||||
|
ctx.response.body = data;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
12
deno.lock
generated
12
deno.lock
generated
@@ -29,6 +29,7 @@
|
|||||||
"npm:eslint-plugin-react-hooks@^7.0.1": "7.0.1_eslint@9.39.4",
|
"npm:eslint-plugin-react-hooks@^7.0.1": "7.0.1_eslint@9.39.4",
|
||||||
"npm:eslint-plugin-react-refresh@~0.5.2": "0.5.2_eslint@9.39.4",
|
"npm:eslint-plugin-react-refresh@~0.5.2": "0.5.2_eslint@9.39.4",
|
||||||
"npm:eslint@^9.39.4": "9.39.4",
|
"npm:eslint@^9.39.4": "9.39.4",
|
||||||
|
"npm:frimousse@0.3": "0.3.0_react@19.2.4_typescript@5.9.3",
|
||||||
"npm:globals@^17.4.0": "17.4.0",
|
"npm:globals@^17.4.0": "17.4.0",
|
||||||
"npm:path-to-regexp@^6.3.0": "6.3.0",
|
"npm:path-to-regexp@^6.3.0": "6.3.0",
|
||||||
"npm:react-dom@^19.2.4": "19.2.4_react@19.2.4",
|
"npm:react-dom@^19.2.4": "19.2.4_react@19.2.4",
|
||||||
@@ -952,6 +953,16 @@
|
|||||||
"flatted@3.4.2": {
|
"flatted@3.4.2": {
|
||||||
"integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA=="
|
"integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA=="
|
||||||
},
|
},
|
||||||
|
"frimousse@0.3.0_react@19.2.4_typescript@5.9.3": {
|
||||||
|
"integrity": "sha512-kO6LMoKY/cLAYEhXXtqLRaLIE6L/DagpFPrUZaLv3LsUa1/8Iza3HhwZcgN8eZ+weXnhv69eoclNUPohcCa/IQ==",
|
||||||
|
"dependencies": [
|
||||||
|
"react",
|
||||||
|
"typescript"
|
||||||
|
],
|
||||||
|
"optionalPeers": [
|
||||||
|
"typescript"
|
||||||
|
]
|
||||||
|
},
|
||||||
"fsevents@2.3.3": {
|
"fsevents@2.3.3": {
|
||||||
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
||||||
"os": ["darwin"],
|
"os": ["darwin"],
|
||||||
@@ -2050,6 +2061,7 @@
|
|||||||
"npm:eslint-plugin-react-hooks@^7.0.1",
|
"npm:eslint-plugin-react-hooks@^7.0.1",
|
||||||
"npm:eslint-plugin-react-refresh@~0.5.2",
|
"npm:eslint-plugin-react-refresh@~0.5.2",
|
||||||
"npm:eslint@^9.39.4",
|
"npm:eslint@^9.39.4",
|
||||||
|
"npm:frimousse@0.3",
|
||||||
"npm:globals@^17.4.0",
|
"npm:globals@^17.4.0",
|
||||||
"npm:react-dom@^19.2.4",
|
"npm:react-dom@^19.2.4",
|
||||||
"npm:react-markdown@^10.1.0",
|
"npm:react-markdown@^10.1.0",
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"@deno/vite-plugin": "^1.0.6",
|
"@deno/vite-plugin": "^1.0.6",
|
||||||
"@types/react": "^19.2.14",
|
"@types/react": "^19.2.14",
|
||||||
"@vitejs/plugin-react": "^6.0.1",
|
"@vitejs/plugin-react": "^6.0.1",
|
||||||
|
"frimousse": "^0.3.0",
|
||||||
"react": "^19.2.4",
|
"react": "^19.2.4",
|
||||||
"react-dom": "^19.2.4",
|
"react-dom": "^19.2.4",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
|
|||||||
72
src/App.css
72
src/App.css
@@ -2722,8 +2722,8 @@ body.has-player .fab-new {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.comment-replies {
|
.comment-replies {
|
||||||
padding-left: 1.25rem;
|
padding-left: max(0.4rem, calc(1.25rem - var(--depth, 0) * 0.1rem));
|
||||||
margin-left: 1.1rem;
|
margin-left: max(0.25rem, calc(1.1rem - var(--depth, 0) * 0.09rem));
|
||||||
margin-top: 0.35rem;
|
margin-top: 0.35rem;
|
||||||
border-left: 2px solid
|
border-left: 2px solid
|
||||||
color-mix(in srgb, var(--color-accent) 30%, transparent);
|
color-mix(in srgb, var(--color-accent) 30%, transparent);
|
||||||
@@ -3193,6 +3193,74 @@ body.has-player .fab-new {
|
|||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
color: var(--color-text);
|
color: var(--color-text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Emoji picker (frimousse) ── */
|
||||||
|
.emoji-picker-float {
|
||||||
|
position: absolute;
|
||||||
|
bottom: calc(100% + 4px);
|
||||||
|
left: 0;
|
||||||
|
z-index: 201;
|
||||||
|
width: 320px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.18);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emoji-picker-float input {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border: none;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
background: var(--color-bg);
|
||||||
|
color: var(--color-text);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.emoji-picker-float input::placeholder {
|
||||||
|
color: var(--color-text-muted, #888);
|
||||||
|
}
|
||||||
|
/* frimousse uses bare attributes (no data- prefix) */
|
||||||
|
.emoji-picker-float [frimousse-viewport] {
|
||||||
|
max-height: 220px;
|
||||||
|
/* frimousse already sets overflow-y: auto inline */
|
||||||
|
}
|
||||||
|
.emoji-picker-float [frimousse-category-header] {
|
||||||
|
padding: 4px 8px 2px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text-muted, #888);
|
||||||
|
background: var(--color-surface);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
}
|
||||||
|
.emoji-picker-float [frimousse-emoji] {
|
||||||
|
flex: 0 0 calc(100% / var(--frimousse-list-columns, 9));
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 4px 0;
|
||||||
|
font-size: 1.35em;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
border-radius: 4px;
|
||||||
|
transition: background 0.1s;
|
||||||
|
}
|
||||||
|
.emoji-picker-float [frimousse-emoji]:hover,
|
||||||
|
.emoji-picker-float [frimousse-emoji][data-active] {
|
||||||
|
background: var(--color-bg);
|
||||||
|
}
|
||||||
|
.emoji-picker-float [frimousse-loading],
|
||||||
|
.emoji-picker-float [frimousse-empty] {
|
||||||
|
display: block;
|
||||||
|
padding: 16px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--color-text-muted, #888);
|
||||||
|
}
|
||||||
|
|
||||||
.notif-icon--mention {
|
.notif-icon--mention {
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
font-family: monospace;
|
font-family: monospace;
|
||||||
|
|||||||
@@ -6,18 +6,22 @@ interface AvatarProps {
|
|||||||
username: string;
|
username: string;
|
||||||
hasAvatar: boolean;
|
hasAvatar: boolean;
|
||||||
size?: number;
|
size?: number;
|
||||||
|
version?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Avatar(
|
export function Avatar(
|
||||||
{ userId, username, hasAvatar, size = 36 }: AvatarProps,
|
{ userId, username, hasAvatar, size = 36, version }: AvatarProps,
|
||||||
) {
|
) {
|
||||||
const [imgFailed, setImgFailed] = useState(false);
|
const [imgFailed, setImgFailed] = useState(false);
|
||||||
const sizeStyle = { width: size, height: size };
|
const sizeStyle = { width: size, height: size };
|
||||||
|
|
||||||
if (hasAvatar && !imgFailed) {
|
if (hasAvatar && !imgFailed) {
|
||||||
|
const src = version
|
||||||
|
? `${API_URL}/api/avatars/${userId}?v=${version}`
|
||||||
|
: `${API_URL}/api/avatars/${userId}`;
|
||||||
return (
|
return (
|
||||||
<img
|
<img
|
||||||
src={`${API_URL}/api/avatars/${userId}`}
|
src={src}
|
||||||
alt={username}
|
alt={username}
|
||||||
title={username}
|
title={username}
|
||||||
style={sizeStyle}
|
style={sizeStyle}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useRef, useState } from "react";
|
import React, { useRef, useState } from "react";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import { API_URL } from "../config/api.ts";
|
import { API_URL } from "../config/api.ts";
|
||||||
import type { Comment, RawComment, User } from "../model.ts";
|
import type { Comment, RawComment, User } from "../model.ts";
|
||||||
@@ -31,8 +31,6 @@ function buildTree(comments: Comment[]): Map<string, Comment[]> {
|
|||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_INDENT_DEPTH = 6;
|
|
||||||
|
|
||||||
interface CommentNodeProps {
|
interface CommentNodeProps {
|
||||||
comment: Comment;
|
comment: Comment;
|
||||||
tree: Map<string, Comment[]>;
|
tree: Map<string, Comment[]>;
|
||||||
@@ -161,9 +159,7 @@ function CommentNode({
|
|||||||
{children.length > 0 && (
|
{children.length > 0 && (
|
||||||
<ul
|
<ul
|
||||||
className="comment-replies"
|
className="comment-replies"
|
||||||
style={depth >= MAX_INDENT_DEPTH
|
style={{ "--depth": depth } as React.CSSProperties}
|
||||||
? { paddingLeft: 0, marginLeft: 0, borderLeft: "none" }
|
|
||||||
: undefined}
|
|
||||||
>
|
>
|
||||||
{children.map((child) => (
|
{children.map((child) => (
|
||||||
<CommentNode
|
<CommentNode
|
||||||
@@ -357,9 +353,7 @@ function CommentNode({
|
|||||||
{children.length > 0 && (
|
{children.length > 0 && (
|
||||||
<ul
|
<ul
|
||||||
className="comment-replies"
|
className="comment-replies"
|
||||||
style={depth >= MAX_INDENT_DEPTH
|
style={{ "--depth": depth } as React.CSSProperties}
|
||||||
? { paddingLeft: 0, marginLeft: 0, borderLeft: "none" }
|
|
||||||
: undefined}
|
|
||||||
>
|
>
|
||||||
{children.map((child) => (
|
{children.map((child) => (
|
||||||
<CommentNode
|
<CommentNode
|
||||||
|
|||||||
@@ -21,8 +21,7 @@ import { PlaylistCreateForm } from "./PlaylistCreateForm.tsx";
|
|||||||
import { ErrorCard } from "./ErrorCard.tsx";
|
import { ErrorCard } from "./ErrorCard.tsx";
|
||||||
import { FileDropZone } from "./FileDropZone.tsx";
|
import { FileDropZone } from "./FileDropZone.tsx";
|
||||||
import { friendlyFetchError } from "../utils/apiError.ts";
|
import { friendlyFetchError } from "../utils/apiError.ts";
|
||||||
|
import { MAX_FILE_SIZE } from "../config/upload.ts";
|
||||||
const MAX_FILE_SIZE = 50 * 1024 * 1024;
|
|
||||||
|
|
||||||
type Mode = "url" | "file";
|
type Mode = "url" | "file";
|
||||||
type Phase = "create" | "playlist";
|
type Phase = "create" | "playlist";
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
|
import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
|
||||||
|
import { EmojiPicker } from "frimousse";
|
||||||
import { MentionDropdown } from "./MentionDropdown.tsx";
|
import { MentionDropdown } from "./MentionDropdown.tsx";
|
||||||
import { useMentionAutocomplete } from "../hooks/useMentionAutocomplete.ts";
|
import { useMentionAutocomplete } from "../hooks/useMentionAutocomplete.ts";
|
||||||
|
import { useEmojiTrigger } from "../hooks/useEmojiTrigger.ts";
|
||||||
|
|
||||||
export interface TextEditorHandle {
|
export interface TextEditorHandle {
|
||||||
focus(): void;
|
focus(): void;
|
||||||
@@ -34,6 +36,8 @@ export const TextEditor = forwardRef<TextEditorHandle, TextEditorProps>(
|
|||||||
ref,
|
ref,
|
||||||
) {
|
) {
|
||||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const emojiViewportRef = useRef<HTMLDivElement>(null);
|
||||||
|
const emojiSearchRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
useImperativeHandle(ref, () => ({
|
||||||
focus: () => textareaRef.current?.focus(),
|
focus: () => textareaRef.current?.focus(),
|
||||||
@@ -48,6 +52,20 @@ export const TextEditor = forwardRef<TextEditorHandle, TextEditorProps>(
|
|||||||
handleMentionSelect,
|
handleMentionSelect,
|
||||||
} = useMentionAutocomplete(value, onChange, textareaRef);
|
} = useMentionAutocomplete(value, onChange, textareaRef);
|
||||||
|
|
||||||
|
const {
|
||||||
|
emojiOpen,
|
||||||
|
emojiQuery,
|
||||||
|
detectEmojiTrigger,
|
||||||
|
handleEmojiSelect,
|
||||||
|
closeEmoji,
|
||||||
|
} = useEmojiTrigger(value, onChange, textareaRef);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (emojiOpen) {
|
||||||
|
emojiViewportRef.current?.focus({ preventScroll: true });
|
||||||
|
}
|
||||||
|
}, [emojiOpen]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!autoResize) return;
|
if (!autoResize) return;
|
||||||
const el = textareaRef.current;
|
const el = textareaRef.current;
|
||||||
@@ -61,7 +79,10 @@ export const TextEditor = forwardRef<TextEditorHandle, TextEditorProps>(
|
|||||||
<textarea
|
<textarea
|
||||||
ref={textareaRef}
|
ref={textareaRef}
|
||||||
value={value}
|
value={value}
|
||||||
onChange={handleMentionChange}
|
onChange={(e) => {
|
||||||
|
handleMentionChange(e);
|
||||||
|
detectEmojiTrigger(e.target.value, e.target.selectionStart ?? 0);
|
||||||
|
}}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
handleMentionKeyDown(e);
|
handleMentionKeyDown(e);
|
||||||
if (!e.defaultPrevented) onKeyDown?.(e);
|
if (!e.defaultPrevented) onKeyDown?.(e);
|
||||||
@@ -79,6 +100,61 @@ export const TextEditor = forwardRef<TextEditorHandle, TextEditorProps>(
|
|||||||
onSelect={handleMentionSelect}
|
onSelect={handleMentionSelect}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{emojiOpen && (
|
||||||
|
<div
|
||||||
|
className="emoji-picker-float"
|
||||||
|
onKeyDownCapture={(e) => {
|
||||||
|
if (e.key === "Escape") {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
closeEmoji();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
// Redirect printable characters to the search input when it
|
||||||
|
// doesn't already have focus (e.g. while navigating with arrows)
|
||||||
|
if (
|
||||||
|
e.key.length === 1 &&
|
||||||
|
!e.ctrlKey && !e.metaKey && !e.altKey &&
|
||||||
|
document.activeElement !== emojiSearchRef.current
|
||||||
|
) {
|
||||||
|
const search = emojiSearchRef.current;
|
||||||
|
if (search) {
|
||||||
|
e.preventDefault();
|
||||||
|
search.focus({ preventScroll: true });
|
||||||
|
// Inject the character via the native setter so React's
|
||||||
|
// synthetic onChange fires and frimousse updates its search state
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(
|
||||||
|
globalThis.HTMLInputElement.prototype,
|
||||||
|
"value",
|
||||||
|
)?.set;
|
||||||
|
setter?.call(search, search.value + e.key);
|
||||||
|
search.dispatchEvent(new Event("input", { bubbles: true }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<EmojiPicker.Root
|
||||||
|
onEmojiSelect={(e) => handleEmojiSelect(e.emoji)}
|
||||||
|
>
|
||||||
|
<EmojiPicker.Search
|
||||||
|
ref={emojiSearchRef}
|
||||||
|
defaultValue={emojiQuery}
|
||||||
|
placeholder="Search emoji…"
|
||||||
|
/>
|
||||||
|
<EmojiPicker.Viewport
|
||||||
|
ref={emojiViewportRef}
|
||||||
|
// tabIndex={-1} makes the div programmatically focusable so
|
||||||
|
// frimousse's onFocusCapture can detect it and arm arrow-key nav
|
||||||
|
tabIndex={-1}
|
||||||
|
>
|
||||||
|
<EmojiPicker.Loading>Loading…</EmojiPicker.Loading>
|
||||||
|
<EmojiPicker.Empty>No emoji found.</EmojiPicker.Empty>
|
||||||
|
<EmojiPicker.List />
|
||||||
|
</EmojiPicker.Viewport>
|
||||||
|
</EmojiPicker.Root>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|||||||
1
src/config/upload.ts
Normal file
1
src/config/upload.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
|
||||||
79
src/hooks/useEmojiTrigger.ts
Normal file
79
src/hooks/useEmojiTrigger.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import { type RefObject, useCallback, useRef, useState } from "react";
|
||||||
|
|
||||||
|
// Trigger: ':' not preceded by a word character, followed by 1+ word chars
|
||||||
|
const TRIGGER_RE = /(?<![A-Za-z0-9_]):([A-Za-z0-9_+\-]{1,})$/;
|
||||||
|
|
||||||
|
interface EmojiTriggerState {
|
||||||
|
open: boolean;
|
||||||
|
query: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useEmojiTrigger(
|
||||||
|
value: string,
|
||||||
|
onChange: (value: string) => void,
|
||||||
|
textareaRef: RefObject<HTMLTextAreaElement | null>,
|
||||||
|
) {
|
||||||
|
const [state, setState] = useState<EmojiTriggerState>({
|
||||||
|
open: false,
|
||||||
|
query: "",
|
||||||
|
});
|
||||||
|
// Saved positions at the moment the trigger was detected
|
||||||
|
const triggerStartRef = useRef(0);
|
||||||
|
const triggerCursorRef = useRef(0);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call this from the textarea's onChange (alongside the mention handler).
|
||||||
|
* It receives the new value and cursor position already read from the event.
|
||||||
|
*/
|
||||||
|
const detectEmojiTrigger = useCallback(
|
||||||
|
(newValue: string, cursor: number) => {
|
||||||
|
const textBefore = newValue.slice(0, cursor);
|
||||||
|
const match = TRIGGER_RE.exec(textBefore);
|
||||||
|
if (match) {
|
||||||
|
triggerStartRef.current = match.index;
|
||||||
|
triggerCursorRef.current = cursor;
|
||||||
|
setState({ open: true, query: match[1] });
|
||||||
|
} else {
|
||||||
|
setState((s) => s.open ? { open: false, query: "" } : s);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when frimousse fires onEmojiSelect.
|
||||||
|
* Replaces the ':query' text with the selected emoji.
|
||||||
|
*/
|
||||||
|
const handleEmojiSelect = useCallback(
|
||||||
|
(native: string) => {
|
||||||
|
const start = triggerStartRef.current;
|
||||||
|
const cursor = triggerCursorRef.current;
|
||||||
|
const newValue = value.slice(0, start) + native + " " +
|
||||||
|
value.slice(cursor);
|
||||||
|
onChange(newValue);
|
||||||
|
setState({ open: false, query: "" });
|
||||||
|
const newPos = start + native.length + 1; // +1 for trailing space
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
const el = textareaRef.current;
|
||||||
|
if (el) {
|
||||||
|
el.focus();
|
||||||
|
el.setSelectionRange(newPos, newPos);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[value, onChange, textareaRef],
|
||||||
|
);
|
||||||
|
|
||||||
|
const closeEmoji = useCallback(() => {
|
||||||
|
setState({ open: false, query: "" });
|
||||||
|
requestAnimationFrame(() => textareaRef.current?.focus());
|
||||||
|
}, [textareaRef]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
emojiOpen: state.open,
|
||||||
|
emojiQuery: state.query,
|
||||||
|
detectEmojiTrigger,
|
||||||
|
handleEmojiSelect,
|
||||||
|
closeEmoji,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -314,6 +314,7 @@ export interface OnlineUser {
|
|||||||
userId: string;
|
userId: string;
|
||||||
username: string;
|
username: string;
|
||||||
hasAvatar: boolean;
|
hasAvatar: boolean;
|
||||||
|
avatarVersion?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WelcomeMessage {
|
export interface WelcomeMessage {
|
||||||
|
|||||||
@@ -13,8 +13,7 @@ import { TextEditor } from "../components/TextEditor.tsx";
|
|||||||
import { ErrorCard } from "../components/ErrorCard.tsx";
|
import { ErrorCard } from "../components/ErrorCard.tsx";
|
||||||
import { FileDropZone } from "../components/FileDropZone.tsx";
|
import { FileDropZone } from "../components/FileDropZone.tsx";
|
||||||
import { friendlyFetchError } from "../utils/apiError.ts";
|
import { friendlyFetchError } from "../utils/apiError.ts";
|
||||||
|
import { MAX_FILE_SIZE } from "../config/upload.ts";
|
||||||
const MAX_FILE_SIZE = 50 * 1024 * 1024;
|
|
||||||
|
|
||||||
type Mode = "url" | "file";
|
type Mode = "url" | "file";
|
||||||
type DumpCreateState =
|
type DumpCreateState =
|
||||||
|
|||||||
@@ -555,6 +555,7 @@ export function Index() {
|
|||||||
username={u.username}
|
username={u.username}
|
||||||
hasAvatar={u.hasAvatar}
|
hasAvatar={u.hasAvatar}
|
||||||
size={32}
|
size={32}
|
||||||
|
version={u.avatarVersion}
|
||||||
/>
|
/>
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -503,11 +503,8 @@ export function UserPublicProfile() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setState((prev) =>
|
setState((prev) =>
|
||||||
prev.status === "loaded"
|
prev.status === "loaded" && body.data
|
||||||
? {
|
? { ...prev, user: deserializeUser(body.data) }
|
||||||
...prev,
|
|
||||||
user: { ...prev.user, avatarMime: body.data?.avatarMime },
|
|
||||||
}
|
|
||||||
: prev
|
: prev
|
||||||
);
|
);
|
||||||
} catch {
|
} catch {
|
||||||
@@ -561,6 +558,7 @@ export function UserPublicProfile() {
|
|||||||
username={profileUser.username}
|
username={profileUser.username}
|
||||||
hasAvatar={!!profileUser.avatarMime}
|
hasAvatar={!!profileUser.avatarMime}
|
||||||
size={72}
|
size={72}
|
||||||
|
version={profileUser.updatedAt?.getTime()}
|
||||||
/>
|
/>
|
||||||
{isOwnProfile && (
|
{isOwnProfile && (
|
||||||
<label className="avatar-change-overlay" title="Change avatar">
|
<label className="avatar-change-overlay" title="Change avatar">
|
||||||
|
|||||||
Reference in New Issue
Block a user