Compare commits

...

18 Commits

Author SHA1 Message Date
hyungi 0cbb188375 feat(ui): DS 웹 UI 세이지 재설계 5페이지 일괄 배포 (대시보드·문서·뉴스·digest·메모)
goal 1~4 + digest. 적대 리뷰(15-agent) 확정 결함 반영본. frontend-only.
원본 커밋 = gitea feat/ui-sage-all a1a46f2. eid 마이그레이션 301~305 워킹트리
격리(미티게이션) 미접촉.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 11:12:17 +00:00
hyungi 3a865978af feat(ui): 홈 대시보드 데일리 홈 cockpit 재설계 (안1 골격+안2 위젯+안3 분포)
확정 시안 dashboard-sage-3 의 권장 합성(안1 데일리 홈 골격 + 안2 검토/파이프라인
위젯 + 안3 도메인 분포 한 줄)으로 콘텐츠 재구조화. F1 세이지 테마 위 레이아웃 개편.
- 인사 헤더 + 오늘 요약 띠(검토 대기 + 디제스트 톱 + 스탯 띠)
- 2열: 좌(빠른 캡처·활동 타임라인) / 우(학습·도메인 분포+파이프라인 칩·고정)
- digest/도메인 분포는 기존 엔드포인트 wiring(백엔드 변경 0), 학습 streak는 링크형 degrade

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 07:57:59 +00:00
hyungi 4001949d78 fix(study): 복습함 탭 전환 시 선택 초기화 (탭별 독립 선택)
검토 지적: 탭 바꿔도 selected 잔존 → 탭별 독립 선택으로 setTab 에서 selected={} 리셋. (선택 복습은 이미 현재 탭 shown 기준이라 데이터 오염은 없었고 UX 정합 개선.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 07:22:36 +00:00
hyungi af07fb427b feat(study): 복습함(B4 v1) — 오늘 할 일/미확인 2탭 + 멀티셀렉트 선택 복습
/study/review-box: GET /study-cards/due(review_stage) 를 2탭 분리(오늘 할 일=review_stage 보유 / 미확인=review_stage null 신규). 카드 멀티셀렉트 → pendingReviewCards store 로 cards-study 복습 세션에 선택분 전달(백엔드 세션 X = eid contention 중 fastapi 무재빌드). '이 탭 전체 복습'도. 완료 탭은 졸업카드 엔드포인트 필요라 비활성('추후'). 허브에 복습함 진입 카드.
- 신규 store /stores/studySession.ts(pendingReviewCards). cards-study startReview 가 consume. 전부 frontend-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 07:18:13 +00:00
hyungi 50b070fcd3 polish(study): 암기카드 학습 문구 다듬기 + '이 카드 이상해요' 버튼 강조
시안 합의본 문구 실제 반영: 탭하면 정답이 보여요 / 봤어요·다음 / 오늘 복습을 마쳤어요 / 애매하거나 몰랐던 카드는 내일 다시 만나요 / 공부로 돌아가기 / 앞—떠올리기 / 평가 sublabel 내일 다시·N일 뒤. 키보드 힌트(Space·Enter)는 sm:inline(데스크탑만). 플래그 버튼=흐린 텍스트→테두리 칩(hover 경고색).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 07:07:02 +00:00
hyungi 56d1caf1c8 fix(study): 검수함 카드 마크다운+수식 렌더 — 근거/앞면/정답
cards-review view 모드가 cue/cloze/fact/근거를 평문으로 뿌려 표·**굵게**·수식이 raw 노출. cards-study와 동일하게 renderMathMarkdown(근거 블록)·renderMathMarkdownInline(앞면·정답) 적용. 편집모드 textarea는 raw 유지.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 06:43:10 +00:00
hyungi c0772bc21c fix(study): 검수함 each_key_duplicate 크래시 — 자료(수동) 그룹 null 키 중복 해소
manual 카드 그룹은 source_question_id=null 이라 자료가 2개+ 면 {#each ... (g.source_question_id)} 키 중복 → Svelte each_key_duplicate 크래시. 키를 (source_question_id ?? question_text) 고유값으로 변경. 추가로 자료 그룹은 approve-batch 가 source_question_id:int 필수라 422 → 일괄승인 버튼을 question 그룹에만 노출. 개별 승인/수정/삭제는 cardId 기반이라 자료도 정상.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 06:39:16 +00:00
hyungi a812d93c64 Merge remote-tracking branch 'origin/feat/study-memo-card-p1' into feat/email-pkm-folder 2026-06-07 06:14:22 +00:00
hyungi e0cd89aef7 Merge remote-tracking branch 'origin/feat/study-memo-card-p1' into feat/email-pkm-folder 2026-06-07 06:07:49 +00:00
hyungi 420ee0fefb Merge remote-tracking branch 'origin/feat/study-memo-card-p1' into feat/email-pkm-folder 2026-06-07 05:47:08 +00:00
hyungi 56df3d3b4f Merge remote-tracking branch 'origin/feat/study-memo-card-p1' into feat/email-pkm-folder 2026-06-07 05:37:29 +00:00
hyungi b9802fcee5 Merge remote-tracking branch 'origin/feat/study-memo-card-p1' into feat/email-pkm-folder 2026-06-07 02:45:15 +00:00
hyungi 4eb01bcd11 Merge remote-tracking branch 'origin/feat/study-memo-card-p1' into feat/email-pkm-folder 2026-06-07 02:38:39 +00:00
hyungi eda1da1507 merge(study): 카드 그룹핑(material) 2026-06-07 00:41:26 +00:00
hyungi b679f3ecb5 merge(study): 암기카드 검수 UI 2026-06-06 23:49:25 +00:00
hyungi 9334c50bd3 merge(study): 암기노트 P1 HR/A (정정훅·needs_review 큐·알람) 2026-06-06 23:09:10 +00:00
hyungi 0bd82a7b0f merge(study): 암기노트 Phase 1 추출 파이프라인 (additive, disjoint) 2026-06-06 12:39:39 +00:00
hyungi 2e5baa8329 feat(email): PKM 폴더 선별 수집 + eml 본문 추출 활성화
mailplus_archive: INBOX 전체 → MAILPLUS_FOLDER(기본 PKM) 선별 수집, eml extract 스킵 가드 제거(검색·색인 편입), 폴더별 UID 상태(job_name=mailplus:<folder>), 폴더 부재 시 no-op. extract_worker: _extract_eml 신설(From/To/Date/Subject 헤더 prepend + 본문 text/plain 우선·html→bs4 fallback, 첨부 extract_meta 인벤토리 scaffold). preview/marker 는 eml 자동 skip 이라 라우팅 무변경. DNS drift(D25, mailplus.hyungi.net→.227) 교정 후 활성. 할일(events) 연계 없음.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 15:41:17 +09:00
12 changed files with 1305 additions and 1331 deletions
+95
View File
@@ -1,9 +1,11 @@
"""텍스트 추출 워커 — kordoc / PyMuPDF / Surya OCR / LibreOffice / 직접 읽기 / 웹 HTML""" """텍스트 추출 워커 — kordoc / PyMuPDF / Surya OCR / LibreOffice / 직접 읽기 / 웹 HTML"""
import email
import hashlib import hashlib
import re import re
import subprocess import subprocess
from datetime import datetime, timezone from datetime import datetime, timezone
from email.header import decode_header
from pathlib import Path from pathlib import Path
import httpx import httpx
@@ -23,6 +25,8 @@ TEXT_FORMATS = {"md", "txt", "csv", "json", "xml", "html"}
OFFICE_FORMATS = {"xlsx", "xls", "docx", "doc", "pptx", "ppt", "odt", "ods", "odp", "odoc", "osheet"} OFFICE_FORMATS = {"xlsx", "xls", "docx", "doc", "pptx", "ppt", "odt", "ods", "odp", "odoc", "osheet"}
# OCR 대상 이미지 포맷 # OCR 대상 이미지 포맷
IMAGE_FORMATS = {"jpg", "jpeg", "png", "tiff", "tif", "bmp", "gif", "webp"} IMAGE_FORMATS = {"jpg", "jpeg", "png", "tiff", "tif", "bmp", "gif", "webp"}
# 이메일 (선별 PKM 폴더 수집 → 헤더+본문 추출)
EML_FORMATS = {"eml"}
EXTRACTOR_VERSION = "kordoc@1.7" EXTRACTOR_VERSION = "kordoc@1.7"
PYMUPDF_VERSION = "pymupdf" PYMUPDF_VERSION = "pymupdf"
@@ -233,6 +237,90 @@ async def _extract_web_html(doc: Document, html_path: Path) -> None:
) )
# ─── 이메일(.eml) 추출 ───
def _decode_eml_header(raw: str) -> str:
"""MIME 인코딩 헤더 디코딩."""
if not raw:
return ""
out = []
for data, charset in decode_header(raw):
if isinstance(data, bytes):
out.append(data.decode(charset or "utf-8", errors="replace"))
else:
out.append(data)
return "".join(out)
async def _extract_eml(doc: Document, eml_path: Path) -> None:
"""이메일(.eml) 본문 추출 — From/To/Date/Subject 헤더 블록 + 본문.
본문은 text/plain 우선, 없으면 text/html → bs4 평문(_extract_web_with_bs4 재사용).
헤더를 본문 머리에 prepend 해 검색·요약이 발신자/제목 맥락을 갖게 함.
첨부는 extract_meta['email_attachments'] 에 인벤토리만 (본문 추출은 후속 — scaffold).
"""
raw = eml_path.read_bytes()
msg = email.message_from_bytes(raw)
hdr_lines = []
for label in ("From", "To", "Date", "Subject"):
val = _decode_eml_header(msg.get(label, ""))
if val:
hdr_lines.append(f"{label}: {val}")
body = ""
html_body = ""
attachments = []
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
disp = (part.get("Content-Disposition") or "").lower()
if "attachment" in disp:
payload = part.get_payload(decode=True)
attachments.append({
"filename": _decode_eml_header(part.get_filename() or ""),
"content_type": ctype,
"size": len(payload) if payload else 0,
})
continue
if ctype == "text/plain" and not body:
payload = part.get_payload(decode=True)
if payload is not None:
body = payload.decode(part.get_content_charset() or "utf-8", errors="replace")
elif ctype == "text/html" and not html_body:
payload = part.get_payload(decode=True)
if payload is not None:
html_body = payload.decode(part.get_content_charset() or "utf-8", errors="replace")
else:
payload = msg.get_payload(decode=True)
if payload is not None:
decoded = payload.decode(msg.get_content_charset() or "utf-8", errors="replace")
if msg.get_content_type() == "text/html":
html_body = decoded
else:
body = decoded
# text/plain 없으면 html → bs4 평문 (devonagent 최종 fallback 재사용, 신규 의존성 0)
if not body and html_body:
body, _ = _extract_web_with_bs4(html_body)
if attachments:
names = ", ".join(a["filename"] for a in attachments if a["filename"])
hdr_lines.append(f"Attachments: {len(attachments)}" + (f" ({names})" if names else ""))
header_block = "\n".join(hdr_lines)
full_text = (header_block + "\n\n" + (body or "")).replace("\x00", "").strip()
doc.extracted_text = full_text
doc.extracted_at = datetime.now(timezone.utc)
doc.extractor_version = "eml@stdlib"
if attachments:
meta = dict(doc.extract_meta or {})
meta["email_attachments"] = attachments
doc.extract_meta = meta
logger.info(f"[eml] {doc.file_path} ({len(full_text)}자, 첨부 {len(attachments)})")
# ─── 메인 처리 ─── # ─── 메인 처리 ───
async def process(document_id: int, session: AsyncSession) -> None: async def process(document_id: int, session: AsyncSession) -> None:
@@ -257,6 +345,13 @@ async def process(document_id: int, session: AsyncSession) -> None:
await _extract_web_html(doc, full_path) await _extract_web_html(doc, full_path)
return return
# ─── 이메일 (.eml) — 헤더+본문 추출 (선별 PKM 폴더 수집) ───
if fmt in EML_FORMATS:
if not full_path.exists():
raise FileNotFoundError(f"파일 없음: {full_path}")
await _extract_eml(doc, full_path)
return
# ─── 텍스트 파일 — 직접 읽기 ─── # ─── 텍스트 파일 — 직접 읽기 ───
if fmt in TEXT_FORMATS: if fmt in TEXT_FORMATS:
if not full_path.exists(): if not full_path.exists():
+22 -18
View File
@@ -55,13 +55,20 @@ def _detect_origin(subject: str, body: str) -> str:
return "external" return "external"
def _fetch_emails_sync(host: str, port: int, user: str, password: str, last_uid: int | None): def _fetch_emails_sync(host: str, port: int, user: str, password: str, last_uid: int | None, folder: str):
"""동기 IMAP 메일 가져오기 (asyncio.to_thread에서 실행)""" """동기 IMAP 메일 가져오기 (asyncio.to_thread에서 실행).
선별 폴더(MAILPLUS_FOLDER, 기본 'PKM')만 수집 — INBOX 전체 X.
폴더 부재 시 no-op (사용자가 MailPlus 규칙으로 폴더 생성 전까진 안전하게 0건).
"""
results = [] results = []
conn = imaplib.IMAP4_SSL(host, port, timeout=30) conn = imaplib.IMAP4_SSL(host, port, timeout=30)
try: try:
conn.login(user, password) conn.login(user, password)
conn.select("INBOX") typ, _ = conn.select(folder)
if typ != "OK":
logger.info(f"[메일] 폴더 '{folder}' 없음/접근불가 — 수집 건너뜀 (no-op)")
return results
if last_uid: if last_uid:
# 증분 동기화: last_uid 이후 # 증분 동기화: last_uid 이후
@@ -71,14 +78,13 @@ def _fetch_emails_sync(host: str, port: int, user: str, password: str, last_uid:
since = (datetime.now() - timedelta(days=7)).strftime("%d-%b-%Y") since = (datetime.now() - timedelta(days=7)).strftime("%d-%b-%Y")
_, data = conn.uid("search", None, f"SINCE {since}") _, data = conn.uid("search", None, f"SINCE {since}")
uids = data[0].split() uids = (data[0] or b"").split()
for uid_bytes in uids: for uid_bytes in uids:
uid = int(uid_bytes) uid = int(uid_bytes)
_, msg_data = conn.uid("fetch", uid_bytes, "(RFC822)") _, msg_data = conn.uid("fetch", uid_bytes, "(RFC822)")
if msg_data[0] is None: if msg_data[0] is None:
continue continue
raw = msg_data[0][1] results.append((uid, msg_data[0][1]))
results.append((uid, raw))
finally: finally:
conn.logout() conn.logout()
@@ -91,15 +97,18 @@ async def run():
port = int(os.getenv("MAILPLUS_PORT", "993")) port = int(os.getenv("MAILPLUS_PORT", "993"))
user = os.getenv("MAILPLUS_USER", "") user = os.getenv("MAILPLUS_USER", "")
password = os.getenv("MAILPLUS_PASS", "") password = os.getenv("MAILPLUS_PASS", "")
folder = os.getenv("MAILPLUS_FOLDER", "PKM")
if not all([host, user, password]): if not all([host, user, password]):
logger.warning("MailPlus 인증 정보 미설정") logger.warning("MailPlus 인증 정보 미설정")
return return
job_name = f"mailplus:{folder}"
async with async_session() as session: async with async_session() as session:
# 마지막 UID 조회 # 마지막 UID 조회 (UID 는 폴더별 네임스페이스 → job_name 에 폴더 포함)
state = await session.execute( state = await session.execute(
select(AutomationState).where(AutomationState.job_name == "mailplus") select(AutomationState).where(AutomationState.job_name == job_name)
) )
state_row = state.scalar_one_or_none() state_row = state.scalar_one_or_none()
last_uid = int(state_row.last_check_value) if state_row and state_row.last_check_value else None last_uid = int(state_row.last_check_value) if state_row and state_row.last_check_value else None
@@ -107,7 +116,7 @@ async def run():
# IMAP 동기 호출을 비동기로 래핑 # IMAP 동기 호출을 비동기로 래핑
try: try:
emails = await asyncio.to_thread( emails = await asyncio.to_thread(
_fetch_emails_sync, host, port, user, password, last_uid, _fetch_emails_sync, host, port, user, password, last_uid, folder,
) )
except Exception as e: except Exception as e:
logger.error(f"IMAP 연결 실패: {e}") logger.error(f"IMAP 연결 실패: {e}")
@@ -174,15 +183,10 @@ async def run():
session.add(doc) session.add(doc)
await session.flush() await session.flush()
safe_subj = subject.replace("\n", " ").replace("\r", " ")[:200] # 검색·색인 편입 (extract → classify → embed/chunk). 할일 연계 없음.
await enqueue_stage(session, doc.id, "extract")
# TODO: extract_worker가 eml 본문/첨부 파싱 지원 시 이 조건 제거 archived.append(subject.replace("\n", " ").replace("\r", " ")[:200])
if doc.file_format != "eml":
await enqueue_stage(session, doc.id, "extract")
else:
logger.debug(f"[메일] {safe_subj} — eml extract 미지원, 큐 스킵")
archived.append(safe_subj)
max_uid = max(max_uid, uid) max_uid = max(max_uid, uid)
except Exception as e: except Exception as e:
@@ -194,7 +198,7 @@ async def run():
state_row.last_run_at = datetime.now(timezone.utc) state_row.last_run_at = datetime.now(timezone.utc)
else: else:
session.add(AutomationState( session.add(AutomationState(
job_name="mailplus", job_name=job_name,
last_check_value=str(max_uid), last_check_value=str(max_uid),
last_run_at=datetime.now(timezone.utc), last_run_at=datetime.now(timezone.utc),
)) ))
+13
View File
@@ -0,0 +1,13 @@
/**
* 카드 학습 세션 전달용 store.
*
* 복습함(/study/review-box)에서 선택한 카드들을 cards-study 복습 세션으로 넘긴다.
* 백엔드 '세션 by card_ids' 엔드포인트 없이(= eid contention 중 fastapi 무재빌드) 동작하도록
* 선택 카드 객체 배열을 그대로 전달. cards-study 가 startReview 에서 consume(읽고 비움).
*
* 모듈 레벨 store 라 SPA 네비게이션 동안 유지되고, 새로고침 시 사라진다(그땐 복습함에서 다시 선택).
*/
import { writable } from 'svelte/store';
// CardItem[] | null — 복습함에서 '선택 복습' 시 set, cards-study 가 소비 후 null.
export const pendingReviewCards = writable(null);
+316 -400
View File
@@ -1,76 +1,124 @@
<script lang="ts"> <script lang="ts">
// 대시보드 — 상황판. 사용자 지시서 기반 재설계. // 대시보드 — 데일리 홈 cockpit (확정 시안 dashboard-sage-3 안1 골격 + 안2 검토/파이프라인 위젯 + 안3 도메인 분포 한 줄).
// 정보 위계: 헤더 → 핀 메모 → 카드 4개 → 최근 활동 → 파이프라인. // 정보 흐름: 인사 → 오늘 요약 띠(검토 대기 + 디제스트 + 스탯) → 2열(좌: 빠른 캡처·활동 / 우: 학습·도메인 분포·고정).
// 단일 흐름 레이아웃, 모바일 우선, 행동 유도는 승인 대기에만. // 데이터는 전부 기존 엔드포인트 wiring(백엔드 변경 0). 학습 streak/복습 마감은 전용 엔드포인트 부재라 링크형으로 degrade.
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { import {
dashboardSummary, dashboardSummary,
refresh,
type DashboardSummary, type DashboardSummary,
type PipelineStatus, type PipelineStatus,
type QueueLag, type QueueLag,
} from '$lib/stores/system'; } from '$lib/stores/system';
import { domainBgClass, domainLabel } from '$lib/utils/domainSlug'; import { domainBgClass, domainLabel } from '$lib/utils/domainSlug';
import { user } from '$lib/stores/auth';
import { api } from '$lib/api'; import { api } from '$lib/api';
import Card from '$lib/components/ui/Card.svelte';
import EmptyState from '$lib/components/ui/EmptyState.svelte'; import EmptyState from '$lib/components/ui/EmptyState.svelte';
import Skeleton from '$lib/components/ui/Skeleton.svelte'; import Skeleton from '$lib/components/ui/Skeleton.svelte';
import { import {
Inbox, Scale, FileText, Activity, StickyNote, Newspaper, Pin, ChevronRight, Pencil, Scale, FileText, Pin, ChevronRight, GraduationCap, Upload, Newspaper,
Library, Mic, Video, Sparkles,
} from 'lucide-svelte'; } from 'lucide-svelte';
import { renderMemoHtml, countHiddenTasks, DEFAULT_HIDE_AFTER_MS } from '$lib/utils/memoRenderer';
import { addToast } from '$lib/stores/toast'; import { addToast } from '$lib/stores/toast';
let summary = $derived<DashboardSummary | null>($dashboardSummary); let summary = $derived<DashboardSummary | null>($dashboardSummary);
let loading = $derived(summary === null); let loading = $derived(summary === null);
// ─── 핀 고정 메모 ─── // ─── 인사 헤더 ───
let pinnedMemos = $state<any[]>([]); const greetingName = $derived($user?.username ?? 'hyungi');
// 메모별 "완료 항목 펼침" 토글 — key: memo.id, value: true 면 숨겨진 체크 항목 노출 const todayLabel = new Intl.DateTimeFormat('ko-KR', {
let showHiddenByMemo = $state<Record<number, boolean>>({}); year: 'numeric', month: 'long', day: 'numeric', weekday: 'long',
// 자동 숨김 tick. 1초 해상도로 충분 (hideAfter 10초라 오차 수용). }).format(new Date());
let nowTick = $state(new Date());
$effect(() => { // ─── 디제스트 헤드라인 (best-effort, 기존 /digest) ───
const id = setInterval(() => { nowTick = new Date(); }, 1000); interface DigestLead {
return () => clearInterval(id); topic_label: string;
}); article_count: number;
importance_score: number;
country: string;
date: string;
}
let digestLead = $state<DigestLead | null>(null);
onMount(async () => { const COUNTRY_KO: Record<string, string> = {
KR: '한국', JP: '일본', US: '미국', CN: '중국', DE: '독일',
FR: '프랑스', GB: '영국', TW: '대만',
};
function countryKo(c: string): string {
return COUNTRY_KO[c?.toUpperCase?.()] ?? c ?? '';
}
// ─── 도메인 분포 (best-effort, 기존 /documents/tree) ───
interface DomainDist { name: string; count: number; }
let domainDist = $state<DomainDist[]>([]);
let domainTotal = $derived(domainDist.reduce((s, d) => s + d.count, 0));
function domainCount(slugLike: string): number {
// domainBgClass 와 동일 매핑 기준으로 특정 도메인 건수 추출 (스탯 띠용)
const target = domainBgClass(slugLike);
return domainDist.find((d) => domainBgClass(d.name) === target)?.count ?? 0;
}
// ─── 빠른 캡처 (기존 POST /memos) ───
let captureText = $state('');
let capturing = $state(false);
async function quickCapture() {
const content = captureText.trim();
if (!content || capturing) return;
capturing = true;
try { try {
const res = await api<any>('/memos/?pinned=true&page_size=3&archived=false'); await api('/memos/', { method: 'POST', body: JSON.stringify({ content }) });
pinnedMemos = res.items || []; captureText = '';
} catch { /* 실패 시 빈 배열 유지 */ } addToast('success', '메모 저장됨');
}); void refresh(); // 메모 수 등 요약 즉시 갱신(60s 폴 기다리지 않음)
// ─── 핀 메모 체크박스 토글 ───
async function handlePinCheckbox(e: MouseEvent, memo: any) {
const target = e.target as HTMLElement;
if (target.tagName !== 'INPUT' || (target as HTMLInputElement).type !== 'checkbox') return;
e.preventDefault();
e.stopPropagation(); // details 토글 충돌 방지
const input = target as HTMLInputElement;
const taskIndex = parseInt(input.dataset.taskIndex || '', 10);
if (isNaN(taskIndex)) return;
const checked = input.checked;
try {
const updated = await api<any>(`/memos/${memo.id}/tasks/${taskIndex}`, {
method: 'PATCH',
body: JSON.stringify({ checked }),
});
pinnedMemos = pinnedMemos.map((m) => (m.id === memo.id ? updated : m));
} catch { } catch {
input.checked = !checked; // 롤백 addToast('error', '메모 저장 실패');
addToast('error', '체크박스 변경 실패'); } finally {
capturing = false;
} }
} }
function onCaptureKeydown(e: KeyboardEvent) {
function toggleShowHidden(memoId: number) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void quickCapture(); }
showHiddenByMemo = { ...showHiddenByMemo, [memoId]: !showHiddenByMemo[memoId] };
} }
// ─── 파이프라인 ─── // ─── 핀 고정 메모 (기존 /memos?pinned) ───
let pinnedMemos = $state<any[]>([]);
function pinTitle(memo: any): string {
const firstLine = memo.content?.split('\n')[0]?.replace(/^#+\s*/, '').trim();
return memo.title || firstLine || '메모';
}
onMount(async () => {
// 핀 메모
try {
const res = await api<any>('/memos/?pinned=true&page_size=4&archived=false');
pinnedMemos = res.items || [];
} catch { /* 빈 배열 유지 */ }
// 디제스트 최신 — countries→topics flatten 후 중요도 desc(동률 시 기사수 desc) top
try {
const d = await api<any>('/digest');
const topics = (d.countries || []).flatMap((c: any) =>
(c.topics || []).map((t: any) => ({ ...t, country: c.country })));
topics.sort((a: any, b: any) =>
(b.importance_score - a.importance_score) || (b.article_count - a.article_count));
if (topics[0]) {
digestLead = {
topic_label: topics[0].topic_label,
article_count: topics[0].article_count,
importance_score: topics[0].importance_score,
country: topics[0].country,
date: d.digest_date,
};
}
} catch { /* 디제스트 없으면 블록 자동 생략 */ }
// 도메인 분포 — 트리 top-level 노드 건수
try {
const tree = await api<any[]>('/documents/tree');
domainDist = (tree || [])
.map((n) => ({ name: n.name as string, count: n.count as number }))
.sort((a, b) => b.count - a.count);
} catch { /* 분포 없으면 카드 자동 생략 */ }
});
// ─── 파이프라인 (기존 로직 재사용, 칩 요약 + 상세 접힘) ───
const STAGE_ORDER = ['extract', 'stt', 'classify', 'embed', 'preview', 'thumbnail'] as const; const STAGE_ORDER = ['extract', 'stt', 'classify', 'embed', 'preview', 'thumbnail'] as const;
const STAGE_LABEL: Record<string, string> = { const STAGE_LABEL: Record<string, string> = {
extract: '추출', stt: '전사', classify: '분류', embed: '임베딩', extract: '추출', stt: '전사', classify: '분류', embed: '임베딩',
@@ -80,13 +128,10 @@
interface PipelineRow { interface PipelineRow {
stage: string; label: string; stage: string; label: string;
pending: number; processing: number; failed: number; total: number; pending: number; processing: number; failed: number; total: number;
// §4 — queue_lag 의 oldest_pending_age_sec (적체 신호용)
oldestPendingAgeSec: number | null; oldestPendingAgeSec: number | null;
} }
function buildPipelineRows(items: PipelineStatus[], lag: QueueLag[]): PipelineRow[] { function buildPipelineRows(items: PipelineStatus[], lag: QueueLag[]): PipelineRow[] {
// §4 — 24h 누적 (pipeline_status) + 현재 시점 lag (queue_lag) 두 소스 머지.
// queue_lag 가 있으면 stage 별 pending/processing/failed 는 그쪽 (정확) 사용.
const lagMap = new Map(lag.map((l) => [l.stage, l])); const lagMap = new Map(lag.map((l) => [l.stage, l]));
const grouped = new Map<string, { pending: number; processing: number; failed: number; ageSec: number | null }>(); const grouped = new Map<string, { pending: number; processing: number; failed: number; ageSec: number | null }>();
for (const it of items) { for (const it of items) {
@@ -96,14 +141,12 @@
else if (it.status === 'failed') cur.failed += it.count; else if (it.status === 'failed') cur.failed += it.count;
grouped.set(it.stage, cur); grouped.set(it.stage, cur);
} }
// queue_lag 로 덮어쓰기 (현재 시점 신호가 우선)
for (const l of lag) { for (const l of lag) {
grouped.set(l.stage, { grouped.set(l.stage, {
pending: l.pending, processing: l.processing, failed: l.failed, pending: l.pending, processing: l.processing, failed: l.failed,
ageSec: l.oldest_pending_age_sec, ageSec: l.oldest_pending_age_sec,
}); });
} }
// queue_lag 만 있는 stage 도 전부 포함
const allStages = new Set([...grouped.keys(), ...lagMap.keys()]); const allStages = new Set([...grouped.keys(), ...lagMap.keys()]);
const orderedStages = [ const orderedStages = [
...STAGE_ORDER.filter((s) => allStages.has(s)), ...STAGE_ORDER.filter((s) => allStages.has(s)),
@@ -126,13 +169,10 @@
let pipelineMax = $derived(Math.max(1, ...pipelineRows.map((r) => r.total))); let pipelineMax = $derived(Math.max(1, ...pipelineRows.map((r) => r.total)));
let totalFailed = $derived(summary?.failed_count ?? 0); let totalFailed = $derived(summary?.failed_count ?? 0);
let totalPending = $derived(pipelineRows.reduce((s, r) => s + r.pending, 0)); let totalPending = $derived(pipelineRows.reduce((s, r) => s + r.pending, 0));
let totalProcessing = $derived(pipelineRows.reduce((s, r) => s + r.processing, 0));
// §4 — 카테고리 mini-card 데이터 let pipelineManualClosed = $state(false);
const CATEGORY_CARDS: { key: string; label: string; href: string; icon: any }[] = [ let pipelineOpen = $derived(pipelineManualClosed ? false : totalFailed > 0);
{ key: 'library', label: '자료실', href: '/library', icon: Library },
{ key: 'audio', label: '오디오', href: '/audio', icon: Mic },
{ key: 'video', label: '비디오', href: '/video', icon: Video },
];
function formatAge(sec: number | null): string { function formatAge(sec: number | null): string {
if (sec == null || sec <= 0) return ''; if (sec == null || sec <= 0) return '';
@@ -142,23 +182,9 @@
return `${Math.floor(sec / 86400)}일 전`; return `${Math.floor(sec / 86400)}일 전`;
} }
// 파이프라인 접힘 상태
let pipelineManualClosed = $state(false);
let pipelineOpen = $derived(pipelineManualClosed ? false : totalFailed > 0);
// ─── 시스템 상태 ───
function pickSystemTone(s: DashboardSummary) {
if (s.failed_count > 0) return { label: `실패 ${s.failed_count}`, tone: 'error' as const };
const backlog = s.pipeline_status.some((p) => p.status === 'pending' && p.count > 10);
if (backlog) return { label: '대기열 적체', tone: 'warning' as const };
return { label: '정상', tone: 'success' as const };
}
const TONE_DOT: Record<string, string> = { success: 'bg-success', warning: 'bg-warning', error: 'bg-error' };
const TONE_TEXT: Record<string, string> = { success: 'text-success', warning: 'text-warning', error: 'text-error' };
let systemView = $derived(summary ? pickSystemTone(summary) : null);
function formatTime(dateStr: string) { function formatTime(dateStr: string) {
const d = new Date(dateStr); const d = new Date(dateStr);
if (isNaN(d.getTime())) return ''; // 빈 문자열/유효하지 않은 created_at → 'Invalid Date' 회피
const diff = Date.now() - d.getTime(); const diff = Date.now() - d.getTime();
if (diff < 60000) return '방금'; if (diff < 60000) return '방금';
if (diff < 3600000) return `${Math.floor(diff / 60000)}분 전`; if (diff < 3600000) return `${Math.floor(diff / 60000)}분 전`;
@@ -168,351 +194,251 @@
} }
</script> </script>
<div class="p-4 lg:p-6"> <div class="p-4 lg:p-8">
<div class="max-w-4xl mx-auto"> <div class="max-w-5xl mx-auto">
<!-- ═══ 1. 헤더 + 시스템 상태 ═══ --> <!-- ═══ 인사 헤더 ═══ -->
<div class="flex items-center justify-between mb-5"> <div class="flex items-baseline gap-2.5 flex-wrap">
<h2 class="text-xl font-bold text-text">대시보드</h2> <h1 class="text-2xl font-bold text-text tracking-tight">안녕하세요, {greetingName}</h1>
{#if systemView} <span class="text-sm text-dim">오늘도 지식 쌓는 날.</span>
<span class="text-xs text-dim flex items-center gap-1.5 select-none">
{systemView.label}
<span class="w-2 h-2 rounded-full {TONE_DOT[systemView.tone]}"></span>
</span>
{/if}
</div> </div>
<div class="text-xs text-faint mt-1 mb-6 tracking-wide">{todayLabel}</div>
{#if loading} {#if loading}
<!-- 스켈레톤 --> <!-- 스켈레톤 -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-5"> <div class="bg-surface border border-default rounded-card p-5 mb-5">
{#each Array(4) as _} <Skeleton w="w-40" h="h-10" />
<Card><Skeleton w="w-20" h="h-3" /><Skeleton w="w-16" h="h-8" class="mt-3" /><Skeleton w="w-24" h="h-3" class="mt-2" /></Card> <Skeleton w="w-full" h="h-4" class="mt-4" />
{/each} <Skeleton w="w-2/3" h="h-4" class="mt-2" />
</div>
<div class="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-5">
<div class="space-y-5">
<div class="bg-surface border border-default rounded-card p-5"><Skeleton w="w-24" h="h-4" /><Skeleton w="w-full" h="h-10" class="mt-3" /></div>
<div class="bg-surface border border-default rounded-card p-5"><Skeleton w="w-24" h="h-4" /><Skeleton w="w-full" h="h-40" class="mt-3" /></div>
</div>
<div class="space-y-5">
<div class="bg-surface border border-default rounded-card p-5"><Skeleton w="w-full" h="h-24" /></div>
<div class="bg-surface border border-default rounded-card p-5"><Skeleton w="w-full" h="h-32" /></div>
</div>
</div> </div>
<Card class="mb-4"><Skeleton w="w-24" h="h-4" /><Skeleton w="w-full" h="h-40" class="mt-3" /></Card>
<Card><Skeleton w="w-24" h="h-4" /><Skeleton w="w-full" h="h-20" class="mt-3" /></Card>
{:else if summary} {:else if summary}
<!-- ═══ 2. 핀 고정 메모 (조건부, 펼침/접힘) ═══ --> <!-- ═══ 오늘 요약 띠 ═══ -->
{#if pinnedMemos.length > 0} <div class="bg-surface border border-default rounded-card p-5 lg:p-6 mb-5">
<div class="mb-5 space-y-1.5"> <!-- 검토 대기 + 디제스트 -->
{#each pinnedMemos as memo (memo.id)} <div class="flex flex-col sm:flex-row items-stretch gap-5">
<details class="group/pin"> <!-- 검토 대기 강조 -->
<summary class="flex items-center gap-2.5 px-3 py-2 bg-surface border border-default/50 rounded-lg <div class="flex flex-col justify-center sm:pr-6 sm:border-r border-default sm:min-w-[150px]">
hover:bg-surface-hover transition-colors text-sm cursor-pointer select-none list-none"> <span class="text-4xl font-extrabold tracking-tight leading-none {summary.inbox_count > 0 ? 'text-warning' : 'text-success'}">
<Pin size={13} class="text-accent shrink-0" /> {summary.inbox_count.toLocaleString()}
<span class="text-text truncate flex-1"> </span>
{memo.title && memo.title !== memo.content?.split('\n')[0]?.replace(/^#+\s*/, '').slice(0, 80) <span class="text-[11px] text-dim mt-1.5 uppercase tracking-wide">검토 대기 문서</span>
? memo.title {#if summary.inbox_count > 0}
: memo.content?.split('\n')[0] || '메모'} <a href="/inbox" class="text-[11px] text-accent font-semibold mt-2 hover:underline">검토 시작 →</a>
</span> {:else}
<ChevronRight size={13} class="text-dim shrink-0 transition-transform group-open/pin:rotate-90" /> <span class="text-[11px] text-dim mt-2">미분류 없음</span>
</summary> {/if}
<!-- svelte-ignore a11y_click_events_have_key_events --> </div>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div <!-- 디제스트 톱 (best-effort) -->
class="mt-1 px-3 py-2.5 bg-surface/50 border border-default/30 rounded-lg text-sm text-text" {#if digestLead}
onclick={(e) => handlePinCheckbox(e, memo)} <a href="/digest" class="flex-1 flex flex-col justify-center gap-1.5 group">
> <div class="flex items-center gap-2">
<div <span class="text-[10px] font-bold text-error bg-error/10 rounded px-1.5 py-0.5 uppercase tracking-wide">속보</span>
class="prose prose-sm max-w-none memo-content-pin" <span class="text-[11px] text-faint">{digestLead.date} 브리핑</span>
class:show-hidden={showHiddenByMemo[memo.id]}
>
{@html renderMemoHtml(memo.content || '', {
compact: true,
interactive: true,
taskStates: memo.memo_task_state ?? {},
now: nowTick,
})}
</div>
<div class="flex items-center gap-3 mt-2">
{#if countHiddenTasks(memo.memo_task_state, nowTick, DEFAULT_HIDE_AFTER_MS) > 0 || showHiddenByMemo[memo.id]}
<button
type="button"
class="text-[11px] text-dim hover:text-text underline-offset-2 hover:underline"
onclick={(e) => { e.stopPropagation(); toggleShowHidden(memo.id); }}
>
{#if showHiddenByMemo[memo.id]}
완료 항목 숨기기
{:else}
완료 {countHiddenTasks(memo.memo_task_state, nowTick, DEFAULT_HIDE_AFTER_MS)}개 보기
{/if}
</button>
{/if}
<a href="/memos" class="text-[11px] text-accent hover:underline">메모함에서 보기 →</a>
</div>
</div> </div>
</details> <div class="text-[15px] font-semibold text-text leading-snug group-hover:text-accent transition-colors">
{/each} {digestLead.topic_label}
{#if pinnedMemos.length >= 3} </div>
<a href="/memos" class="text-[11px] text-accent hover:underline pl-8">더보기 →</a> <div class="text-[11px] text-dim">
관련 기사 <strong class="text-text">{digestLead.article_count}</strong>
· 중요도 {digestLead.importance_score.toFixed(2)}
· {countryKo(digestLead.country)}
</div>
</a>
{:else}
<a href="/news" class="flex-1 flex items-center gap-2 text-sm text-dim hover:text-accent transition-colors">
<Newspaper size={16} /> 오늘의 뉴스 브리핑 보기 →
</a>
{/if} {/if}
</div> </div>
{/if}
<!-- ═══ 3. 핵심 카드 4개 ═══ --> <!-- 스탯 띠 -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-5"> <div class="flex flex-nowrap overflow-x-auto border-t border-default mt-4 pt-4">
<!-- 문서함 --> {@render stat((summary.documents_count ?? 0).toLocaleString(), '문서', 'text-accent')}
<a href="/documents" class="block"> {@render stat((summary.news_count ?? 0).toLocaleString(), '뉴스')}
<Card interactive class="h-full"> {#if domainTotal > 0}
<div class="flex items-start justify-between"> {@render stat(domainCount('Industrial_Safety').toLocaleString(), '산업안전', 'text-domain-safety')}
<p class="text-sm text-dim">문서함</p> {@render stat(domainCount('Engineering').toLocaleString(), '엔지니어링', 'text-domain-engineering')}
<FileText size={18} class="text-faint" /> {/if}
</div> {#if summary.category_counts?.library}
<p class="text-3xl font-bold mt-2 text-text">{(summary.documents_count ?? 0).toLocaleString()}</p> {@render stat(summary.category_counts.library.toLocaleString(), '자료실')}
<p class="text-xs text-dim mt-1"> {/if}
{#if summary.today_added > 0} {@render stat((summary.memos_count ?? 0).toLocaleString(), '메모')}
<span class="text-accent">+{summary.today_added} 오늘</span> </div>
{:else}
일반 문서
{/if}
</p>
</Card>
</a>
<!-- 메모 -->
<a href="/memos" class="block">
<Card interactive class="h-full">
<div class="flex items-start justify-between">
<p class="text-sm text-dim">메모</p>
<StickyNote size={18} class="text-faint" />
</div>
<p class="text-3xl font-bold mt-2 text-text">{(summary.memos_count ?? 0).toLocaleString()}</p>
<p class="text-xs text-dim mt-1">직접 작성</p>
</Card>
</a>
<!-- 뉴스 -->
<a href="/news" class="block">
<Card interactive class="h-full">
<div class="flex items-start justify-between">
<p class="text-sm text-dim">뉴스</p>
<Newspaper size={18} class="text-faint" />
</div>
<p class="text-3xl font-bold mt-2 text-text">{(summary.news_count ?? 0).toLocaleString()}</p>
<p class="text-xs text-dim mt-1">수집 기사</p>
</Card>
</a>
<!-- 승인 대기 (액션형) -->
<a href="/inbox" class="block">
<Card interactive class="h-full">
<div class="flex items-start justify-between">
<p class="text-sm text-dim">승인 대기</p>
<Inbox size={18} class="text-faint" />
</div>
<p class="text-3xl font-bold mt-2 {summary.inbox_count > 0 ? 'text-warning' : 'text-success'}">
{summary.inbox_count}
</p>
{#if summary.inbox_count > 0}
<p class="text-xs text-accent mt-1">검토하기 →</p>
{:else}
<p class="text-xs text-dim mt-1">미분류 없음</p>
{/if}
</Card>
</a>
</div> </div>
<!-- ═══ 3.5. 카테고리 + 자료실 제안 (§4) ═══ --> <!-- ═══ 2열 본문 ═══ -->
{#if summary.category_counts && (Object.keys(summary.category_counts).length > 0 || summary.library_pending_suggestions > 0)} <div class="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-5 items-start">
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-5">
{#each CATEGORY_CARDS as cat}
{@const count = summary.category_counts?.[cat.key] ?? 0}
<a href={cat.href} class="block">
<Card interactive class="h-full">
<div class="flex items-start justify-between">
<p class="text-sm text-dim">{cat.label}</p>
<cat.icon size={18} class="text-faint" />
</div>
<p class="text-2xl font-bold mt-2 text-text">{count.toLocaleString()}</p>
<p class="text-xs text-dim mt-1">카테고리</p>
</Card>
</a>
{/each}
<!-- 자료실 제안 (action card) --> <!-- ─── 왼쪽 ─── -->
<a href="/library" class="block"> <div class="space-y-5">
<Card interactive class="h-full">
<div class="flex items-start justify-between">
<p class="text-sm text-dim">자료실 제안</p>
<Sparkles size={18} class="text-faint" />
</div>
<p class="text-2xl font-bold mt-2 {summary.library_pending_suggestions > 0 ? 'text-warning' : 'text-success'}">
{summary.library_pending_suggestions}
</p>
{#if summary.library_pending_suggestions > 0}
<p class="text-xs text-accent mt-1">검토하기 →</p>
{:else}
<p class="text-xs text-dim mt-1">대기 없음</p>
{/if}
</Card>
</a>
</div>
{/if}
<!-- ═══ 3.6. tier 관측성 3종 카드 (B-3) ═══ --> <!-- 빠른 캡처 -->
{#if summary.tier_health && summary.tier_health.triage_total > 0} <div class="bg-surface border border-default rounded-card p-5">
{@const th = summary.tier_health} <div class="text-[11px] font-bold text-dim uppercase tracking-wider mb-3">빠른 캡처</div>
{@const esc_rate = th.triage_total > 0 ? th.escalated_total / th.triage_total : 0} <div class="flex gap-2 items-center">
{@const json_rate = th.triage_total > 0 ? th.triage_json_invalid / th.triage_total : 0} <input
{@const sup_rate = th.triage_total > 0 ? th.suppressed_total / th.triage_total : 0} class="flex-1 h-9 border border-default rounded-md bg-bg text-text text-sm px-3.5 outline-none focus:border-accent transition-colors placeholder:text-faint"
{@const deep_total = th.deep_total ?? 0} type="text"
{@const deep_err_rate = deep_total > 0 ? (th.deep_err_total ?? 0) / deep_total : 0} placeholder="메모 한 줄 남기기…"
<!-- Day 4 튜닝 (2026-04-27): 운영 패턴 실측 후 임계치 재조정. bind:value={captureText}
3일 telemetry 기준 escalate 97% 가 정상 (safety 정책 의도) → <80% 가 진짜 신호. --> onkeydown={onCaptureKeydown}
{@const esc_tone = esc_rate < 0.80 ? 'text-error' : 'text-text'} disabled={capturing}
{@const json_tone = json_rate > 0.05 ? 'text-error' : 'text-text'} />
{@const sup_tone = sup_rate > 0.10 ? 'text-warning' : 'text-text'} <button
{@const deep_tone = deep_err_rate > 0.05 ? 'text-error' : 'text-text'} class="h-9 px-4 rounded-md bg-accent text-white text-xs font-semibold hover:bg-accent-hover transition-colors disabled:opacity-50 shrink-0"
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-5"> onclick={quickCapture}
<!-- 에스컬레이션 비율 --> disabled={capturing || !captureText.trim()}
<Card class="h-full"> >저장</button>
<div class="flex items-start justify-between">
<p class="text-sm text-dim">에스컬레이션 비율 (24h)</p>
<Sparkles size={18} class="text-faint" />
</div> </div>
<p class="text-2xl font-bold mt-2 {esc_tone}"> <div class="flex gap-2 mt-2.5">
{(esc_rate * 100).toFixed(1)}% <a href="/documents" class="inline-flex items-center gap-1.5 text-[11px] text-accent-hover bg-accent/10 rounded-md px-2.5 py-1 hover:bg-accent/20 transition-colors">
</p> <Upload size={11} /> 파일 업로드
<p class="text-xs text-dim mt-1"> </a>
{th.escalated_total} / {th.triage_total} </div>
{#if esc_rate < 0.80}<span class="text-error ml-1">(매칭 실패 증가)</span>{/if} </div>
</p>
<p class="text-[10px] text-faint mt-1">safety 정책상 95~100% 가 정상</p> <!-- 최근 활동 타임라인 -->
{#if Object.keys(th.escalation_by_reason).length > 0} <div class="bg-surface border border-default rounded-card p-5">
<div class="mt-2 flex flex-wrap gap-1"> <div class="flex items-baseline justify-between mb-3">
{#each Object.entries(th.escalation_by_reason).slice(0, 4) as [reason, n]} <span class="text-[11px] font-bold text-dim uppercase tracking-wider">최근 활동</span>
<span class="text-[10px] px-1.5 py-0.5 rounded bg-surface-muted text-dim"> <div class="flex items-center gap-3">
{reason} {n} {#if summary.law_alerts > 0}
</span> <a href="/documents?source=law_monitor"
class="text-[11px] flex items-center gap-1 px-2.5 py-1 rounded-full bg-warning/10 text-warning border border-warning/20 hover:bg-warning/20 transition-colors">
<Scale size={11} /> 법령 {summary.law_alerts}
</a>
{/if}
<a href="/documents" class="text-[11px] text-accent hover:underline">전체 보기 →</a>
</div>
</div>
{#if summary.recent_documents.length > 0}
<div class="flex flex-col">
{#each summary.recent_documents as doc, i (doc.id)}
<a href="/documents/{doc.id}"
class="grid grid-cols-[auto_14px_1fr] gap-x-3 py-2.5 {i > 0 ? 'border-t border-default' : ''} group">
<div class="text-[10px] text-faint text-right pt-1 whitespace-nowrap tabular-nums w-14">{formatTime(doc.created_at)}</div>
<div class="flex flex-col items-center">
<span class="w-2 h-2 rounded-full mt-1.5 shrink-0 {domainBgClass(doc.ai_domain)}"></span>
{#if i < summary.recent_documents.length - 1}<span class="flex-1 w-px bg-default mt-1"></span>{/if}
</div>
<div class="pb-1">
<div class="text-[10px] font-bold uppercase tracking-wide text-dim mb-0.5">{domainLabel(doc.ai_domain)}</div>
<div class="text-[13px] text-text leading-snug group-hover:text-accent transition-colors truncate">{doc.title || '제목 없음'}</div>
</div>
</a>
{/each} {/each}
</div> </div>
{/if} {:else}
</Card> <EmptyState
icon={FileText}
<!-- triage JSON 건강도 --> title="아직 문서가 없습니다"
<Card class="h-full"> description="NAS PKM 폴더에 파일을 추가하면 자동으로 인덱싱됩니다."
<div class="flex items-start justify-between"> />
<p class="text-sm text-dim">triage JSON 건강도 (24h)</p>
<Sparkles size={18} class="text-faint" />
</div>
<p class="text-2xl font-bold mt-2 {json_tone}">
{(json_rate * 100).toFixed(1)}%
</p>
<p class="text-xs text-dim mt-1">
깨짐 {th.triage_json_invalid}
{#if json_rate > 0.05}<span class="text-error ml-1">(프롬프트 이슈 의심)</span>{/if}
</p>
<p class="text-[10px] text-faint mt-1">5% 초과 시 4B 프롬프트·모델 재검토</p>
</Card>
<!-- Backlog Suppression -->
<Card class="h-full">
<div class="flex items-start justify-between">
<p class="text-sm text-dim">Backlog Suppression (24h)</p>
<Sparkles size={18} class="text-faint" />
</div>
<p class="text-2xl font-bold mt-2 {sup_tone}">
{(sup_rate * 100).toFixed(1)}%
</p>
<p class="text-xs text-dim mt-1">
억제 {th.suppressed_total}
{#if sup_rate > 0.10}<span class="text-warning ml-1">(임계치 재조정 신호)</span>{/if}
</p>
<p class="text-[10px] text-faint mt-1">10% 초과 시 ratio/pending threshold 조정</p>
</Card>
<!-- Deep summary 안정성 (Day 4 신규) -->
<Card class="h-full">
<div class="flex items-start justify-between">
<p class="text-sm text-dim">Deep summary 안정성 (24h)</p>
<Sparkles size={18} class="text-faint" />
</div>
<p class="text-2xl font-bold mt-2 {deep_tone}">
{(deep_err_rate * 100).toFixed(1)}%
</p>
<p class="text-xs text-dim mt-1">
실패 {th.deep_err_total ?? 0} / {deep_total}
{#if deep_err_rate > 0.05}<span class="text-error ml-1">(MLX 안정성 점검)</span>{/if}
</p>
<p class="text-[10px] text-faint mt-1">call_failed / parse:* 합계, 5% 초과 시 점검</p>
</Card>
</div>
{/if}
<!-- ═══ 4. 최근 활동 ═══ -->
<Card class="mb-4">
<div class="flex items-center justify-between mb-3">
<h3 class="text-sm font-semibold text-text">최근 활동</h3>
<div class="flex items-center gap-3">
{#if summary.law_alerts > 0}
<a
href="/documents?source=law_monitor"
class="text-[11px] flex items-center gap-1 px-2.5 py-1 rounded-full
bg-warning/10 text-warning border border-warning/20
hover:bg-warning/20 transition-colors"
>
<Scale size={11} /> 법령 {summary.law_alerts}
</a>
{/if} {/if}
</div> </div>
</div> </div>
{#if summary.recent_documents.length > 0} <!-- ─── 오른쪽 ─── -->
<div class="divide-y divide-default/50"> <div class="space-y-5">
{#each summary.recent_documents as doc (doc.id)}
<a
href="/documents/{doc.id}"
class="block py-2.5 first:pt-0 last:pb-0 hover:bg-surface-hover -mx-5 px-5 transition-colors"
>
<div class="flex items-center justify-between gap-3">
<span class="text-sm text-text truncate">{doc.title || '제목 없음'}</span>
<span class="text-[11px] text-dim shrink-0">{formatTime(doc.created_at)}</span>
</div>
<div class="flex items-center gap-1.5 mt-1">
<span class="w-1.5 h-1.5 rounded-full shrink-0 {domainBgClass(doc.ai_domain)}"></span>
<span class="text-[11px] text-dim truncate">{domainLabel(doc.ai_domain)}</span>
</div>
</a>
{/each}
</div>
{:else}
<EmptyState
icon={FileText}
title="아직 문서가 없습니다"
description="NAS PKM 폴더에 파일을 추가하면 자동으로 인덱싱됩니다."
/>
{/if}
</Card>
<!-- ═══ 5. 파이프라인 (접힘) ═══ --> <!-- 학습 (streak/복습 마감은 백엔드 부재로 링크형 degrade) -->
<a href="/study" class="block bg-surface border border-default rounded-card p-5 hover:bg-surface-hover transition-colors group">
<div class="flex items-center justify-between">
<span class="text-[11px] font-bold text-dim uppercase tracking-wider">학습</span>
<GraduationCap size={16} class="text-faint" />
</div>
<div class="text-[15px] font-semibold text-text mt-3 group-hover:text-accent transition-colors">암기 노트 학습 시작 →</div>
<div class="text-[11px] text-dim mt-1">검수함 · 복습함 · 암기카드</div>
</a>
<!-- 도메인 분포 + 파이프라인 -->
{#if domainDist.length > 0}
<div class="bg-surface border border-default rounded-card p-5">
<div class="text-[11px] font-bold text-dim uppercase tracking-wider mb-2">도메인 분포</div>
<div class="text-[11px] text-faint mb-3">전체 <strong class="text-base font-bold text-text tracking-tight align-baseline">{domainTotal.toLocaleString()}</strong></div>
<!-- 분포 막대 -->
<div class="flex gap-0.5 h-2 rounded mb-4 overflow-hidden">
{#each domainDist as d (d.name)}
<div class="h-full rounded-sm {domainBgClass(d.name)}" style="width:{domainTotal > 0 ? (d.count / domainTotal) * 100 : 0}%"></div>
{/each}
</div>
<div class="flex flex-col gap-1.5">
{#each domainDist.slice(0, 6) as d (d.name)}
<a href="/documents?domain={encodeURIComponent(d.name)}" class="flex items-center gap-2 text-xs hover:text-accent transition-colors group">
<span class="w-2.5 h-2.5 rounded-sm shrink-0 {domainBgClass(d.name)}"></span>
<span class="flex-1 text-text truncate group-hover:text-accent">{domainLabel(d.name)}</span>
<span class="font-semibold text-dim tabular-nums">{d.count.toLocaleString()}</span>
</a>
{/each}
</div>
<!-- 파이프라인 칩 (안2 흡수) -->
<div class="flex items-center gap-1.5 flex-wrap mt-4 pt-3.5 border-t border-default">
<span class="text-[10px] text-faint uppercase tracking-wide mr-1">파이프라인</span>
{#if totalFailed > 0}<span class="text-[10px] font-bold rounded px-2 py-0.5 text-error bg-error/10">실패 {totalFailed}</span>{/if}
{#if totalPending > 0}<span class="text-[10px] font-bold rounded px-2 py-0.5 text-warning bg-warning/10">대기 {totalPending}</span>{/if}
{#if totalProcessing > 0}<span class="text-[10px] font-bold rounded px-2 py-0.5 text-success bg-success/10">처리중 {totalProcessing}</span>{/if}
{#if totalFailed === 0 && totalPending === 0 && totalProcessing === 0}<span class="text-[10px] font-bold rounded px-2 py-0.5 text-success bg-success/10">정상</span>{/if}
</div>
</div>
{/if}
<!-- 고정 항목 -->
{#if pinnedMemos.length > 0}
<div class="bg-surface border border-default rounded-card p-5">
<div class="flex items-baseline justify-between mb-3">
<span class="text-[11px] font-bold text-dim uppercase tracking-wider">고정 항목</span>
<a href="/memos" class="text-[11px] text-accent hover:underline">관리 →</a>
</div>
<div class="flex flex-col gap-2">
{#each pinnedMemos as memo (memo.id)}
<a href="/memos" class="flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-bg hover:bg-surface-hover transition-colors">
<span class="text-[9px] font-bold rounded px-1.5 py-0.5 uppercase tracking-wide shrink-0 mt-0.5 text-accent-hover bg-accent/10">메모</span>
<span class="text-xs text-text leading-snug flex-1">{pinTitle(memo)}</span>
<Pin size={11} class="text-faint shrink-0 mt-0.5" />
</a>
{/each}
</div>
</div>
{/if}
</div>
</div>
<!-- ═══ 파이프라인 상세 (실패 있을 때 자동 펼침) ═══ -->
<details <details
class="mt-5"
open={pipelineOpen} open={pipelineOpen}
ontoggle={(e) => { if (!e.currentTarget.open) pipelineManualClosed = true; }} ontoggle={(e) => { if (!e.currentTarget.open) pipelineManualClosed = true; }}
> >
<summary <summary class="flex items-center justify-between px-5 py-3.5 bg-surface border border-default rounded-card cursor-pointer hover:bg-surface-hover transition-colors select-none list-none">
class="flex items-center justify-between px-5 py-3.5 bg-surface border border-default rounded-lg
cursor-pointer hover:bg-surface-hover transition-colors select-none list-none"
>
<span class="text-sm font-semibold text-text flex items-center gap-2"> <span class="text-sm font-semibold text-text flex items-center gap-2">
<ChevronRight size={14} class="transition-transform details-chevron" /> <ChevronRight size={14} class="transition-transform details-chevron" />
파이프라인 파이프라인 상세
</span> </span>
<span class="text-xs text-dim flex items-center gap-2.5"> <span class="text-xs text-dim flex items-center gap-2.5">
{#if totalFailed > 0} {#if totalFailed > 0}<span class="text-error font-medium">실패 {totalFailed}</span>{/if}
<span class="text-error font-medium">실패 {totalFailed}</span> {#if totalPending > 0}<span>대기 {totalPending}</span>{/if}
{/if} {#if totalFailed === 0 && totalPending === 0}<span>처리 완료</span>{/if}
{#if totalPending > 0}
<span>대기 {totalPending}</span>
{/if}
{#if totalFailed === 0 && totalPending === 0}
<span>처리 완료</span>
{/if}
</span> </span>
</summary> </summary>
<div class="mt-2 px-5 py-4 bg-surface border border-default rounded-lg"> <div class="mt-2 px-5 py-4 bg-surface border border-default rounded-card">
<p class="text-xs text-dim mb-3">최근 24시간</p> <p class="text-xs text-dim mb-3">최근 24시간</p>
{#if pipelineRows.length > 0} {#if pipelineRows.length > 0}
<div class="space-y-3"> <div class="space-y-3">
@@ -522,9 +448,7 @@
<span class="text-dim"> <span class="text-dim">
{row.label} {row.label}
{#if row.oldestPendingAgeSec && row.oldestPendingAgeSec > 600} {#if row.oldestPendingAgeSec && row.oldestPendingAgeSec > 600}
<span class="ml-1 text-warning" title="가장 오래된 pending 의 경과 시간"> <span class="ml-1 text-warning" title="가장 오래된 pending 의 경과 시간">({formatAge(row.oldestPendingAgeSec)})</span>
({formatAge(row.oldestPendingAgeSec)})
</span>
{/if} {/if}
</span> </span>
<span class="text-dim tabular-nums"> <span class="text-dim tabular-nums">
@@ -551,22 +475,14 @@
</div> </div>
</div> </div>
{#snippet stat(value: string, label: string, colorClass = 'text-text')}
<div class="flex flex-col items-start px-4 first:pl-0 border-l border-default first:border-l-0 min-w-[64px]">
<span class="text-xl font-bold tracking-tight leading-none {colorClass}">{value}</span>
<span class="text-[10px] text-faint mt-1 uppercase tracking-wide">{label}</span>
</div>
{/snippet}
<style> <style>
details[open] .details-chevron { transform: rotate(90deg); } details[open] :global(.details-chevron) { transform: rotate(90deg); }
details summary::-webkit-details-marker { display: none; } details summary::-webkit-details-marker { display: none; }
.memo-content-pin :global(p) { margin: 0.2em 0; }
.memo-content-pin :global(ul), .memo-content-pin :global(ol) { margin: 0.2em 0; padding-left: 1.5em; }
.memo-content-pin :global(code) { background: var(--bg); padding: 0.1em 0.3em; border-radius: 3px; font-size: 0.85em; }
.memo-content-pin :global(a) { color: var(--accent); }
.memo-content-pin :global(.memo-checkbox) { cursor: pointer; width: 14px; height: 14px; accent-color: var(--accent); vertical-align: middle; margin-right: 3px; }
.memo-content-pin :global(li:has(.memo-checkbox)) { list-style: none; margin-left: -1.5em; }
.memo-content-pin :global(.memo-task-done) { opacity: 0.5; text-decoration: line-through; }
/* 체크 후 10초 경과 항목 자동 숨김 (`show-hidden` 클래스로 토글 해제) */
.memo-content-pin :global(.memo-task-hidden) { display: none; }
.memo-content-pin.show-hidden :global(.memo-task-hidden) { display: list-item; }
.memo-content-pin :global(.due-badge) { display: inline-block; font-size: 10px; padding: 1px 5px; border-radius: 8px; margin-left: 3px; }
.memo-content-pin :global(.due-overdue) { background: rgba(245, 86, 78, 0.15); color: var(--error); }
.memo-content-pin :global(.due-soon) { background: rgba(251, 191, 36, 0.15); color: var(--warning); }
.memo-content-pin :global(.due-normal) { background: var(--surface); color: var(--text-dim); }
.memo-content-pin :global(.due-done) { background: var(--surface); color: var(--text-dim); opacity: 0.6; }
</style> </style>
+62 -62
View File
@@ -410,20 +410,20 @@
</div><!-- /.digest-page --> </div><!-- /.digest-page -->
<style> <style>
/* ── 팔레트 로컬 재정의 ── /* ── 세이지 팔레트 로컬 재정의 ──
앱 :root 다크 토큰(--surface:#1a1d27, --accent:파랑 등)이 하위 var() 로 새지 않도록 앱 :root 다크 토큰(--surface:#1a1d27, --accent:파랑 등)이 하위 var() 로 새지 않도록
이 subtree 에서 값으로 덮어쓴다. 하위 모든 var(--surface/--card/--line/--brand …)는 이 subtree 에서 세이지값으로 덮어쓴다. 하위 모든 var(--surface/--card/--line/--brand …)는
여기서 해석된다. 검정(#000/#1f2024) 미사용. */ 여기서 해석된다. 검정(#000/#1f2024) 미사용. */
.digest-page { .digest-page {
--brand: #d97757; --brand: #4f8a6b;
--brand-d: #c2603f; --brand-d: #3d7256;
--surface: #f0eee6; --surface: #ecf0e8;
--card: #fff; --card: #fff;
--ink: #2e2420; --ink: #23291f;
--muted: #6b6f76; --muted: #697061;
--line: #e3e0d6; --line: #dde3d6;
font-family: 'Apple SD Gothic Neo', 'Noto Sans KR', 'Malgun Gothic', system-ui, sans-serif; font-family: 'Apple SD Gothic Neo', 'Noto Sans KR', 'Malgun Gothic', system-ui, sans-serif;
color: #3a322a; color: #333a2d;
} }
/* ── App shell ── */ /* ── App shell ── */
@@ -437,14 +437,14 @@
/* ── Masthead ── */ /* ── Masthead ── */
header.bar { header.bar {
background: #faf7f1; background: #f4f7f1;
border-bottom: 3px solid var(--brand); border-bottom: 3px solid var(--brand);
padding: 0 32px; padding: 0 32px;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0; gap: 0;
min-height: 56px; min-height: 56px;
box-shadow: 0 1px 0 #e3e0d6; box-shadow: 0 1px 0 #dde3d6;
} }
header.bar .mark { header.bar .mark {
display: flex; display: flex;
@@ -467,7 +467,7 @@
header.bar h1 { header.bar h1 {
font-size: 15px; font-size: 15px;
font-weight: 700; font-weight: 700;
color: #3a322a; color: #333a2d;
margin: 0; margin: 0;
letter-spacing: -0.01em; letter-spacing: -0.01em;
white-space: nowrap; white-space: nowrap;
@@ -493,11 +493,11 @@
header.bar .stat-val { header.bar .stat-val {
font-size: 13px; font-size: 13px;
font-weight: 700; font-weight: 700;
color: #3a322a; color: #333a2d;
} }
header.bar .stat-lbl { header.bar .stat-lbl {
font-size: 10px; font-size: 10px;
color: #9a8e84; color: #9aa090;
letter-spacing: 0.04em; letter-spacing: 0.04em;
} }
@@ -508,20 +508,20 @@
gap: 4px; gap: 4px;
} }
.date-btn { .date-btn {
background: #f0eee6; background: #ecf0e8;
border: 1px solid #d8d3c8; border: 1px solid #cfd7c6;
border-radius: 4px; border-radius: 4px;
width: 26px; width: 26px;
height: 28px; height: 28px;
font-size: 14px; font-size: 14px;
font-weight: 700; font-weight: 700;
color: #5a4f46; color: #4a5142;
cursor: pointer; cursor: pointer;
line-height: 1; line-height: 1;
transition: background 0.15s, color 0.15s; transition: background 0.15s, color 0.15s;
} }
.date-btn:hover:not(:disabled) { .date-btn:hover:not(:disabled) {
background: #e7e2d6; background: #e3ebdf;
color: var(--brand-d); color: var(--brand-d);
} }
.date-btn:disabled { .date-btn:disabled {
@@ -529,13 +529,13 @@
cursor: not-allowed; cursor: not-allowed;
} }
.date-select { .date-select {
background: #f0eee6; background: #ecf0e8;
border: 1px solid #d8d3c8; border: 1px solid #cfd7c6;
border-radius: 4px; border-radius: 4px;
padding: 4px 8px; padding: 4px 8px;
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
color: #5a4f46; color: #4a5142;
letter-spacing: 0.02em; letter-spacing: 0.02em;
max-width: 220px; max-width: 220px;
cursor: pointer; cursor: pointer;
@@ -561,7 +561,7 @@
padding: 10px 14px; padding: 10px 14px;
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
color: #7a6e64; color: #697061;
cursor: pointer; cursor: pointer;
border: none; border: none;
background: none; background: none;
@@ -571,8 +571,8 @@
font-family: inherit; font-family: inherit;
} }
.country-nav .nav-item:hover { .country-nav .nav-item:hover {
color: #3a322a; color: #333a2d;
border-bottom-color: #d8d3c8; border-bottom-color: #cfd7c6;
} }
.country-nav .nav-item.active { .country-nav .nav-item.active {
color: var(--brand); color: var(--brand);
@@ -586,16 +586,16 @@
border-radius: 2px; border-radius: 2px;
letter-spacing: 0.05em; letter-spacing: 0.05em;
background: var(--surface); background: var(--surface);
color: #7a6e64; color: #697061;
} }
.country-nav .nav-item.active .cc-chip { .country-nav .nav-item.active .cc-chip {
background: rgba(217, 119, 87, 0.15); background: rgba(79, 138, 107, 0.15);
color: var(--brand); color: var(--brand);
} }
.country-nav .topic-count { .country-nav .topic-count {
font-size: 10px; font-size: 10px;
font-weight: 400; font-weight: 400;
color: #9a8e84; color: #9aa090;
} }
/* ── Body ── */ /* ── Body ── */
@@ -626,7 +626,7 @@
.edition-line .edition-date { .edition-line .edition-date {
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
color: #7a6e64; color: #697061;
letter-spacing: 0.04em; letter-spacing: 0.04em;
} }
.edition-line .edition-sep { .edition-line .edition-sep {
@@ -636,13 +636,13 @@
} }
.edition-line .edition-sub { .edition-line .edition-sub {
font-size: 11px; font-size: 11px;
color: #9a8e84; color: #9aa090;
} }
/* ── Lead story block ── */ /* ── Lead story block ── */
.lead-block { .lead-block {
background: var(--card); background: var(--card);
border: 1px solid #d8d3c8; border: 1px solid #cfd7c6;
border-top: 4px solid var(--brand); border-top: 4px solid var(--brand);
border-radius: 4px; border-radius: 4px;
padding: 28px 32px 24px; padding: 28px 32px 24px;
@@ -657,7 +657,7 @@
right: 0; right: 0;
width: 200px; width: 200px;
height: 100%; height: 100%;
background: linear-gradient(to left, rgba(217, 119, 87, 0.05), transparent); background: linear-gradient(to left, rgba(79, 138, 107, 0.05), transparent);
pointer-events: none; pointer-events: none;
} }
.lead-meta { .lead-meta {
@@ -683,9 +683,9 @@
gap: 5px; gap: 5px;
font-size: 11px; font-size: 11px;
font-weight: 600; font-weight: 600;
color: #3a322a; color: #333a2d;
background: var(--surface); background: var(--surface);
border: 1px solid #d8d3c8; border: 1px solid #cfd7c6;
padding: 3px 8px; padding: 3px 8px;
border-radius: 3px; border-radius: 3px;
} }
@@ -700,27 +700,27 @@
} }
.lead-meta .cnt-badge { .lead-meta .cnt-badge {
font-size: 11px; font-size: 11px;
color: #7a6e64; color: #697061;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 4px; gap: 4px;
} }
.lead-meta .cnt-badge strong { .lead-meta .cnt-badge strong {
color: #3a322a; color: #333a2d;
font-weight: 700; font-weight: 700;
} }
.lead-headline { .lead-headline {
font-size: 28px; font-size: 28px;
font-weight: 800; font-weight: 800;
line-height: 1.25; line-height: 1.25;
color: #2e2420; color: #23291f;
letter-spacing: -0.02em; letter-spacing: -0.02em;
margin: 0 0 14px; margin: 0 0 14px;
} }
.lead-summary { .lead-summary {
font-size: 14px; font-size: 14px;
line-height: 1.75; line-height: 1.75;
color: #5a4f46; color: #4a5142;
margin: 0 0 20px; margin: 0 0 20px;
max-width: 680px; max-width: 680px;
} }
@@ -747,7 +747,7 @@
.lead-articles a { .lead-articles a {
font-size: 13px; font-size: 13px;
font-weight: 600; font-weight: 600;
color: #3a322a; color: #333a2d;
text-decoration: none; text-decoration: none;
line-height: 1.45; line-height: 1.45;
} }
@@ -766,7 +766,7 @@
font-weight: 700; font-weight: 700;
letter-spacing: 0.06em; letter-spacing: 0.06em;
text-transform: uppercase; text-transform: uppercase;
color: #9a8e84; color: #9aa090;
white-space: nowrap; white-space: nowrap;
} }
.lead-imp-bar .bar-track { .lead-imp-bar .bar-track {
@@ -800,7 +800,7 @@
font-weight: 800; font-weight: 800;
letter-spacing: 0.12em; letter-spacing: 0.12em;
text-transform: uppercase; text-transform: uppercase;
color: #9a8e84; color: #9aa090;
white-space: nowrap; white-space: nowrap;
} }
.section-head .sh-line { .section-head .sh-line {
@@ -820,7 +820,7 @@
/* ── Story card ── */ /* ── Story card ── */
.story-card { .story-card {
background: var(--card); background: var(--card);
border: 1px solid #d8d3c8; border: 1px solid #cfd7c6;
border-radius: 4px; border-radius: 4px;
padding: 18px 20px 16px; padding: 18px 20px 16px;
display: flex; display: flex;
@@ -829,7 +829,7 @@
transition: box-shadow 0.15s; transition: box-shadow 0.15s;
} }
.story-card:hover { .story-card:hover {
box-shadow: 0 2px 12px rgba(90, 70, 55, 0.09); box-shadow: 0 2px 12px rgba(74, 81, 66, 0.09);
} }
.story-card.featured { .story-card.featured {
border-top: 3px solid var(--brand-d); border-top: 3px solid var(--brand-d);
@@ -846,9 +846,9 @@
gap: 5px; gap: 5px;
font-size: 10px; font-size: 10px;
font-weight: 600; font-weight: 600;
color: #3a322a; color: #333a2d;
background: var(--surface); background: var(--surface);
border: 1px solid #d8d3c8; border: 1px solid #cfd7c6;
padding: 2px 7px; padding: 2px 7px;
border-radius: 3px; border-radius: 3px;
} }
@@ -863,21 +863,21 @@
} }
.card-meta .cnt-tag { .card-meta .cnt-tag {
font-size: 10px; font-size: 10px;
color: #9a8e84; color: #9aa090;
margin-left: auto; margin-left: auto;
} }
.card-title { .card-title {
font-size: 15px; font-size: 15px;
font-weight: 700; font-weight: 700;
line-height: 1.35; line-height: 1.35;
color: #2e2420; color: #23291f;
letter-spacing: -0.01em; letter-spacing: -0.01em;
margin: 0; margin: 0;
} }
.card-summary { .card-summary {
font-size: 12px; font-size: 12px;
line-height: 1.65; line-height: 1.65;
color: #5a4f46; color: #4a5142;
margin: 0; margin: 0;
flex: 1; flex: 1;
} }
@@ -891,7 +891,7 @@
.card-articles a { .card-articles a {
font-size: 11px; font-size: 11px;
font-weight: 600; font-weight: 600;
color: #3a322a; color: #333a2d;
text-decoration: none; text-decoration: none;
line-height: 1.4; line-height: 1.4;
display: flex; display: flex;
@@ -904,7 +904,7 @@
width: 3px; width: 3px;
height: 3px; height: 3px;
border-radius: 50%; border-radius: 50%;
background: #b8a898; background: #9aa090;
flex-shrink: 0; flex-shrink: 0;
margin-top: 5px; margin-top: 5px;
} }
@@ -923,7 +923,7 @@
.card-imp .imp-val { .card-imp .imp-val {
font-size: 10px; font-size: 10px;
font-weight: 600; font-weight: 600;
color: #9a8e84; color: #9aa090;
} }
/* ── Sidebar stack ── */ /* ── Sidebar stack ── */
@@ -934,7 +934,7 @@
} }
.sidebar-card { .sidebar-card {
background: var(--card); background: var(--card);
border: 1px solid #d8d3c8; border: 1px solid #cfd7c6;
border-radius: 4px; border-radius: 4px;
padding: 14px 16px; padding: 14px 16px;
display: flex; display: flex;
@@ -958,24 +958,24 @@
.sidebar-card .cc-name { .sidebar-card .cc-name {
font-size: 10px; font-size: 10px;
font-weight: 600; font-weight: 600;
color: #7a6e64; color: #697061;
} }
.sidebar-card .sc-cnt { .sidebar-card .sc-cnt {
font-size: 10px; font-size: 10px;
color: #9a8e84; color: #9aa090;
margin-left: auto; margin-left: auto;
} }
.sidebar-card .s-title { .sidebar-card .s-title {
font-size: 13px; font-size: 13px;
font-weight: 700; font-weight: 700;
line-height: 1.35; line-height: 1.35;
color: #2e2420; color: #23291f;
margin: 0; margin: 0;
} }
.sidebar-card .s-summary { .sidebar-card .s-summary {
font-size: 11px; font-size: 11px;
line-height: 1.55; line-height: 1.55;
color: #5a4f46; color: #4a5142;
margin: 0; margin: 0;
} }
.sidebar-card .s-link { .sidebar-card .s-link {
@@ -995,7 +995,7 @@
} }
.compact-card { .compact-card {
background: var(--card); background: var(--card);
border: 1px solid #d8d3c8; border: 1px solid #cfd7c6;
border-radius: 4px; border-radius: 4px;
padding: 14px 16px; padding: 14px 16px;
display: flex; display: flex;
@@ -1019,24 +1019,24 @@
.compact-card .c-ko { .compact-card .c-ko {
font-size: 10px; font-size: 10px;
font-weight: 600; font-weight: 600;
color: #7a6e64; color: #697061;
} }
.compact-card .c-cnt { .compact-card .c-cnt {
font-size: 10px; font-size: 10px;
color: #9a8e84; color: #9aa090;
margin-left: auto; margin-left: auto;
} }
.compact-card .c-title { .compact-card .c-title {
font-size: 13px; font-size: 13px;
font-weight: 700; font-weight: 700;
line-height: 1.35; line-height: 1.35;
color: #2e2420; color: #23291f;
margin: 0; margin: 0;
} }
.compact-card .c-summary { .compact-card .c-summary {
font-size: 11px; font-size: 11px;
line-height: 1.55; line-height: 1.55;
color: #5a4f46; color: #4a5142;
margin: 0; margin: 0;
flex: 1; flex: 1;
} }
@@ -1056,11 +1056,11 @@
.compact-card .c-imp-fill { .compact-card .c-imp-fill {
height: 100%; height: 100%;
border-radius: 1px; border-radius: 1px;
background: rgba(217, 119, 87, 0.6); background: rgba(79, 138, 107, 0.6);
} }
/* ── Importance swatches ── */ /* ── Importance swatches ── */
.imp-high { background: rgba(217, 119, 87, 0.85); } .imp-high { background: rgba(79, 138, 107, 0.85); }
/* 극단적 긴 무공백 토큰(연속 CJK·URL) 가로 오버플로 방어 */ /* 극단적 긴 무공백 토큰(연속 CJK·URL) 가로 오버플로 방어 */
.lead-headline, .lead-summary, .card-title, .card-summary, .lead-headline, .lead-summary, .card-title, .card-summary,
File diff suppressed because it is too large Load Diff
+11 -11
View File
@@ -292,10 +292,10 @@
}; };
const KIND_BADGE_CLASS = { const KIND_BADGE_CLASS = {
note: 'bg-surface text-dim', note: 'bg-surface text-dim',
task: 'bg-indigo-100 text-indigo-700', task: 'bg-accent/15 text-accent-hover',
calendar_event: 'bg-blue-100 text-blue-700', calendar_event: 'bg-domain-engineering/15 text-domain-engineering',
activity_log: 'bg-emerald-100 text-emerald-700', activity_log: 'bg-success/15 text-success',
reference: 'bg-amber-100 text-amber-700', reference: 'bg-domain-reference/15 text-domain-reference',
}; };
async function handleCheckboxClick(e, memo) { async function handleCheckboxClick(e, memo) {
@@ -400,9 +400,9 @@
</div> </div>
{/if} {/if}
<!-- ═══ 빠른 입력 ═══ --> <!-- ═══ 빠른 입력 (상단 고정) ═══ -->
{#if !showArchived} {#if !showArchived}
<Card class="mb-5"> <Card class="mb-5 sticky top-0 z-10 shadow-sm">
<!-- 선택적 제목 --> <!-- 선택적 제목 -->
{#if showTitle} {#if showTitle}
<input <input
@@ -526,7 +526,7 @@
{#if memo.source_channel === 'voice' || memo.ai_event_kind || memo._last_promoted} {#if memo.source_channel === 'voice' || memo.ai_event_kind || memo._last_promoted}
<div class="flex flex-wrap items-center gap-1.5 mb-1.5"> <div class="flex flex-wrap items-center gap-1.5 mb-1.5">
{#if memo.source_channel === 'voice'} {#if memo.source_channel === 'voice'}
<span class="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] bg-rose-100 text-rose-700" title="음성 메모"> <span class="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] bg-domain-philosophy/15 text-domain-philosophy" title="음성 메모">
<Mic size={10} /> 음성 <Mic size={10} /> 음성
</span> </span>
{/if} {/if}
@@ -536,7 +536,7 @@
</span> </span>
{/if} {/if}
{#if memo._last_promoted} {#if memo._last_promoted}
<a href={`/events/${memo._last_promoted.event_id}`} class="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] bg-emerald-100 text-emerald-700 hover:bg-emerald-200"> <a href={`/events/${memo._last_promoted.event_id}`} class="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] bg-success/15 text-success hover:bg-success/25">
<ArrowRight size={10} /> events #{memo._last_promoted.event_id} <ArrowRight size={10} /> events #{memo._last_promoted.event_id}
</a> </a>
{/if} {/if}
@@ -586,13 +586,13 @@
<!-- PR-2B: AI triage 결과 → 1-click promote 버튼 (분류 결과 있고 dismissed 아닌 메모) --> <!-- PR-2B: AI triage 결과 → 1-click promote 버튼 (분류 결과 있고 dismissed 아닌 메모) -->
{#if editingId !== memo.id && memo.ai_event_kind && memo.ai_event_kind !== 'note' && !memo._last_promoted && !showArchived} {#if editingId !== memo.id && memo.ai_event_kind && memo.ai_event_kind !== 'note' && !memo._last_promoted && !showArchived}
<div class="flex flex-wrap gap-1 mt-2 pt-2 border-t border-default/30"> <div class="flex flex-wrap gap-1 mt-2 pt-2 border-t border-default/30">
<button onclick={() => promoteMemo(memo.id, 'task')} class={`inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] transition-colors ${memo.ai_event_kind === 'task' ? 'bg-indigo-500 text-white hover:bg-indigo-600' : 'bg-surface text-dim hover:bg-surface-hover hover:text-text'}`}> <button onclick={() => promoteMemo(memo.id, 'task')} class={`inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] transition-colors ${memo.ai_event_kind === 'task' ? 'bg-accent text-white hover:bg-accent-hover' : 'bg-surface text-dim hover:bg-surface-hover hover:text-text'}`}>
<FileText size={11} /> 할 일로 <FileText size={11} /> 할 일로
</button> </button>
<button onclick={() => promoteMemo(memo.id, 'calendar_event')} class={`inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] transition-colors ${memo.ai_event_kind === 'calendar_event' ? 'bg-blue-500 text-white hover:bg-blue-600' : 'bg-surface text-dim hover:bg-surface-hover hover:text-text'}`}> <button onclick={() => promoteMemo(memo.id, 'calendar_event')} class={`inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] transition-colors ${memo.ai_event_kind === 'calendar_event' ? 'bg-domain-engineering text-white hover:opacity-90' : 'bg-surface text-dim hover:bg-surface-hover hover:text-text'}`}>
<Calendar size={11} /> 일정으로 <Calendar size={11} /> 일정으로
</button> </button>
<button onclick={() => promoteMemo(memo.id, 'activity_log')} class={`inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] transition-colors ${memo.ai_event_kind === 'activity_log' ? 'bg-emerald-500 text-white hover:bg-emerald-600' : 'bg-surface text-dim hover:bg-surface-hover hover:text-text'}`}> <button onclick={() => promoteMemo(memo.id, 'activity_log')} class={`inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] transition-colors ${memo.ai_event_kind === 'activity_log' ? 'bg-success text-white hover:opacity-90' : 'bg-surface text-dim hover:bg-surface-hover hover:text-text'}`}>
<Activity size={11} /> 활동으로 <Activity size={11} /> 활동으로
</button> </button>
<button onclick={() => dismissEventSuggestion(memo.id)} class="inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] bg-surface text-dim hover:bg-surface-hover hover:text-text transition-colors"> <button onclick={() => dismissEventSuggestion(memo.id)} class="inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] bg-surface text-dim hover:bg-surface-hover hover:text-text transition-colors">
+245 -265
View File
@@ -1,101 +1,59 @@
<script lang="ts"> <script lang="ts">
// 야간 수집 뉴스 브리핑 (Morning Briefing) — 매일 KST 05:10 cron 으로 만들어진 // 모닝브리핑 /news — 확정 시안 '편집 신문 1면'. 야간(KST 0~5h) 수집 뉴스를
// topic×country 비교 분석 1페이지 카드. 기존 article list / source tree / // topic×country 비교 분석. 전 기능 보존(국가 관점·기사ID·차이/공통·인용·지난흐름·읽음/별표·날짜).
// 북마크 / 노트 / 필터 UI 는 폐기 (PR-MorningBriefing-2 swap). // 이모지 국기 → 국가 색칩(no-emoji 규칙). 데이터·API 는 기존 /briefing 그대로.
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { api, type ApiError } from '$lib/api'; import { api, type ApiError } from '$lib/api';
import Card from '$lib/components/ui/Card.svelte';
type CountryPerspective = {
country: string;
summary: string;
article_ids: number[];
};
type KeyQuote = {
country: string;
source: string;
quote: string;
};
type CountryPerspective = { country: string; summary: string; article_ids: number[] };
type KeyQuote = { country: string; source: string; quote: string };
type BriefingTopic = { type BriefingTopic = {
id: number; id: number; topic_rank: number; topic_label: string; headline: string;
topic_rank: number; country_perspectives: CountryPerspective[]; divergences: string[]; convergences: string[];
topic_label: string; key_quotes: KeyQuote[]; historical_context: string | null; cluster_members: number[];
headline: string; article_count: number; country_count: number; importance_score: number; llm_fallback_used: boolean;
country_perspectives: CountryPerspective[]; is_read: boolean; read_at: string | null; highlighted: boolean; highlighted_at: string | null;
divergences: string[];
convergences: string[];
key_quotes: KeyQuote[];
historical_context: string | null;
cluster_members: number[];
article_count: number;
country_count: number;
importance_score: number;
llm_fallback_used: boolean;
is_read: boolean;
read_at: string | null;
highlighted: boolean;
highlighted_at: string | null;
}; };
type BriefingDateSummary = { type BriefingDateSummary = {
briefing_date: string; briefing_date: string; total_topics: number; total_articles: number;
total_topics: number; status: string; read_count: number; highlighted_count: number;
total_articles: number;
status: string;
read_count: number;
highlighted_count: number;
}; };
type Briefing = { type Briefing = {
briefing_date: string; briefing_date: string; window_start: string; window_end: string;
window_start: string; total_articles: number; total_countries: number; total_topics: number;
window_end: string; llm_calls: number; llm_failures: number;
total_articles: number;
total_countries: number;
total_topics: number;
llm_calls: number;
llm_failures: number;
status: 'success' | 'partial' | 'failed' | 'empty'; status: 'success' | 'partial' | 'failed' | 'empty';
headline_oneliner: string | null; headline_oneliner: string | null; topics: BriefingTopic[];
topics: BriefingTopic[];
}; };
const COUNTRY_META: Record<string, { flag: string; label: string }> = { // 국가 라벨(한국어, 이모지 없음) + 색칩 토큰
KR: { flag: '🇰🇷', label: '한국' }, const COUNTRY_LABEL: Record<string, string> = {
US: { flag: '🇺🇸', label: '미국' }, KR: '한국', US: '미국', JP: '일본', CN: '중국', HK: '홍콩', TW: '대만',
JP: { flag: '🇯🇵', label: '일본' }, DE: '독일', FR: '프랑스', GB: '영국', UK: '영국', IN: '인도', RU: '러시아',
CN: { flag: '🇨🇳', label: '중국' }, IR: '이란', IL: '이스라엘', PH: '필리핀', AU: '호주', NL: '네덜란드',
HK: { flag: '🇭🇰', label: '홍콩' }, };
TW: { flag: '🇹🇼', label: '대만' }, const COUNTRY_CHIP: Record<string, string> = {
DE: { flag: '🇩🇪', label: '독일' }, KR: 'bg-warning', US: 'bg-domain-engineering', JP: 'bg-domain-reference',
FR: { flag: '🇫🇷', label: '프랑스' }, DE: 'bg-accent-hover', HK: 'bg-domain-philosophy', CN: 'bg-error',
GB: { flag: '🇬🇧', label: '영국' }, TW: 'bg-domain-general', GB: 'bg-domain-engineering', UK: 'bg-domain-engineering',
UK: { flag: '🇬🇧', label: '영국' }, FR: 'bg-domain-philosophy', IN: 'bg-domain-reference', RU: 'bg-error',
IN: { flag: '🇮🇳', label: '인도' }, IL: 'bg-accent', IR: 'bg-warning',
RU: { flag: '🇷🇺', label: '러시아' },
IR: { flag: '🇮🇷', label: '이란' },
IL: { flag: '🇮🇱', label: '이스라엘' },
PH: { flag: '🇵🇭', label: '필리핀' },
AU: { flag: '🇦🇺', label: '호주' },
NL: { flag: '🇳🇱', label: '네덜란드' },
}; };
function countryLabel(code: string): string { function countryLabel(code: string): string {
const meta = COUNTRY_META[code?.toUpperCase()]; return COUNTRY_LABEL[code?.toUpperCase?.()] ?? code;
return meta ? `${meta.flag} ${meta.label}` : code; }
function countryChip(code: string): string {
return COUNTRY_CHIP[code?.toUpperCase?.()] ?? 'bg-dim';
} }
let briefing = $state<Briefing | null>(null); let briefing = $state<Briefing | null>(null);
let loading = $state(true); let loading = $state(true);
let errorMsg = $state<string | null>(null); let errorMsg = $state<string | null>(null);
// 2026-05-13 추가 — 날짜 선택 + 카드 액션
let availableDates = $state<BriefingDateSummary[]>([]); let availableDates = $state<BriefingDateSummary[]>([]);
let selectedDate = $state<string>(''); // YYYY-MM-DD ('' = 최신) let selectedDate = $state<string>('');
async function loadBriefing(dateStr: string) { async function loadBriefing(dateStr: string) {
loading = true; loading = true; errorMsg = null;
errorMsg = null;
try { try {
const path = dateStr ? `/briefing?date=${dateStr}` : '/briefing/latest'; const path = dateStr ? `/briefing?date=${dateStr}` : '/briefing/latest';
briefing = await api<Briefing>(path); briefing = await api<Briefing>(path);
@@ -109,216 +67,238 @@
loading = false; loading = false;
} }
} }
async function loadDates() { async function loadDates() {
try { try { availableDates = await api<BriefingDateSummary[]>('/briefing/dates'); }
availableDates = await api<BriefingDateSummary[]>('/briefing/dates'); catch { availableDates = []; }
} catch {
availableDates = [];
}
}
function onDateChange() {
loadBriefing(selectedDate);
} }
function onDateChange() { loadBriefing(selectedDate); }
async function toggleRead(topic: BriefingTopic) { async function toggleRead(topic: BriefingTopic) {
if (!briefing) return; if (!briefing) return;
const next = !topic.is_read; const next = !topic.is_read;
try { try {
const r = await api<{ id: number; is_read: boolean; read_at: string | null; highlighted: boolean; highlighted_at: string | null }>( const r = await api<{ is_read: boolean; read_at: string | null }>(
`/briefing/topics/${topic.id}/read`, `/briefing/topics/${topic.id}/read`, { method: 'PATCH', body: JSON.stringify({ value: next }) });
{ method: 'PATCH', body: JSON.stringify({ value: next }) } topic.is_read = r.is_read; topic.read_at = r.read_at;
); } catch (e) { console.error('toggleRead failed', e); }
topic.is_read = r.is_read;
topic.read_at = r.read_at;
} catch (e) {
console.error('toggleRead failed', e);
}
} }
async function toggleHighlight(topic: BriefingTopic) { async function toggleHighlight(topic: BriefingTopic) {
if (!briefing) return; if (!briefing) return;
const next = !topic.highlighted; const next = !topic.highlighted;
try { try {
const r = await api<{ id: number; is_read: boolean; read_at: string | null; highlighted: boolean; highlighted_at: string | null }>( const r = await api<{ highlighted: boolean; highlighted_at: string | null }>(
`/briefing/topics/${topic.id}/highlight`, `/briefing/topics/${topic.id}/highlight`, { method: 'PATCH', body: JSON.stringify({ value: next }) });
{ method: 'PATCH', body: JSON.stringify({ value: next }) } topic.highlighted = r.highlighted; topic.highlighted_at = r.highlighted_at;
); } catch (e) { console.error('toggleHighlight failed', e); }
topic.highlighted = r.highlighted;
topic.highlighted_at = r.highlighted_at;
} catch (e) {
console.error('toggleHighlight failed', e);
}
} }
onMount(async () => { onMount(async () => { await Promise.all([loadDates(), loadBriefing('')]); });
await Promise.all([loadDates(), loadBriefing('')]);
});
const fallbackPct = $derived( const fallbackPct = $derived(
briefing && briefing.llm_calls > 0 briefing && briefing.llm_calls > 0 ? Math.round((briefing.llm_failures / briefing.llm_calls) * 100) : 0
? Math.round((briefing.llm_failures / briefing.llm_calls) * 100)
: 0
); );
const highlightedCount = $derived(briefing ? briefing.topics.filter((t) => t.highlighted).length : 0);
const leadTopic = $derived(briefing && briefing.topics.length > 0 ? briefing.topics[0] : null);
const restTopics = $derived(briefing ? briefing.topics.slice(1) : []);
function folio(rank: number) { return String(rank).padStart(2, '0'); }
</script> </script>
<div class="mx-auto max-w-3xl px-4 py-6 space-y-4"> <div class="nws bg-bg min-h-full p-4 lg:p-6">
<header class="space-y-2"> <div class="max-w-[1240px] mx-auto">
<div class="flex items-center justify-between gap-3 flex-wrap">
<h1 class="text-xl font-semibold">야간 뉴스 브리핑</h1> <!-- ═══ 마스트헤드 ═══ -->
{#if availableDates.length > 0} <header class="bg-surface border border-default rounded-lg relative overflow-hidden px-5 lg:px-7 pt-5 pb-4">
<div class="flex items-center gap-2"> <span class="absolute left-0 top-0 bottom-0 w-[5px] bg-accent"></span>
<label for="briefing-date" class="text-xs text-dim">날짜</label> <div class="flex justify-between items-end flex-wrap gap-3 border-b-2 border-text pb-2.5 mb-3">
<select <div class="nws-serif font-extrabold tracking-tight text-text text-3xl lg:text-4xl leading-none">모닝브리핑</div>
id="briefing-date" <div class="flex items-center gap-2.5 flex-wrap text-xs text-dim font-mono">
bind:value={selectedDate} {#if availableDates.length > 0}
onchange={onDateChange} <select
class="text-sm border border-default rounded-md px-2 py-1 bg-surface" bind:value={selectedDate}
> onchange={onDateChange}
<option value="">최신</option> class="bg-bg border border-default rounded-md px-2 py-1 text-xs text-text"
{#each availableDates as d} aria-label="브리핑 날짜"
<option value={d.briefing_date}> >
{d.briefing_date} · {d.total_topics}토픽 <option value="">최신</option>
{#if d.highlighted_count > 0}{d.highlighted_count}{/if} {#each availableDates as d}
</option> <option value={d.briefing_date}>{d.briefing_date} · {d.total_topics}토픽{#if d.highlighted_count > 0} · {d.highlighted_count}{/if}</option>
{/each}
</select>
{:else if briefing}
<span class="font-bold text-text">{briefing.briefing_date}</span>
{/if}
{#if briefing}
<span>{briefing.total_topics}토픽{#if highlightedCount > 0} · 별표 <span class="text-warning font-bold">{highlightedCount}</span>{/if}</span>
<span>새벽 수집</span>
{/if}
</div>
</div>
{#if briefing?.headline_oneliner}
<div class="nws-serif text-text font-semibold text-lg lg:text-[22px] leading-snug tracking-tight mb-3.5">
<span class="block font-mono text-xs font-bold text-accent-hover uppercase tracking-wider mb-1">오늘의 한 줄</span>
{briefing.headline_oneliner}
</div>
{/if}
{#if briefing}
<div class="flex flex-wrap border-t border-default pt-3">
<div class="flex flex-col gap-0.5 pr-6 border-r border-default">
<span class="nws-serif text-2xl font-extrabold text-text leading-none">{briefing.total_articles}</span>
<span class="text-[11px] text-dim uppercase tracking-wide">총 기사</span>
</div>
<div class="flex flex-col gap-0.5 px-6 border-r border-default">
<span class="nws-serif text-2xl font-extrabold text-text leading-none">{briefing.total_countries}</span>
<span class="text-[11px] text-dim uppercase tracking-wide">개국</span>
</div>
<div class="flex flex-col gap-0.5 px-6">
<span class="nws-serif text-2xl font-extrabold text-text leading-none">{briefing.total_topics}</span>
<span class="text-[11px] text-dim uppercase tracking-wide">토픽</span>
</div>
</div>
{/if}
{#if briefing && (briefing.status === 'partial' || briefing.status === 'failed')}
<div class="flex items-center gap-2.5 mt-3.5 px-3.5 py-2 rounded-md text-[13px]
{briefing.status === 'failed' ? 'bg-error/10 border border-error/30 text-error' : 'bg-warning/10 border border-warning/30 text-warning'}">
<span class="w-2 h-2 rounded-full shrink-0 {briefing.status === 'failed' ? 'bg-error' : 'bg-warning'}"></span>
{#if briefing.status === 'failed'}
LLM 분석 실패율이 높습니다 ({briefing.llm_failures}/{briefing.llm_calls}, {fallbackPct}%). 일부 토픽이 원문 묶음으로 표시됩니다.
{:else}
일부 토픽 LLM 실패 ({briefing.llm_failures}/{briefing.llm_calls}). 다른 토픽은 정상 분석되었습니다.
{/if}
</div>
{/if}
</header>
<!-- ═══ 본문 ═══ -->
{#if loading}
<div class="bg-surface border border-default rounded-lg p-5 mt-4 text-sm text-dim">불러오는 중…</div>
{:else if errorMsg}
<div class="bg-surface border border-default rounded-lg p-5 mt-4 text-sm text-text">{errorMsg}</div>
{:else if briefing}
{#if briefing.status === 'empty'}
<div class="bg-surface border border-default rounded-lg p-5 mt-4">
<p class="text-sm text-text">오늘 새벽({briefing.briefing_date}) 다국 비교 가능한 토픽이 없습니다.</p>
<p class="mt-2 text-xs text-dim">(수집 뉴스 0건 또는 2개국 이상 다룬 주제 없음)</p>
</div>
{:else}
<!-- 리드 토픽 (전체 너비, 관점 2열) -->
{#if leadTopic}
{@render topicCard(leadTopic, true)}
{/if}
<!-- 나머지 토픽 (2열 그리드) -->
{#if restTopics.length > 0}
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4">
{#each restTopics as topic (topic.id)}
{@render topicCard(topic, false)}
{/each} {/each}
</select> </div>
{/if}
{/if}
{/if}
</div>
</div>
{#snippet topicCard(topic, isLead)}
<article class="bg-surface border rounded-lg overflow-hidden relative transition-opacity
{isLead ? 'mt-4' : ''}
{topic.highlighted ? 'border-accent ring-2 ring-accent/25' : 'border-default'}
{topic.is_read ? 'opacity-50 hover:opacity-80' : ''}">
{#if topic.is_read}
<span class="absolute top-3 right-[88px] text-[10px] font-mono font-bold tracking-widest text-error border border-error rounded px-1.5 py-0.5 -rotate-6 opacity-70 pointer-events-none uppercase select-none">읽음</span>
{/if}
<!-- head -->
<div class="flex items-start gap-3.5 px-5 pt-4 pb-3.5 border-b border-default">
<div class="nws-serif font-extrabold leading-none text-text shrink-0 text-center pt-0.5 min-w-[42px]
{topic.highlighted ? 'text-white bg-accent rounded-md px-1 py-1.5' : ''} {isLead ? 'text-3xl' : 'text-2xl'}">{folio(topic.topic_rank)}</div>
<div class="flex-1 min-w-0">
<div class="font-mono text-[11px] tracking-wide uppercase text-accent-hover font-bold mb-1">
{topic.topic_label}{#if topic.llm_fallback_used}<span class="text-dim ml-1 normal-case">(원문 묶음)</span>{/if}
</div>
<div class="nws-serif font-bold leading-tight text-text tracking-tight {isLead ? 'text-[23px]' : 'text-[19px]'}">{topic.headline}</div>
<div class="inline-flex items-center gap-1.5 mt-2 text-xs text-dim font-mono">
<span>{topic.country_count}개국</span><span class="w-1 h-1 rounded-full bg-faint"></span><span>{topic.article_count}</span>
</div>
</div>
<div class="flex gap-1.5 shrink-0">
<button type="button" onclick={() => toggleHighlight(topic)} aria-label="별표 토글" title={topic.highlighted ? '별표 해제' : '별표'}
class="w-[34px] h-[30px] rounded-md border flex items-center justify-center transition-colors
{topic.highlighted ? 'bg-accent border-accent text-white' : 'bg-bg border-default text-dim hover:text-text hover:bg-surface-hover'}">★</button>
<button type="button" onclick={() => toggleRead(topic)} aria-label="읽음 토글" title={topic.is_read ? '읽지 않음으로' : '읽음 처리'}
class="w-[34px] h-[30px] rounded-md border flex items-center justify-center text-xs transition-colors
{topic.is_read ? 'bg-accent/15 border-accent text-accent-hover' : 'bg-bg border-default text-dim hover:text-text hover:bg-surface-hover'}">✓</button>
</div>
</div>
<!-- body -->
<div class="px-5 pt-4 pb-4.5">
{#if topic.country_perspectives.length > 0}
<div class="nws-rule font-mono text-[10px] tracking-wider uppercase text-faint flex items-center gap-2 mb-2">국가별 관점</div>
<div class="grid gap-2.5 {isLead ? 'lg:grid-cols-2' : 'grid-cols-1'}">
{#each topic.country_perspectives as cp}
<div class="border-l-[3px] border-border-strong pl-3 py-0.5">
<div class="flex items-center gap-2 flex-wrap mb-1">
<span class="font-mono text-[10.5px] font-extrabold tracking-wide text-white rounded px-1.5 py-0.5 {countryChip(cp.country)}">{countryLabel(cp.country)}</span>
{#if cp.article_ids.length > 0}
<span class="inline-flex gap-1.5 flex-wrap">
{#each cp.article_ids as id}
<a href={`/documents/${id}`} class="font-mono text-[11px] text-accent-hover bg-accent/12 rounded px-1.5 py-px border border-transparent hover:border-accent transition-colors">#{id}</a>
{/each}
</span>
{/if}
</div>
<div class="text-[13.5px] text-text leading-relaxed">{cp.summary}</div>
</div>
{/each}
</div>
{/if}
{#if topic.divergences.length > 0 || topic.convergences.length > 0}
<div class="grid gap-2.5 mt-3.5 {isLead && topic.divergences.length > 0 && topic.convergences.length > 0 ? 'lg:grid-cols-2' : 'grid-cols-1'}">
{#if topic.divergences.length > 0}
<div class="rounded-lg px-3.5 py-3 text-[13px] leading-relaxed bg-error/[0.06] border border-error/20">
<span class="block font-mono text-[10px] font-bold tracking-wide uppercase mb-1.5 text-error">차이</span>
<span class="text-text">{topic.divergences.join(' · ')}</span>
</div>
{/if}
{#if topic.convergences.length > 0}
<div class="rounded-lg px-3.5 py-3 text-[13px] leading-relaxed bg-accent/12 border border-accent/25">
<span class="block font-mono text-[10px] font-bold tracking-wide uppercase mb-1.5 text-accent-hover">공통</span>
<span class="text-text">{topic.convergences.join(' · ')}</span>
</div>
{/if}
</div>
{/if}
{#if topic.key_quotes.length > 0}
<div class="mt-3.5 flex flex-col gap-2.5">
{#each topic.key_quotes as q}
<div class="nws-quote relative pl-6">
<div class="nws-serif italic text-[15px] leading-snug text-text">{q.quote}</div>
<div class="text-[11px] text-dim font-mono mt-1 flex items-center gap-1.5 flex-wrap">
{#if q.country}<span class="text-[9.5px] font-extrabold tracking-wide text-white rounded px-1.5 py-0.5 {countryChip(q.country)}">{countryLabel(q.country)}</span>{/if}
<span class="font-bold text-text">{q.source}</span>
</div>
</div>
{/each}
</div>
{/if}
{#if topic.historical_context}
<div class="mt-3.5 px-3 py-2.5 rounded-md bg-bg border border-default text-[12.5px] text-dim leading-relaxed">
<span class="font-mono text-[10px] font-bold tracking-wide uppercase text-faint mr-1.5">지난 흐름</span>{topic.historical_context}
</div> </div>
{/if} {/if}
</div> </div>
<p class="text-sm text-dim"> </article>
{#if briefing} {/snippet}
{briefing.briefing_date} 새벽 수집 · 총 {briefing.total_articles}건 / {briefing.total_countries}개국 / {briefing.total_topics}개 토픽
{:else}
매일 KST 자정~05:00 누적 뉴스를 주제별로 다국 비교 분석합니다.
{/if}
</p>
</header>
{#if loading} <style>
<Card> .nws-serif { font-family: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, "Times New Roman", serif; }
<p class="text-sm text-dim">불러오는 중…</p> .nws-rule::after { content: ""; flex: 1; height: 1px; background: var(--border); }
</Card> .nws-quote::before {
{:else if errorMsg} content: "\201C"; font-family: Georgia, serif; font-size: 36px; line-height: 0;
<Card> color: var(--accent); position: absolute; left: 0; top: 16px;
<p class="text-sm">{errorMsg}</p> }
</Card> </style>
{:else if briefing}
{#if briefing.status === 'empty'}
<Card>
<p class="text-sm">
오늘 새벽({briefing.briefing_date}) 다국 비교 가능한 토픽이 없습니다.
</p>
<p class="mt-2 text-xs text-dim">
(수집 뉴스 0건 또는 2개국 이상 다룬 주제 없음)
</p>
</Card>
{:else}
{#if briefing.status === 'failed'}
<div class="border border-error/40 bg-error/10 text-sm rounded-md px-4 py-3">
⚠ LLM 분석 실패율이 높습니다 ({briefing.llm_failures}/{briefing.llm_calls}, {fallbackPct}%). 일부 토픽이 원문 묶음으로 표시됩니다.
</div>
{:else if briefing.status === 'partial'}
<div class="border border-warning/40 bg-warning/10 text-sm rounded-md px-4 py-3">
일부 토픽 LLM 실패 ({briefing.llm_failures}/{briefing.llm_calls}). 다른 토픽은 정상 분석되었습니다.
</div>
{/if}
{#each briefing.topics as topic (topic.id)}
<div class:opacity-60={topic.is_read}>
<Card class={topic.highlighted ? "ring-2 ring-yellow-400" : ""}>
<div class="space-y-3">
<div class="flex items-start gap-2">
<span class="text-xs text-faint shrink-0 pt-1">#{topic.topic_rank}</span>
<div class="flex-1 min-w-0">
<h2 class="text-base font-semibold leading-snug">
{topic.topic_label}
{#if topic.llm_fallback_used}
<span class="ml-1 text-xs text-dim">(원문 묶음)</span>
{/if}
</h2>
<p class="text-sm text-dim mt-1">{topic.headline}</p>
<p class="text-xs text-faint mt-1">
{topic.country_count}개국 · {topic.article_count}
</p>
</div>
<div class="flex flex-col items-end gap-1 shrink-0">
<button
type="button"
onclick={() => toggleHighlight(topic)}
class="text-base leading-none px-1.5 py-0.5 rounded hover:bg-surface"
class:text-yellow-500={topic.highlighted}
class:text-faint={!topic.highlighted}
title={topic.highlighted ? '하이라이트 해제' : '하이라이트'}
aria-label="하이라이트 토글"
>★</button>
<button
type="button"
onclick={() => toggleRead(topic)}
class="text-xs px-1.5 py-0.5 rounded border border-default hover:bg-surface"
title={topic.is_read ? '읽지 않음으로' : '읽음 처리'}
aria-label="읽음 토글"
>{topic.is_read ? '✓읽음' : '읽음'}</button>
</div>
</div>
{#if topic.country_perspectives.length > 0}
<div class="space-y-1.5">
{#each topic.country_perspectives as cp}
<div class="text-sm leading-relaxed">
<span class="font-medium">{countryLabel(cp.country)}</span>
<span class="text-dim mx-1">·</span>
<span>{cp.summary}</span>
{#if cp.article_ids.length > 0}
<span class="ml-1 text-xs text-faint">
{#each cp.article_ids as id, i}
{#if i > 0}<span class="mx-0.5">·</span>{/if}<a
href={`/documents/${id}`}
class="hover:text-accent"
>#{id}</a>
{/each}
</span>
{/if}
</div>
{/each}
</div>
{/if}
{#if topic.divergences.length > 0}
<div class="text-xs">
<span class="text-dim">차이 </span>
<span class="text-text">{topic.divergences.join(' · ')}</span>
</div>
{/if}
{#if topic.convergences.length > 0}
<div class="text-xs">
<span class="text-dim">공통 </span>
<span class="text-text">{topic.convergences.join(' · ')}</span>
</div>
{/if}
{#if topic.key_quotes.length > 0}
<ul class="text-xs space-y-1 border-l-2 border-default pl-3">
{#each topic.key_quotes as q}
<li>
<span class="text-dim">{countryLabel(q.country)} · {q.source}</span>
<span class="text-text">"{q.quote}"</span>
</li>
{/each}
</ul>
{/if}
{#if topic.historical_context}
<p class="text-xs text-faint italic">
↩ 지난 흐름 · {topic.historical_context}
</p>
{/if}
</div>
</Card>
</div>
{/each}
{/if}
{/if}
</div>
+12 -1
View File
@@ -3,7 +3,7 @@
// 주제로 보기(퀴즈·복습·통계) / 자료 학습 / 필사 세션 / 암기카드 검수. // 주제로 보기(퀴즈·복습·통계) / 자료 학습 / 필사 세션 / 암기카드 검수.
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { api } from '$lib/api'; import { api } from '$lib/api';
import { BookOpen, PenLine, GraduationCap, FolderKanban, Layers, Repeat, Flag } from 'lucide-svelte'; import { BookOpen, PenLine, GraduationCap, FolderKanban, Layers, Repeat, Flag, Inbox } from 'lucide-svelte';
let cardReviewCount = $state(0); let cardReviewCount = $state(0);
let questionFlagCount = $state(0); let questionFlagCount = $state(0);
@@ -86,6 +86,17 @@
<p class="text-xs text-dim">검수한 암기카드를 모바일에서 학습. <b>복습(간격반복 1·3·7·14일)</b>으로 자기평가하거나, <b>그냥 공부</b>로 덜 본 카드를 가볍게 훑어봅니다.</p> <p class="text-xs text-dim">검수한 암기카드를 모바일에서 학습. <b>복습(간격반복 1·3·7·14일)</b>으로 자기평가하거나, <b>그냥 공부</b>로 덜 본 카드를 가볍게 훑어봅니다.</p>
</a> </a>
<a
href="/study/review-box"
class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
>
<div class="flex items-center gap-2 mb-2">
<Inbox size={18} class="text-accent" />
<h2 class="text-base font-semibold text-text">복습함</h2>
</div>
<p class="text-xs text-dim">오늘 복습할 카드와 미확인 카드를 한눈에 보고, <b>골라서</b> 복습합니다.</p>
</a>
<a <a
href="/study/questions-review" href="/study/questions-review"
class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors" class="block p-5 rounded-lg border border-default bg-surface hover:border-accent hover:bg-accent/5 transition-colors"
@@ -17,6 +17,7 @@
import Button from '$lib/components/ui/Button.svelte'; import Button from '$lib/components/ui/Button.svelte';
import Skeleton from '$lib/components/ui/Skeleton.svelte'; import Skeleton from '$lib/components/ui/Skeleton.svelte';
import EmptyState from '$lib/components/ui/EmptyState.svelte'; import EmptyState from '$lib/components/ui/EmptyState.svelte';
import { renderMathMarkdown, renderMathMarkdownInline } from '$lib/utils/mathMarkdown';
let loading = $state(true); let loading = $state(true);
let groups = $state([]); // [{ source_question_id, question_text, correct_choice, cards: [...] }] let groups = $state([]); // [{ source_question_id, question_text, correct_choice, cards: [...] }]
@@ -152,7 +153,7 @@
<EmptyState title="검수할 카드가 없습니다" description="새 문제를 풀면 AI가 암기카드를 추출해 여기에 쌓입니다." icon={CheckCheck} /> <EmptyState title="검수할 카드가 없습니다" description="새 문제를 풀면 AI가 암기카드를 추출해 여기에 쌓입니다." icon={CheckCheck} />
{:else} {:else}
<div class="space-y-5"> <div class="space-y-5">
{#each shownGroups as g (g.source_question_id)} {#each shownGroups as g (g.source_question_id ?? g.question_text)}
<div class="rounded-card border border-default bg-bg/40 p-3"> <div class="rounded-card border border-default bg-bg/40 p-3">
<!-- 출처 문제 --> <!-- 출처 문제 -->
<div class="mb-3 flex items-start gap-2 rounded-lg border border-default bg-surface px-3 py-2"> <div class="mb-3 flex items-start gap-2 rounded-lg border border-default bg-surface px-3 py-2">
@@ -162,7 +163,7 @@
<div class="text-sm text-text">{g.question_text}</div> <div class="text-sm text-text">{g.question_text}</div>
{#if g.correct_choice}<div class="mt-0.5 text-xs text-accent">사용자 정답: {g.correct_choice}</div>{/if} {#if g.correct_choice}<div class="mt-0.5 text-xs text-accent">사용자 정답: {g.correct_choice}</div>{/if}
</div> </div>
{#if g.cards.length > 1} {#if g.cards.length > 1 && g.source_question_id != null}
<Button variant="secondary" size="sm" icon={CheckCheck} onclick={() => approveGroup(g.source_question_id, g.cards.length)}>{g.cards.length}장 승인</Button> <Button variant="secondary" size="sm" icon={CheckCheck} onclick={() => approveGroup(g.source_question_id, g.cards.length)}>{g.cards.length}장 승인</Button>
{/if} {/if}
</div> </div>
@@ -200,18 +201,22 @@
{:else} {:else}
<!-- 보기 모드 --> <!-- 보기 모드 -->
<div class="rounded-md border border-default bg-surface-active px-3 py-2 text-sm"> <div class="rounded-md border border-default bg-surface-active px-3 py-2 text-sm">
<div class="text-[10px] font-bold uppercase tracking-wide text-faint"></div>{c.cue} <div class="text-[10px] font-bold uppercase tracking-wide text-faint"></div>
<div class="math-area break-words">{@html renderMathMarkdownInline(c.cue)}</div>
</div> </div>
<div class="mt-1.5 rounded-md border border-accent-ring bg-bg px-3 py-2 text-sm"> <div class="mt-1.5 rounded-md border border-accent-ring bg-bg px-3 py-2 text-sm">
{#if c.format === 'cloze' && c.cloze_text} {#if c.format === 'cloze' && c.cloze_text}
{c.cloze_text} <span class="math-area break-words">{@html renderMathMarkdownInline(c.cloze_text)}</span>
<div class="mt-1 text-xs text-accent">정답: <b>{c.fact}</b></div> <div class="mt-1 text-xs text-accent">정답: <b class="math-area break-words">{@html renderMathMarkdownInline(c.fact)}</b></div>
{:else} {:else}
<b class="text-accent">{c.fact}</b> <b class="math-area break-words text-accent">{@html renderMathMarkdownInline(c.fact)}</b>
{/if} {/if}
</div> </div>
{#if c.evidence?.length} {#if c.evidence?.length}
<div class="mt-2 text-[11px] text-dim">근거: {c.evidence[0].snippet}</div> <div class="mt-2">
<span class="text-[10px] font-bold uppercase tracking-wide text-faint">근거</span>
<div class="markdown-body math-area mt-1 overflow-x-auto text-[11px] leading-relaxed text-dim">{@html renderMathMarkdown(c.evidence[0].snippet)}</div>
</div>
{:else if c.source_kind === 'manual'} {:else if c.source_kind === 'manual'}
<div class="mt-2 text-[11px] text-faint">출처: 직접 추가 자료</div> <div class="mt-2 text-[11px] text-faint">출처: 직접 추가 자료</div>
{:else} {:else}
@@ -21,6 +21,8 @@
import Skeleton from '$lib/components/ui/Skeleton.svelte'; import Skeleton from '$lib/components/ui/Skeleton.svelte';
import EmptyState from '$lib/components/ui/EmptyState.svelte'; import EmptyState from '$lib/components/ui/EmptyState.svelte';
import { renderMathMarkdown, renderMathMarkdownInline } from '$lib/utils/mathMarkdown'; import { renderMathMarkdown, renderMathMarkdownInline } from '$lib/utils/mathMarkdown';
import { get } from 'svelte/store';
import { pendingReviewCards } from '$lib/stores/studySession';
// sr_schedule.py 단일 source 미러 — '암'(correct) 다음 복습일 라벨 전용(실제 스케줄은 백엔드). // sr_schedule.py 단일 source 미러 — '암'(correct) 다음 복습일 라벨 전용(실제 스케줄은 백엔드).
// stage===null = 신규 카드(progress 없음): '암'이면 백엔드가 due 안 박음(외움→큐 제외)이라 '안 나옴'. // stage===null = 신규 카드(progress 없음): '암'이면 백엔드가 due 안 박음(외움→큐 제외)이라 '안 나옴'.
@@ -29,7 +31,7 @@
if (stage === null || stage === undefined) return '안 나옴'; if (stage === null || stage === undefined) return '안 나옴';
const ns = stage + 1; const ns = stage + 1;
if (ns >= 4) return '졸업'; if (ns >= 4) return '졸업';
return `+${REVIEW_INTERVAL_DAYS[ns]}일`; return `${REVIEW_INTERVAL_DAYS[ns]}`;
} }
let mode = $state('landing'); // 'landing' | 'review' | 'cram' let mode = $state('landing'); // 'landing' | 'review' | 'cram'
@@ -82,6 +84,14 @@
revealed = false; revealed = false;
tally = { correct: 0, unsure: 0, wrong: 0 }; tally = { correct: 0, unsure: 0, wrong: 0 };
marks = []; marks = [];
// 복습함(/study/review-box)에서 선택해 넘긴 카드가 있으면 그걸로 세션 구성.
const preset = get(pendingReviewCards);
if (preset && preset.length) {
pendingReviewCards.set(null); // 소비
cards = preset;
loading = false;
return;
}
try { try {
cards = _dueCache ?? (await fetchDue()); cards = _dueCache ?? (await fetchDue());
_dueCache = null; // 소비 _dueCache = null; // 소비
@@ -279,10 +289,10 @@
> >
<div class="mb-1.5 flex items-center gap-2"> <div class="mb-1.5 flex items-center gap-2">
<Layers size={18} class="text-accent" /> <Layers size={18} class="text-accent" />
<h2 class="text-base font-semibold text-text">그냥 공부 (휙휙)</h2> <h2 class="text-base font-semibold text-text">그냥 공부</h2>
</div> </div>
<p class="text-xs text-dim"> <p class="text-xs text-dim">
덜 본 카드부터 빠르게 넘겨보며 <b class="text-text"></b>만 기록합니다. 간격반복(SR)과 무관 — 가볍게 훑을 때. 아직 덜 본 카드부터 가볍게 넘겨보며 <b class="text-text">어요</b>만 기록해요. 복습 일정과는 무관해요.
</p> </p>
</button> </button>
</div> </div>
@@ -294,21 +304,21 @@
<!-- 결과 화면 --> <!-- 결과 화면 -->
<div class="flex flex-1 flex-col items-center justify-center text-center"> <div class="flex flex-1 flex-col items-center justify-center text-center">
{#if mode === 'review'} {#if mode === 'review'}
<div class="text-lg font-bold text-text">오늘 카드 복습 완료</div> <div class="text-lg font-bold text-text">오늘 복습을 마쳤어요</div>
<div class="my-6 flex gap-9"> <div class="my-6 flex gap-9">
<div><div class="text-3xl font-extrabold text-success">{tally.correct}</div><div class="text-xs text-dim"></div></div> <div><div class="text-3xl font-extrabold text-success">{tally.correct}</div><div class="text-xs text-dim"></div></div>
<div><div class="text-3xl font-extrabold text-warning">{tally.unsure}</div><div class="text-xs text-dim">애매</div></div> <div><div class="text-3xl font-extrabold text-warning">{tally.unsure}</div><div class="text-xs text-dim">애매</div></div>
<div><div class="text-3xl font-extrabold text-error">{tally.wrong}</div><div class="text-xs text-dim">모름</div></div> <div><div class="text-3xl font-extrabold text-error">{tally.wrong}</div><div class="text-xs text-dim">모름</div></div>
</div> </div>
<p class="text-xs text-dim">애매·모름 카드는 내일 복습 큐에 다시 올라옵니다. 암 카드는 간격만큼 쉬어요.</p> <p class="text-xs text-dim">애매하거나 몰랐던 카드는 내일 다시 만나요. 외운 카드는 간격만큼 쉬어요.</p>
{:else} {:else}
<div class="text-lg font-bold text-text">훑어보기 완료</div> <div class="text-lg font-bold text-text">훑어보기 완료</div>
<div class="my-6 text-3xl font-extrabold text-accent">{seen}<span class="ml-1 text-sm font-medium text-dim"></span></div> <div class="my-6 text-3xl font-extrabold text-accent">{seen}<span class="ml-1 text-sm font-medium text-dim"></span></div>
<p class="text-xs text-dim">'봤'로 기록한 카드는 다음 덜 본 순서에서 뒤로 갑니다.</p> <p class="text-xs text-dim">'봤어요'로 표시한 카드는 다음 덜 본 순서 뒤로 가요.</p>
{/if} {/if}
<div class="mt-7 flex gap-2"> <div class="mt-7 flex gap-2">
<Button variant="secondary" onclick={backToLanding}>다시 고르기</Button> <Button variant="secondary" onclick={backToLanding}>다시 고르기</Button>
<Button variant="primary" onclick={() => goto('/study')}>공부 허브로</Button> <Button variant="primary" onclick={() => goto('/study')}>공부 돌아가기</Button>
</div> </div>
</div> </div>
@@ -359,7 +369,7 @@
type="button" type="button"
onclick={flagCard} onclick={flagCard}
disabled={flagBusy || busy} disabled={flagBusy || busy}
class="flex items-center gap-1 text-[11px] text-faint transition-colors hover:text-warning disabled:opacity-50" class="flex items-center gap-1 rounded-full border border-default px-2.5 py-1 text-[11px] font-medium text-dim transition-colors hover:border-warning hover:bg-warning/10 hover:text-warning disabled:opacity-50"
title="카드 내용이 이상하면 검수함으로 보냅니다" title="카드 내용이 이상하면 검수함으로 보냅니다"
> >
<Flag size={12} /> 이 카드 이상해요 <Flag size={12} /> 이 카드 이상해요
@@ -367,7 +377,7 @@
</div> </div>
<div class="mt-3 text-[10px] font-bold uppercase tracking-wide text-faint"> <div class="mt-3 text-[10px] font-bold uppercase tracking-wide text-faint">
앞 — {current.format === 'qa' ? '질문' : '회상'} 앞 — {current.format === 'qa' ? '질문' : '떠올리기'}
</div> </div>
<div class="math-area mt-1 break-words text-lg font-semibold leading-relaxed text-text md:mt-2 md:text-2xl">{@html renderMathMarkdownInline(frontText(current))}</div> <div class="math-area mt-1 break-words text-lg font-semibold leading-relaxed text-text md:mt-2 md:text-2xl">{@html renderMathMarkdownInline(frontText(current))}</div>
@@ -389,7 +399,7 @@
onclick={() => (revealed = true)} onclick={() => (revealed = true)}
class="mt-auto flex items-center justify-center gap-2 rounded-md border border-dashed border-accent-ring bg-surface-hover py-3 text-sm font-medium text-accent transition-colors hover:bg-accent/5" class="mt-auto flex items-center justify-center gap-2 rounded-md border border-dashed border-accent-ring bg-surface-hover py-3 text-sm font-medium text-accent transition-colors hover:bg-accent/5"
> >
<Eye size={16} /> 탭하 정답 보 <span class="text-faint">(Space)</span> <Eye size={16} /> 탭하 정답여요 <span class="hidden text-faint sm:inline">· Space</span>
</button> </button>
{/if} {/if}
</div> </div>
@@ -402,12 +412,12 @@
onclick={() => rate('모름')} onclick={() => rate('모름')}
disabled={busy} disabled={busy}
class="flex flex-col items-center rounded-lg bg-error py-3.5 text-sm font-bold text-white transition-opacity hover:opacity-90 disabled:opacity-50" class="flex flex-col items-center rounded-lg bg-error py-3.5 text-sm font-bold text-white transition-opacity hover:opacity-90 disabled:opacity-50"
>모름<span class="mt-0.5 text-[10px] font-medium opacity-85">내일</span></button> >모름<span class="mt-0.5 text-[10px] font-medium opacity-85">내일 다시</span></button>
<button <button
onclick={() => rate('애매')} onclick={() => rate('애매')}
disabled={busy} disabled={busy}
class="flex flex-col items-center rounded-lg bg-warning py-3.5 text-sm font-bold text-white transition-opacity hover:opacity-90 disabled:opacity-50" class="flex flex-col items-center rounded-lg bg-warning py-3.5 text-sm font-bold text-white transition-opacity hover:opacity-90 disabled:opacity-50"
>애매<span class="mt-0.5 text-[10px] font-medium opacity-85">내일</span></button> >애매<span class="mt-0.5 text-[10px] font-medium opacity-85">내일 다시</span></button>
<button <button
onclick={() => rate('암')} onclick={() => rate('암')}
disabled={busy} disabled={busy}
@@ -420,7 +430,7 @@
onclick={markSeen} onclick={markSeen}
disabled={busy} disabled={busy}
class="mt-3 w-full rounded-lg bg-accent py-3.5 text-sm font-bold text-white transition-colors hover:bg-accent-hover disabled:opacity-50" class="mt-3 w-full rounded-lg bg-accent py-3.5 text-sm font-bold text-white transition-colors hover:bg-accent-hover disabled:opacity-50"
>봤다 — 다음 <span class="text-xs font-medium opacity-85">(Enter)</span></button> >봤어요 · 다음 <span class="hidden text-xs font-medium opacity-85 sm:inline">Enter</span></button>
{/if} {/if}
{/if} {/if}
</div> </div>
@@ -0,0 +1,144 @@
<script>
/**
* /study/review-box — 복습함 (카드 SR 복습 현황 + 선택 학습, B4).
*
* GET /study-cards/due (review_stage 포함) 로 오늘의 복습 큐를 받아 2탭으로 분리:
* - 오늘 할 일: review_stage != null (예전에 평가돼 복습일이 도래한 카드)
* - 미확인 : review_stage == null (검수 통과했지만 아직 한 번도 회상 안 한 새 카드)
* - 완료 : 졸업 카드 — 백엔드 엔드포인트 필요(현재 미배포 = eid contention 중 fastapi 무재빌드)라 추후.
*
* 멀티셀렉트 → 선택 카드를 pendingReviewCards store 로 cards-study 복습 세션에 전달(백엔드 세션 X).
*/
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { api } from '$lib/api';
import { addToast } from '$lib/stores/toast';
import { pendingReviewCards } from '$lib/stores/studySession';
import { ArrowLeft, Repeat, GraduationCap, CheckCheck, Play } from 'lucide-svelte';
import Button from '$lib/components/ui/Button.svelte';
import Skeleton from '$lib/components/ui/Skeleton.svelte';
import EmptyState from '$lib/components/ui/EmptyState.svelte';
let loading = $state(true);
let cards = $state([]); // /due 결과 (CardItem[], review_stage 포함)
let tab = $state('today'); // 'today' | 'new' | 'done'
let selected = $state({}); // card.id -> true
let newCards = $derived(cards.filter((c) => c.review_stage === null || c.review_stage === undefined));
let dueCards = $derived(cards.filter((c) => c.review_stage !== null && c.review_stage !== undefined));
let shown = $derived(tab === 'today' ? dueCards : tab === 'new' ? newCards : []);
let selectedCount = $derived(shown.filter((c) => selected[c.id]).length);
let allShownSelected = $derived(shown.length > 0 && shown.every((c) => selected[c.id]));
async function load() {
loading = true;
try {
cards = (await api('/study-cards/due?limit=200')) ?? [];
} catch (err) {
addToast('error', err?.detail || '복습 카드 조회 실패');
cards = [];
} finally {
loading = false;
}
}
function frontText(c) {
const t = (c.format === 'cloze' && c.cloze_text ? c.cloze_text : c.cue) ?? '';
return t.length > 60 ? t.slice(0, 60) + '…' : t;
}
function toggle(id) {
selected = { ...selected, [id]: !selected[id] };
}
function selectAllShown() {
const next = { ...selected };
shown.forEach((c) => { next[c.id] = !allShownSelected; });
selected = next;
}
function startCards(list) {
if (!list.length) return;
pendingReviewCards.set(list);
goto('/study/cards-study?mode=review');
}
function startSelected() {
startCards(shown.filter((c) => selected[c.id]));
}
function startTab() {
startCards(shown);
}
function setTab(t) {
if (t === 'done' || t === tab) return; // 완료 탭은 백엔드 준비 전 비활성
selected = {}; // 탭 전환 시 선택 초기화 — 탭별 독립 선택(선택 복습은 현재 탭 기준)
tab = t;
}
onMount(load);
</script>
<svelte:head><title>복습함</title></svelte:head>
<div class="mx-auto max-w-3xl px-4 py-6">
<div class="mb-4 flex items-center gap-3">
<Button variant="ghost" size="sm" icon={ArrowLeft} onclick={() => goto('/study')}>공부</Button>
<h1 class="text-xl font-bold text-text">복습함</h1>
</div>
<p class="mb-4 text-sm text-dim">
검수 통과한 암기카드의 복습 현황입니다. 탭에서 카드를 골라 <b class="text-text">선택 복습</b>하거나, 탭 전체를 한 번에 복습할 수 있어요.
</p>
<!---->
<div class="mb-4 flex gap-1.5">
{#each [['today', '오늘 할 일', dueCards.length], ['new', '미확인', newCards.length], ['done', '완료', null]] as [val, label, n] (val)}
<button
onclick={() => setTab(val)}
disabled={val === 'done'}
class="flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-semibold transition-colors
{tab === val ? 'border-accent bg-accent text-white' : 'border-default bg-surface text-dim hover:text-text'}
{val === 'done' ? 'cursor-not-allowed opacity-50' : ''}"
>
{label}
{#if n !== null}<span class="rounded-full px-1.5 text-[10px] {tab === val ? 'bg-white/25' : 'bg-default'}">{n}</span>{/if}
{#if val === 'done'}<span class="text-[10px]">추후</span>{/if}
</button>
{/each}
</div>
{#if loading}
<div class="space-y-2">{#each Array(5).fill(0) as _, i (i)}<Skeleton class="h-12 w-full" />{/each}</div>
{:else if tab === 'done'}
<EmptyState title="완료 탭은 준비 중" description="졸업(완료)한 카드 목록은 백엔드 엔드포인트가 준비되면 추가됩니다." icon={GraduationCap} />
{:else if shown.length === 0}
<EmptyState
title={tab === 'today' ? '오늘 복습할 카드가 없습니다' : '미확인 카드가 없습니다'}
description={tab === 'today' ? '애매·모름으로 평가한 카드의 복습일이 되면 여기에 나타납니다.' : '검수 통과한 새 카드가 여기에 모입니다. 지금은 모두 한 번씩 본 상태예요.'}
icon={Repeat}
/>
{:else}
<!-- 선택 바 -->
<div class="mb-3 flex flex-wrap items-center gap-2">
<button onclick={selectAllShown} class="rounded-md border border-default px-2.5 py-1 text-xs font-medium text-dim transition-colors hover:text-text">
{allShownSelected ? '선택 해제' : '전체 선택'}
</button>
<span class="text-xs text-dim">{selectedCount > 0 ? `${selectedCount} 선택됨` : `${shown.length}`}</span>
<div class="ml-auto flex gap-2">
{#if selectedCount > 0}
<Button variant="secondary" size="sm" icon={Play} onclick={startSelected}>선택 {selectedCount}장 복습</Button>
{/if}
<Button variant="primary" size="sm" icon={CheckCheck} onclick={startTab}>이 탭 전체 복습</Button>
</div>
</div>
<!-- 카드 목록 -->
<div class="space-y-1.5">
{#each shown as c (c.id)}
<label class="flex cursor-pointer items-center gap-3 rounded-lg border border-default bg-surface px-3 py-2.5 transition-colors hover:border-accent">
<input type="checkbox" checked={!!selected[c.id]} onchange={() => toggle(c.id)} class="size-4 shrink-0 accent-accent" />
<span class="shrink-0 rounded-full px-2 py-0.5 text-[10px] font-bold text-white {c.format === 'cloze' ? 'bg-accent' : 'bg-domain-engineering'}">{c.format}</span>
<span class="min-w-0 flex-1 truncate text-sm text-text">{frontText(c)}</span>
</label>
{/each}
</div>
{/if}
</div>