feat(chat,board): file/image attachments on chat, board threads and comments

チャット・掲示板(スレッド/コメント)へファイル/画像添付を追加。

- lib/db/migrations/002_attachments.sql: attachments テーブル + file_assets.source 列
- repositories/AttachmentRepository + services/AttachmentService: 添付紐付け(プロジェクト/アップロード者チェック)
- FileStorageService.uploadForAttachment: 通知/SSE/アクティビティを行わない添付専用アップロード(source='attachment')
- ChatService/BoardService: fileIds 受理・添付紐付け・履歴/詳細表示・削除クリーンアップ(トランザクション)
- API: POST /attachments + chat/board の fileIds 受理
- UI: AttachmentList(画像サムネイル+Lightbox/ダウンロード) + AttachmentPicker(複数アップロード・送信中は送信不可) をチャット/スレッド/コメントに統合
- 添付ファイルは既存の /api/files/[fileId]/download(権限チェック済)で配信
This commit is contained in:
Ken Yasue
2026-06-25 10:07:02 +02:00
parent c747978f3d
commit 25d800a529
31 changed files with 1640 additions and 102 deletions

View File

@ -1,7 +1,9 @@
'use client';
import { useState, type FormEvent } from 'react';
import { useRef, useState, type FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import { AttachmentPicker } from '@/components/files/AttachmentPicker';
import type { AttachmentPickerHandle } from '@/components/files/AttachmentPicker';
export function CommentForm({
projectId,
@ -11,25 +13,29 @@ export function CommentForm({
threadId: number;
}) {
const router = useRouter();
const pickerRef = useRef<AttachmentPickerHandle>(null);
const [bodyMd, setBodyMd] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [pickerLoading, setPickerLoading] = useState(false);
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setLoading(true);
setError(null);
const fileIds = pickerRef.current?.getFileIds() ?? [];
const res = await fetch(
`/api/projects/${projectId}/board/threads/${threadId}/comments`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ bodyMd }),
body: JSON.stringify({ bodyMd, fileIds }),
}
);
setLoading(false);
if (res.ok) {
setBodyMd('');
pickerRef.current?.clear();
router.refresh();
} else {
const b = (await res.json().catch(() => null)) as {
@ -48,6 +54,11 @@ export function CommentForm({
className="min-h-[80px] w-full rounded border px-3 py-2"
required
/>
<AttachmentPicker
ref={pickerRef}
projectId={projectId}
onLoadingChange={setPickerLoading}
/>
{error && (
<p className="text-sm text-red-600" role="alert">
{error}
@ -55,7 +66,7 @@ export function CommentForm({
)}
<button
type="submit"
disabled={loading}
disabled={loading || pickerLoading}
className="rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
>
{loading ? '投稿中...' : 'コメント投稿'}

View File

@ -1,7 +1,9 @@
'use client';
import { useState, type FormEvent } from 'react';
import { useRef, useState, type FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import { AttachmentPicker } from '@/components/files/AttachmentPicker';
import type { AttachmentPickerHandle } from '@/components/files/AttachmentPicker';
const CATEGORIES = [
{ value: '', label: 'なし' },
@ -16,16 +18,19 @@ const CATEGORIES = [
export function ThreadForm({ projectId }: { projectId: number }) {
const router = useRouter();
const pickerRef = useRef<AttachmentPickerHandle>(null);
const [title, setTitle] = useState('');
const [bodyMd, setBodyMd] = useState('');
const [category, setCategory] = useState('');
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [pickerLoading, setPickerLoading] = useState(false);
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setLoading(true);
setError(null);
const fileIds = pickerRef.current?.getFileIds() ?? [];
const res = await fetch(`/api/projects/${projectId}/board/threads`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@ -33,11 +38,13 @@ export function ThreadForm({ projectId }: { projectId: number }) {
title,
bodyMd,
category: category || undefined,
fileIds,
}),
});
setLoading(false);
if (res.ok) {
const data = (await res.json()) as { thread: { id: number } };
pickerRef.current?.clear();
router.push(`/projects/${projectId}/board/${data.thread.id}`);
router.refresh();
} else {
@ -82,6 +89,11 @@ export function ThreadForm({ projectId }: { projectId: number }) {
className="min-h-[120px] w-full rounded border px-3 py-2"
required
/>
<AttachmentPicker
ref={pickerRef}
projectId={projectId}
onLoadingChange={setPickerLoading}
/>
{error && (
<p className="text-sm text-red-600" role="alert">
{error}
@ -89,7 +101,7 @@ export function ThreadForm({ projectId }: { projectId: number }) {
)}
<button
type="submit"
disabled={loading}
disabled={loading || pickerLoading}
className="rounded bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-700 disabled:opacity-50"
>
{loading ? '作成中...' : 'スレッド作成'}

View File

@ -1,7 +1,10 @@
'use client';
import { useEffect, useState, type FormEvent } from 'react';
import type { ChatMessage } from '@/lib/types';
import { useEffect, useRef, useState, type FormEvent } from 'react';
import type { ChatMessageWithAttachments } from '@/lib/types';
import { AttachmentPicker } from '@/components/files/AttachmentPicker';
import type { AttachmentPickerHandle } from '@/components/files/AttachmentPicker';
import { AttachmentList } from '@/components/files/AttachmentList';
interface ChatWindowProps {
projectId: number;
@ -9,16 +12,20 @@ interface ChatWindowProps {
}
export function ChatWindow({ projectId, userName }: ChatWindowProps) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [messages, setMessages] = useState<ChatMessageWithAttachments[]>([]);
const [input, setInput] = useState('');
const [error, setError] = useState<string | null>(null);
const [sending, setSending] = useState(false);
const [pickerLoading, setPickerLoading] = useState(false);
const pickerRef = useRef<AttachmentPickerHandle>(null);
// 履歴取得
useEffect(() => {
fetch(`/api/projects/${projectId}/chat/messages`)
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (data?.items) setMessages(data.items as ChatMessage[]);
if (data?.items)
setMessages(data.items as ChatMessageWithAttachments[]);
})
.catch(() => undefined);
}, [projectId]);
@ -30,7 +37,10 @@ export function ChatWindow({ projectId, userName }: ChatWindowProps) {
try {
const parsed = JSON.parse(event.data) as {
type: string;
data: { message?: ChatMessage; id?: number };
data: {
message?: ChatMessageWithAttachments;
id?: number;
};
};
if (parsed.type === 'chat.message.created' && parsed.data.message) {
setMessages((prev) =>
@ -42,9 +52,12 @@ export function ChatWindow({ projectId, userName }: ChatWindowProps) {
parsed.type === 'chat.message.updated' &&
parsed.data.message
) {
// 編集イベントは本文のみ更新し、添付は既存のものを保持する
setMessages((prev) =>
prev.map((m) =>
m.id === parsed.data.message!.id ? parsed.data.message! : m
m.id === parsed.data.message!.id
? { ...m, ...parsed.data.message!, attachments: m.attachments }
: m
)
);
} else if (parsed.type === 'chat.message.deleted' && parsed.data.id) {
@ -61,13 +74,17 @@ export function ChatWindow({ projectId, userName }: ChatWindowProps) {
event.preventDefault();
if (!input.trim()) return;
setError(null);
setSending(true);
const fileIds = pickerRef.current?.getFileIds() ?? [];
const res = await fetch(`/api/projects/${projectId}/chat/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: input }),
body: JSON.stringify({ body: input, fileIds }),
});
setSending(false);
if (res.ok) {
setInput('');
pickerRef.current?.clear();
} else {
const b = (await res.json().catch(() => null)) as {
error?: { message?: string };
@ -95,6 +112,11 @@ export function ChatWindow({ projectId, userName }: ChatWindowProps) {
>
{m.body}
</span>
{m.attachments && m.attachments.length > 0 && (
<div className="max-w-[80%]">
<AttachmentList attachments={m.attachments} />
</div>
)}
<span className="mt-0.5 text-xs text-gray-400">
{m.createdAt}
</span>
@ -104,24 +126,32 @@ export function ChatWindow({ projectId, userName }: ChatWindowProps) {
</div>
<form
onSubmit={onSend}
className="flex gap-2 border-t p-3"
className="space-y-2 border-t p-3"
data-testid="chat-form"
>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="メッセージを入力(@email でメンション)"
className="flex-1 rounded border px-3 py-2"
data-testid="chat-input"
<AttachmentPicker
ref={pickerRef}
projectId={projectId}
onLoadingChange={setPickerLoading}
/>
<button
type="submit"
className="rounded bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-700"
data-testid="chat-send"
>
</button>
<div className="flex gap-2">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="メッセージを入力(@email でメンション)"
className="flex-1 rounded border px-3 py-2"
data-testid="chat-input"
/>
<button
type="submit"
disabled={sending || pickerLoading}
className="rounded bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-700 disabled:opacity-50"
data-testid="chat-send"
>
{sending ? '送信中...' : '送信'}
</button>
</div>
</form>
{error && (
<p className="px-3 pb-2 text-sm text-red-600" role="alert">

View File

@ -0,0 +1,93 @@
'use client';
import { useEffect, useState } from 'react';
import type { AttachmentView } from '@/lib/types';
/**
* 添付ファイル一覧表示。画像はサムネイル(クリックでLightbox)、
* それ以外はダウンロードリンク。チャット/掲示板で共通利用。
*/
export function AttachmentList({
attachments,
}: {
attachments: AttachmentView[];
}) {
const [lightbox, setLightbox] = useState<AttachmentView | null>(null);
useEffect(() => {
if (!lightbox) return;
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') setLightbox(null);
}
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [lightbox]);
if (attachments.length === 0) return null;
return (
<>
<ul className="mt-1 flex flex-wrap gap-2" data-testid="attachment-list">
{attachments.map((a) => {
const url = `/api/files/${a.fileId}/download`;
const isImage = a.mimeType.startsWith('image/');
return (
<li
key={a.id}
className="overflow-hidden rounded border bg-gray-50"
data-testid={`attachment-${a.id}`}
>
{isImage ? (
<button
type="button"
onClick={() => setLightbox(a)}
className="block"
aria-label={`画像 ${a.originalName} を開く`}
>
<img
src={url}
alt={a.originalName}
className="h-20 w-20 object-cover"
/>
</button>
) : (
<a
href={url}
className="flex h-20 w-28 flex-col items-center justify-center px-2 text-center text-xs text-blue-600 hover:underline"
>
<span className="mb-1">📎</span>
<span className="w-full truncate" title={a.originalName}>
{a.originalName}
</span>
</a>
)}
</li>
);
})}
</ul>
{lightbox && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
onClick={() => setLightbox(null)}
data-testid="attachment-lightbox"
>
<button
type="button"
onClick={() => setLightbox(null)}
className="absolute right-4 top-4 rounded bg-black/50 px-2 py-0.5 text-2xl text-white hover:bg-black/70"
aria-label="閉じる"
>
×
</button>
<img
src={`/api/files/${lightbox.fileId}/download`}
alt={lightbox.originalName}
className="max-h-full max-w-full rounded"
onClick={(e) => e.stopPropagation()}
/>
</div>
)}
</>
);
}

View File

@ -0,0 +1,163 @@
'use client';
import {
forwardRef,
useImperativeHandle,
useRef,
useState,
type ChangeEvent,
} from 'react';
export interface AttachmentPickerHandle {
getFileIds: () => number[];
clear: () => void;
}
interface PickedFile {
fileId: number;
originalName: string;
mimeType: string;
}
/**
* チャット/掲示板用の添付ファイルピッカー。
* 選択したファイルを添付用エンドポイントへアップロードし、
* 親フォームは送信時に getFileIds() でファイルIDを取り出す。
* 送信完了後は clear() で状態をリセットする。
*/
export const AttachmentPicker = forwardRef<
AttachmentPickerHandle,
{ projectId: number; onLoadingChange?: (loading: boolean) => void }
>(function AttachmentPicker({ projectId, onLoadingChange }, ref) {
const [files, setFiles] = useState<PickedFile[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
function reportLoading(next: boolean) {
setLoading(next);
onLoadingChange?.(next);
}
useImperativeHandle(
ref,
() => ({
getFileIds: () => files.map((f) => f.fileId),
clear: () => {
setFiles([]);
setError(null);
if (inputRef.current) inputRef.current.value = '';
},
}),
[files]
);
async function onFile(event: ChangeEvent<HTMLInputElement>) {
const selected = Array.from(event.target.files ?? []);
if (selected.length === 0) return;
reportLoading(true);
setError(null);
try {
const uploaded: PickedFile[] = [];
for (const f of selected) {
const form = new FormData();
form.append('file', f);
const res = await fetch(`/api/projects/${projectId}/attachments`, {
method: 'POST',
body: form,
});
if (!res.ok) {
const b = (await res.json().catch(() => null)) as {
error?: { message?: string };
} | null;
throw new Error(b?.error?.message ?? 'アップロードに失敗しました');
}
const data = (await res.json()) as {
file: { id: number; originalName: string; mimeType: string };
};
uploaded.push({
fileId: data.file.id,
originalName: data.file.originalName,
mimeType: data.file.mimeType,
});
}
setFiles((prev) => [...prev, ...uploaded]);
} catch (err) {
setError(
err instanceof Error ? err.message : 'アップロードに失敗しました'
);
} finally {
reportLoading(false);
if (inputRef.current) inputRef.current.value = '';
}
}
function removeFile(fileId: number) {
setFiles((prev) => prev.filter((f) => f.fileId !== fileId));
}
return (
<div className="space-y-2" data-testid="attachment-picker">
<label className="inline-flex cursor-pointer items-center gap-1 rounded border bg-white px-3 py-1 text-sm text-gray-600 hover:bg-gray-100">
📎
<input
ref={inputRef}
type="file"
multiple
onChange={onFile}
disabled={loading}
className="hidden"
data-testid="attachment-input"
/>
</label>
{loading && (
<p className="text-xs text-gray-500" data-testid="attachment-loading">
...
</p>
)}
{error && (
<p className="text-xs text-red-600" role="alert">
{error}
</p>
)}
{files.length > 0 && (
<ul className="flex flex-wrap gap-2">
{files.map((f) => {
const isImage = f.mimeType.startsWith('image/');
const url = `/api/files/${f.fileId}/download`;
return (
<li
key={f.fileId}
className="relative overflow-hidden rounded border bg-gray-50"
data-testid={`attachment-picked-${f.fileId}`}
>
{isImage ? (
<img
src={url}
alt={f.originalName}
className="h-16 w-16 object-cover"
/>
) : (
<span className="flex h-16 w-24 items-center justify-center px-1 text-center text-[10px] text-blue-600">
<span className="truncate" title={f.originalName}>
{f.originalName}
</span>
</span>
)}
<button
type="button"
onClick={() => removeFile(f.fileId)}
className="absolute right-0 top-0 rounded-bl bg-black/50 px-1 text-xs text-white hover:bg-black/70"
aria-label={`${f.originalName} を削除`}
data-testid={`attachment-remove-${f.fileId}`}
>
×
</button>
</li>
);
})}
</ul>
)}
</div>
);
});