Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 20564ba34b | |||
| a53ef4cc6f | |||
| 282d51daf6 | |||
| f718342b93 |
13
HANDOFF.md
13
HANDOFF.md
@@ -4,7 +4,7 @@
|
||||
|
||||
- 프로젝트명: 10 Minute Planner 웹 UI
|
||||
- 기술 스택: Vue 3 + Vite + TailwindCSS + JavaScript
|
||||
- 현재 기준 버전: `v0.1.10`
|
||||
- 현재 기준 버전: `v0.1.14`
|
||||
- Git 원격 저장소: `https://git.sori.studio/zenn/planner.sori.studio.git`
|
||||
|
||||
## 기준 디자인
|
||||
@@ -26,6 +26,8 @@
|
||||
- 메인 화면 셸: `src/App.vue`
|
||||
- 플래너 종이 레이아웃: `src/components/PlannerPage.vue`
|
||||
- 우측 달력 컴포넌트: `src/components/MiniCalendar.vue`
|
||||
- 프론트 인증 모달: `src/components/AuthDialog.vue`
|
||||
- 프론트 인증 클라이언트: `src/lib/authClient.js`
|
||||
- 백엔드 엔트리 포인트: `backend/src/server.js`
|
||||
- 백엔드 DB 스키마: `backend/src/db/schema.js`
|
||||
- 백엔드 인증 라우트: `backend/src/routes/auth.js`
|
||||
@@ -47,6 +49,9 @@
|
||||
- 상단 날짜 표시에서는 토요일의 `(토)`만 파란색, 일요일의 `(일)`만 빨간색으로 표시한다.
|
||||
- 플래너 상태는 `localStorage`에 저장되며, 날짜별 기록과 선택 날짜, 달력 보고 있던 월까지 복원된다.
|
||||
- `localStorage` 접근 로직은 `src/lib/plannerStorage.js`로 분리하기 시작했고, 이후 API/DB adapter로 교체하기 쉬운 구조로 정리 중이다.
|
||||
- 프론트는 헤더에서 `LOGIN` / `SIGN UP` 모달을 열 수 있고, 로그인 상태면 닉네임과 `LOGOUT` 버튼을 표시한다.
|
||||
- 인증 토큰과 현재 사용자 정보는 프론트 로컬 저장소에 따로 유지하고, 앱 시작 시 `/api/auth/me`로 세션 복원을 시도한다.
|
||||
- 프론트 플래너 API 클라이언트는 `src/lib/plannerApi.js`에 추가되었다.
|
||||
- 루트에서 `npm run dev:backend`, `npm run db:generate`, `npm run db:migrate`로 백엔드 명령을 호출할 수 있다.
|
||||
- 상단 전환 버튼으로 `PLANNER / STATS` 화면을 오갈 수 있다.
|
||||
- 통계 화면에서는 전체 집중 시간, 평균 완료율, 기록 일수, 최근 7일 흐름, 최근 기록, 베스트 데이를 보여준다.
|
||||
@@ -111,6 +116,12 @@
|
||||
- 현재는 SQLite로 시작하되, 확장 시 PostgreSQL로 옮길 수 있게 Drizzle 기반 스키마를 유지한다.
|
||||
- 현재 인증 방식은 Bearer 토큰 기반의 간단한 세션 구조이며, 추후 쿠키/리프레시 토큰 전략으로 확장할 수 있다.
|
||||
- 다음 프론트 단계에서는 `src/lib/plannerStorage.js`를 유지하되, 인증 이후 백엔드 저장소 adapter를 추가해서 `localStorage`와 전환 가능하게 만드는 흐름이 좋다.
|
||||
- 현재 프론트는 인증만 연결된 상태이고, 플래너 저장은 아직 `localStorage` 기준이다.
|
||||
- 로그인 상태에서는 플래너 수정 시 날짜별 서버 저장을 예약하고, 로그인 직후에는 서버 데이터를 먼저 가져오도록 연결하기 시작했다.
|
||||
- 현재는 로컬 저장도 계속 유지하면서 서버 저장을 병행하는 과도기 구조다.
|
||||
- 로그인 시 서버 플래너 데이터로 `plannerRecords`를 교체하고, 로그아웃 시에는 로컬 저장 기반 데이터로 다시 복귀하도록 정리했다.
|
||||
- 이로 인해 다른 사용자 로그인 시 이전 로컬 데이터가 서버 계정 데이터와 섞일 위험을 줄였다.
|
||||
- 로그인 상태에서 특정 날짜의 플래너 내용을 완전히 비우면, 서버 저장 대신 해당 날짜 엔트리를 삭제하도록 정리했다.
|
||||
- 이미지 저장 기능은 추후 `print-only` 또는 별도 export 전용 레이아웃을 기준으로 구현하면 화면/인쇄/공유 결과를 맞추기 쉽다.
|
||||
- Docker Compose는 프론트엔드와 백엔드를 함께 올리는 기준으로 설계하되, NAS 환경에 맞는 볼륨과 재시작 정책도 함께 고려한다.
|
||||
|
||||
|
||||
2
TODO.md
2
TODO.md
@@ -94,4 +94,6 @@
|
||||
- 현재 백엔드는 `backend/` 폴더에 `Fastify + Drizzle + SQLite` 기준 초안이 추가되었다.
|
||||
- 현재 백엔드는 회원가입, 로그인, 현재 사용자 확인용 기본 인증 API까지 포함한다.
|
||||
- 현재 백엔드는 사용자별 플래너 단건 저장/조회와 범위 조회 API까지 포함한다.
|
||||
- 프론트에는 로그인/회원가입 모달과 현재 사용자 상태 표시가 추가되었다.
|
||||
- 로그인 상태일 때는 서버 저장을 우선 사용하는 흐름으로 전환 중이다.
|
||||
- 구현할 때마다 완료된 항목은 체크하고, 큰 결정사항은 `HANDOFF.md`에도 함께 반영한다.
|
||||
|
||||
@@ -162,4 +162,35 @@ export async function registerPlannerRoutes(app) {
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/api/planner/:entryDate', async (request, reply) => {
|
||||
const user = await requireAuthenticatedUser(request, reply)
|
||||
|
||||
if (!user) {
|
||||
return
|
||||
}
|
||||
|
||||
const dateResult = dateSchema.safeParse(request.params.entryDate)
|
||||
|
||||
if (!dateResult.success) {
|
||||
return reply.code(400).send({
|
||||
message: '날짜 형식이 올바르지 않습니다.',
|
||||
})
|
||||
}
|
||||
|
||||
const deletedEntries = await db
|
||||
.delete(plannerEntries)
|
||||
.where(
|
||||
and(
|
||||
eq(plannerEntries.userId, user.id),
|
||||
eq(plannerEntries.entryDate, dateResult.data),
|
||||
),
|
||||
)
|
||||
.returning()
|
||||
|
||||
return {
|
||||
message: deletedEntries.length > 0 ? '플래너가 삭제되었습니다.' : '삭제할 플래너가 없습니다.',
|
||||
deleted: deletedEntries.length > 0,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ten-minute-planner",
|
||||
"version": "0.1.10",
|
||||
"version": "0.1.14",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ten-minute-planner",
|
||||
"version": "0.1.10",
|
||||
"version": "0.1.14",
|
||||
"dependencies": {
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ten-minute-planner",
|
||||
"private": true,
|
||||
"version": "0.1.10",
|
||||
"version": "0.1.14",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
331
src/App.vue
331
src/App.vue
@@ -1,21 +1,45 @@
|
||||
<script setup>
|
||||
import { computed, reactive, ref, watch, nextTick } from 'vue'
|
||||
import { computed, onMounted, reactive, ref, watch, nextTick } from 'vue'
|
||||
import AuthDialog from './components/AuthDialog.vue'
|
||||
import MiniCalendar from './components/MiniCalendar.vue'
|
||||
import PlannerPage from './components/PlannerPage.vue'
|
||||
import StatsDashboard from './components/StatsDashboard.vue'
|
||||
import {
|
||||
clearAuthState,
|
||||
fetchCurrentUser,
|
||||
login,
|
||||
persistAuthState,
|
||||
readAuthState,
|
||||
signup,
|
||||
} from './lib/authClient'
|
||||
import { deletePlannerEntry, fetchPlannerEntries, savePlannerEntry } from './lib/plannerApi'
|
||||
import {
|
||||
createInitialPlannerRecords,
|
||||
persistPlannerState,
|
||||
readPlannerStorageState,
|
||||
restorePlannerUiState,
|
||||
} from './lib/plannerStorage'
|
||||
|
||||
const screenMode = ref('planner')
|
||||
const viewMode = ref('focus')
|
||||
const printLayout = ref('single')
|
||||
const authDialogOpen = ref(false)
|
||||
const authMode = ref('login')
|
||||
const authBusy = ref(false)
|
||||
const authMessage = ref('')
|
||||
const authToken = ref('')
|
||||
const currentUser = ref(null)
|
||||
const syncStatus = ref('local')
|
||||
const syncMessage = ref('')
|
||||
const selectedDate = ref(new Date())
|
||||
const calendarViewDate = ref(new Date(selectedDate.value))
|
||||
const statsRangeStart = ref(toKey(new Date(new Date().setDate(new Date().getDate() - 6))))
|
||||
const statsRangeEnd = ref(toKey(new Date()))
|
||||
const authForm = reactive({
|
||||
nickname: '',
|
||||
email: '',
|
||||
password: '',
|
||||
})
|
||||
|
||||
const hours = [
|
||||
'6', '7', '8', '9', '10', '11', '12',
|
||||
@@ -26,6 +50,8 @@ const hours = [
|
||||
|
||||
const timetableCellCount = hours.length * 6
|
||||
let printPageStyleElement = null
|
||||
let isHydratingRemoteRecords = false
|
||||
const syncTimers = new Map()
|
||||
|
||||
function createEmptyTimetable() {
|
||||
return Array.from({ length: timetableCellCount }, () => false)
|
||||
@@ -271,6 +297,8 @@ const markedDateKeys = computed(() =>
|
||||
.map(([key]) => key),
|
||||
)
|
||||
|
||||
const isAuthenticated = computed(() => Boolean(authToken.value && currentUser.value))
|
||||
|
||||
const filledTasks = computed(() =>
|
||||
planner.value.tasks.filter((task) => task.title.trim()),
|
||||
)
|
||||
@@ -335,30 +363,37 @@ function selectDate(date) {
|
||||
|
||||
function updateComment(record, value) {
|
||||
record.comment = value
|
||||
schedulePlannerSyncForRecord(record)
|
||||
}
|
||||
|
||||
function updateTaskLabel(record, { index, value }) {
|
||||
record.tasks[index].label = value
|
||||
schedulePlannerSyncForRecord(record)
|
||||
}
|
||||
|
||||
function updateTaskTitle(record, { index, value }) {
|
||||
record.tasks[index].title = value
|
||||
schedulePlannerSyncForRecord(record)
|
||||
}
|
||||
|
||||
function toggleTask(record, index) {
|
||||
record.tasks[index].checked = !record.tasks[index].checked
|
||||
schedulePlannerSyncForRecord(record)
|
||||
}
|
||||
|
||||
function updateMemo(record, { index, value }) {
|
||||
record.memo[index].text = value
|
||||
schedulePlannerSyncForRecord(record)
|
||||
}
|
||||
|
||||
function updateMemoLabel(record, { index, value }) {
|
||||
record.memo[index].label = value
|
||||
schedulePlannerSyncForRecord(record)
|
||||
}
|
||||
|
||||
function updateTimetable(record, nextTimetable) {
|
||||
record.timetable = nextTimetable
|
||||
schedulePlannerSyncForRecord(record)
|
||||
}
|
||||
|
||||
function hasPlannerContent(record) {
|
||||
@@ -523,6 +558,7 @@ watch(
|
||||
calendarViewDate: calendarViewDate.value,
|
||||
statsRangeStart: normalizedStatsRange.value.startKey,
|
||||
statsRangeEnd: normalizedStatsRange.value.endKey,
|
||||
includeRecords: !isAuthenticated.value,
|
||||
})
|
||||
},
|
||||
{ deep: true },
|
||||
@@ -538,6 +574,236 @@ function clearTaskLabels(record) {
|
||||
record.tasks.forEach((task) => {
|
||||
task.label = ''
|
||||
})
|
||||
schedulePlannerSyncForRecord(record)
|
||||
}
|
||||
|
||||
function resetAuthForm() {
|
||||
authForm.nickname = ''
|
||||
authForm.email = ''
|
||||
authForm.password = ''
|
||||
}
|
||||
|
||||
function openAuthDialog(mode = 'login') {
|
||||
authMode.value = mode
|
||||
authMessage.value = ''
|
||||
authDialogOpen.value = true
|
||||
}
|
||||
|
||||
function closeAuthDialog() {
|
||||
authDialogOpen.value = false
|
||||
authMessage.value = ''
|
||||
resetAuthForm()
|
||||
}
|
||||
|
||||
function updateAuthField({ field, value }) {
|
||||
authForm[field] = value
|
||||
}
|
||||
|
||||
async function applyAuthSuccess(data) {
|
||||
authToken.value = data.token
|
||||
currentUser.value = data.user
|
||||
syncStatus.value = 'cloud'
|
||||
syncMessage.value = '클라우드 동기화 연결됨'
|
||||
persistAuthState({
|
||||
token: data.token,
|
||||
user: data.user,
|
||||
})
|
||||
await hydratePlannerRecordsFromApi()
|
||||
closeAuthDialog()
|
||||
}
|
||||
|
||||
async function submitAuthForm() {
|
||||
authBusy.value = true
|
||||
authMessage.value = ''
|
||||
|
||||
try {
|
||||
const result =
|
||||
authMode.value === 'login'
|
||||
? await login({
|
||||
email: authForm.email,
|
||||
password: authForm.password,
|
||||
})
|
||||
: await signup({
|
||||
nickname: authForm.nickname,
|
||||
email: authForm.email,
|
||||
password: authForm.password,
|
||||
})
|
||||
|
||||
await applyAuthSuccess(result)
|
||||
} catch (error) {
|
||||
authMessage.value = error.message || '인증 처리 중 문제가 발생했습니다.'
|
||||
} finally {
|
||||
authBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreAuthSession() {
|
||||
const savedAuth = readAuthState()
|
||||
|
||||
if (!savedAuth.token) {
|
||||
return
|
||||
}
|
||||
|
||||
authToken.value = savedAuth.token
|
||||
currentUser.value = savedAuth.user ?? null
|
||||
|
||||
try {
|
||||
const result = await fetchCurrentUser(savedAuth.token)
|
||||
currentUser.value = result.user
|
||||
syncStatus.value = 'cloud'
|
||||
syncMessage.value = '클라우드 동기화 연결됨'
|
||||
persistAuthState({
|
||||
token: savedAuth.token,
|
||||
user: result.user,
|
||||
})
|
||||
await hydratePlannerRecordsFromApi()
|
||||
} catch (error) {
|
||||
authToken.value = ''
|
||||
currentUser.value = null
|
||||
syncStatus.value = 'local'
|
||||
syncMessage.value = '로컬 저장 모드'
|
||||
clearAuthState()
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
clearPendingSyncTimers()
|
||||
authToken.value = ''
|
||||
currentUser.value = null
|
||||
syncStatus.value = 'local'
|
||||
syncMessage.value = '로컬 저장 모드'
|
||||
clearAuthState()
|
||||
restoreLocalPlannerRecords()
|
||||
}
|
||||
|
||||
function replacePlannerRecords(nextRecords) {
|
||||
Object.keys(plannerRecords).forEach((key) => {
|
||||
delete plannerRecords[key]
|
||||
})
|
||||
|
||||
Object.entries(nextRecords).forEach(([key, record]) => {
|
||||
plannerRecords[key] = record
|
||||
})
|
||||
}
|
||||
|
||||
function restoreLocalPlannerRecords() {
|
||||
replacePlannerRecords(createInitialPlannerRecords(plannerSeed, normalizeRecord))
|
||||
|
||||
const savedState = readPlannerStorageState()
|
||||
|
||||
if (savedState.selectedDate) {
|
||||
selectedDate.value = toDateValue(savedState.selectedDate, selectedDate.value)
|
||||
}
|
||||
|
||||
if (savedState.calendarViewDate) {
|
||||
calendarViewDate.value = toDateValue(savedState.calendarViewDate, selectedDate.value)
|
||||
}
|
||||
}
|
||||
|
||||
function findRecordKey(record) {
|
||||
return Object.entries(plannerRecords).find(([, value]) => value === record)?.[0] ?? null
|
||||
}
|
||||
|
||||
function clearPendingSyncTimers() {
|
||||
syncTimers.forEach((timerId) => {
|
||||
window.clearTimeout(timerId)
|
||||
})
|
||||
syncTimers.clear()
|
||||
}
|
||||
|
||||
function schedulePlannerSyncForRecord(record) {
|
||||
const recordKey = findRecordKey(record)
|
||||
|
||||
if (!recordKey) {
|
||||
return
|
||||
}
|
||||
|
||||
schedulePlannerSync(recordKey)
|
||||
}
|
||||
|
||||
function schedulePlannerSync(recordKey) {
|
||||
if (!isAuthenticated.value || isHydratingRemoteRecords) {
|
||||
return
|
||||
}
|
||||
|
||||
if (syncTimers.has(recordKey)) {
|
||||
window.clearTimeout(syncTimers.get(recordKey))
|
||||
}
|
||||
|
||||
syncStatus.value = 'syncing'
|
||||
syncMessage.value = '클라우드 저장 중...'
|
||||
|
||||
const timerId = window.setTimeout(async () => {
|
||||
syncTimers.delete(recordKey)
|
||||
|
||||
try {
|
||||
const record = plannerRecords[recordKey]
|
||||
|
||||
if (!record) {
|
||||
if (syncTimers.size === 0) {
|
||||
syncStatus.value = 'cloud'
|
||||
syncMessage.value = '클라우드 동기화 연결됨'
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!hasPlannerContent(record)) {
|
||||
await deletePlannerEntry(authToken.value, recordKey)
|
||||
|
||||
if (syncTimers.size === 0) {
|
||||
syncStatus.value = 'cloud'
|
||||
syncMessage.value = '클라우드에서 삭제됨'
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
await savePlannerEntry(authToken.value, recordKey, {
|
||||
...record,
|
||||
tasks: record.tasks.map((task) => ({ ...task })),
|
||||
memo: record.memo.map((item) => ({ ...item })),
|
||||
timetable: [...record.timetable],
|
||||
})
|
||||
|
||||
if (syncTimers.size === 0) {
|
||||
syncStatus.value = 'cloud'
|
||||
syncMessage.value = '클라우드에 저장됨'
|
||||
}
|
||||
} catch (error) {
|
||||
syncStatus.value = 'error'
|
||||
syncMessage.value = error.message || '클라우드 저장에 실패했습니다.'
|
||||
}
|
||||
}, 500)
|
||||
|
||||
syncTimers.set(recordKey, timerId)
|
||||
}
|
||||
|
||||
async function hydratePlannerRecordsFromApi() {
|
||||
if (!authToken.value) {
|
||||
return
|
||||
}
|
||||
|
||||
isHydratingRemoteRecords = true
|
||||
syncStatus.value = 'syncing'
|
||||
syncMessage.value = '클라우드 데이터를 불러오는 중...'
|
||||
|
||||
try {
|
||||
const result = await fetchPlannerEntries(authToken.value)
|
||||
const remoteRecords = {}
|
||||
|
||||
result.entries.forEach((entry) => {
|
||||
remoteRecords[entry.entryDate] = normalizeRecord(entry.payload)
|
||||
})
|
||||
|
||||
replacePlannerRecords(remoteRecords)
|
||||
|
||||
syncStatus.value = 'cloud'
|
||||
syncMessage.value = '클라우드 동기화 연결됨'
|
||||
} catch (error) {
|
||||
syncStatus.value = 'error'
|
||||
syncMessage.value = error.message || '클라우드 데이터를 불러오지 못했습니다.'
|
||||
} finally {
|
||||
isHydratingRemoteRecords = false
|
||||
}
|
||||
}
|
||||
|
||||
function applyPrintPageStyle(layout) {
|
||||
@@ -566,6 +832,11 @@ async function printSelectedPlanner(layout = 'single') {
|
||||
await nextTick()
|
||||
window.print()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
syncMessage.value = '로컬 저장 모드'
|
||||
restoreAuthSession()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -583,6 +854,52 @@ async function printSelectedPlanner(layout = 'single') {
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<div class="inline-flex items-center gap-2 rounded-full border border-stone-200 bg-white px-2 py-2">
|
||||
<template v-if="isAuthenticated">
|
||||
<div class="px-2">
|
||||
<p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">SIGNED IN</p>
|
||||
<p class="text-sm font-semibold tracking-[0.02em] text-stone-900">
|
||||
{{ currentUser.nickname }}
|
||||
</p>
|
||||
<p
|
||||
class="text-[10px] font-bold tracking-[0.12em]"
|
||||
:class="syncStatus === 'error' ? 'text-red-500' : syncStatus === 'syncing' ? 'text-blue-500' : 'text-stone-500'"
|
||||
>
|
||||
{{ syncMessage }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-stone-200 px-3 py-2 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
|
||||
@click="logout"
|
||||
>
|
||||
LOGOUT
|
||||
</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="px-2">
|
||||
<p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">MODE</p>
|
||||
<p class="text-sm font-semibold tracking-[0.02em] text-stone-900">LOCAL</p>
|
||||
<p class="text-[10px] font-bold tracking-[0.12em] text-stone-500">
|
||||
{{ syncMessage }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-stone-200 px-3 py-2 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
|
||||
@click="openAuthDialog('login')"
|
||||
>
|
||||
LOGIN
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-stone-900 bg-stone-900 px-3 py-2 text-xs font-bold tracking-[0.14em] text-white transition hover:bg-stone-700"
|
||||
@click="openAuthDialog('signup')"
|
||||
>
|
||||
SIGN UP
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
<div class="inline-flex rounded-full border border-stone-200 bg-stone-100 p-1">
|
||||
<button
|
||||
type="button"
|
||||
@@ -912,5 +1229,17 @@ async function printSelectedPlanner(layout = 'single') {
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<AuthDialog
|
||||
:open="authDialogOpen"
|
||||
:mode="authMode"
|
||||
:form="authForm"
|
||||
:busy="authBusy"
|
||||
:message="authMessage"
|
||||
@close="closeAuthDialog"
|
||||
@submit="submitAuthForm"
|
||||
@switch-mode="authMode = $event; authMessage = ''"
|
||||
@update:field="updateAuthField"
|
||||
/>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
129
src/components/AuthDialog.vue
Normal file
129
src/components/AuthDialog.vue
Normal file
@@ -0,0 +1,129 @@
|
||||
<script setup>
|
||||
const props = defineProps({
|
||||
open: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
mode: {
|
||||
type: String,
|
||||
default: 'login',
|
||||
},
|
||||
form: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
busy: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
message: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits([
|
||||
'close',
|
||||
'submit',
|
||||
'switch-mode',
|
||||
'update:field',
|
||||
])
|
||||
|
||||
function updateField(field, event) {
|
||||
emit('update:field', {
|
||||
field,
|
||||
value: event.target.value,
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-stone-900/45 px-4 py-8 backdrop-blur-sm"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-[28px] border border-white/60 bg-[#f6f1e8] p-6 shadow-2xl sm:p-7">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="space-y-2">
|
||||
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Account</p>
|
||||
<h2 class="text-2xl font-semibold tracking-[-0.04em] text-stone-900">
|
||||
{{ mode === 'login' ? '로그인' : '회원가입' }}
|
||||
</h2>
|
||||
<p class="text-sm leading-6 text-stone-600">
|
||||
{{ mode === 'login' ? '저장된 플래너를 다시 이어서 볼 수 있습니다.' : '사용자별 기록과 통계를 연결하기 위한 계정을 만듭니다.' }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-stone-300 px-3 py-2 text-[10px] font-bold tracking-[0.16em] text-stone-500 transition hover:border-stone-500 hover:text-stone-900"
|
||||
@click="emit('close')"
|
||||
>
|
||||
CLOSE
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form class="mt-6 space-y-4" @submit.prevent="emit('submit')">
|
||||
<div v-if="mode === 'signup'" class="space-y-2">
|
||||
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">닉네임</label>
|
||||
<input
|
||||
:value="form.nickname"
|
||||
type="text"
|
||||
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
|
||||
placeholder="닉네임을 입력해 주세요."
|
||||
@input="updateField('nickname', $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">이메일</label>
|
||||
<input
|
||||
:value="form.email"
|
||||
type="email"
|
||||
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
|
||||
placeholder="zenn@example.com"
|
||||
@input="updateField('email', $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">비밀번호</label>
|
||||
<input
|
||||
:value="form.password"
|
||||
type="password"
|
||||
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
|
||||
placeholder="8자 이상 입력해 주세요."
|
||||
@input="updateField('password', $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="message"
|
||||
class="rounded-2xl border border-stone-300 bg-white/80 px-4 py-3 text-sm font-semibold leading-6 text-stone-700"
|
||||
>
|
||||
{{ message }}
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
class="w-full rounded-full bg-stone-900 px-5 py-3 text-xs font-bold tracking-[0.18em] text-white transition hover:bg-stone-700 disabled:cursor-not-allowed disabled:bg-stone-400"
|
||||
:disabled="busy"
|
||||
>
|
||||
{{ busy ? '처리 중...' : mode === 'login' ? 'LOGIN' : 'SIGN UP' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="mt-5 flex items-center justify-between gap-3 rounded-2xl border border-stone-300 bg-white/70 px-4 py-3">
|
||||
<p class="text-sm font-semibold text-stone-600">
|
||||
{{ mode === 'login' ? '아직 계정이 없나요?' : '이미 계정이 있나요?' }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs font-bold tracking-[0.16em] text-stone-900 underline underline-offset-4"
|
||||
@click="emit('switch-mode', mode === 'login' ? 'signup' : 'login')"
|
||||
>
|
||||
{{ mode === 'login' ? '회원가입' : '로그인' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
81
src/lib/authClient.js
Normal file
81
src/lib/authClient.js
Normal file
@@ -0,0 +1,81 @@
|
||||
const AUTH_STORAGE_KEY = 'ten-minute-planner-auth'
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3001'
|
||||
|
||||
function buildHeaders(token, extraHeaders = {}) {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...extraHeaders,
|
||||
}
|
||||
}
|
||||
|
||||
async function request(path, { method = 'GET', token, body } = {}) {
|
||||
const response = await fetch(`${API_BASE_URL}${path}`, {
|
||||
method,
|
||||
headers: buildHeaders(token),
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || '요청 처리 중 문제가 발생했습니다.')
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
export function readAuthState() {
|
||||
if (typeof window === 'undefined') {
|
||||
return { token: '', user: null }
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(window.localStorage.getItem(AUTH_STORAGE_KEY) ?? '{"token":"","user":null}')
|
||||
} catch (error) {
|
||||
console.warn('저장된 인증 상태를 불러오지 못했습니다.', error)
|
||||
return { token: '', user: null }
|
||||
}
|
||||
}
|
||||
|
||||
export function persistAuthState({ token, user }) {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
window.localStorage.setItem(
|
||||
AUTH_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
token,
|
||||
user,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export function clearAuthState() {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
window.localStorage.removeItem(AUTH_STORAGE_KEY)
|
||||
}
|
||||
|
||||
export async function signup({ email, password, nickname }) {
|
||||
return request('/api/auth/signup', {
|
||||
method: 'POST',
|
||||
body: { email, password, nickname },
|
||||
})
|
||||
}
|
||||
|
||||
export async function login({ email, password }) {
|
||||
return request('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: { email, password },
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchCurrentUser(token) {
|
||||
return request('/api/auth/me', {
|
||||
token,
|
||||
})
|
||||
}
|
||||
58
src/lib/plannerApi.js
Normal file
58
src/lib/plannerApi.js
Normal file
@@ -0,0 +1,58 @@
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3001'
|
||||
|
||||
function buildHeaders(token) {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
}
|
||||
|
||||
async function request(path, { method = 'GET', token, body } = {}) {
|
||||
const response = await fetch(`${API_BASE_URL}${path}`, {
|
||||
method,
|
||||
headers: buildHeaders(token),
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || '플래너 데이터를 처리하지 못했습니다.')
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
export async function fetchPlannerEntries(token, range = {}) {
|
||||
const searchParams = new URLSearchParams()
|
||||
|
||||
if (range.from) {
|
||||
searchParams.set('from', range.from)
|
||||
}
|
||||
|
||||
if (range.to) {
|
||||
searchParams.set('to', range.to)
|
||||
}
|
||||
|
||||
const query = searchParams.toString()
|
||||
return request(`/api/planner${query ? `?${query}` : ''}`, {
|
||||
token,
|
||||
})
|
||||
}
|
||||
|
||||
export async function savePlannerEntry(token, entryDate, payload) {
|
||||
return request(`/api/planner/${entryDate}`, {
|
||||
method: 'PUT',
|
||||
token,
|
||||
body: {
|
||||
payload,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function deletePlannerEntry(token, entryDate) {
|
||||
return request(`/api/planner/${entryDate}`, {
|
||||
method: 'DELETE',
|
||||
token,
|
||||
})
|
||||
}
|
||||
@@ -13,6 +13,10 @@ function readStorageState() {
|
||||
}
|
||||
}
|
||||
|
||||
export function readPlannerStorageState() {
|
||||
return readStorageState()
|
||||
}
|
||||
|
||||
export function createInitialPlannerRecords(seedRecords, normalizeRecord) {
|
||||
const baseRecords = Object.fromEntries(
|
||||
Object.entries(seedRecords).map(([key, record]) => [key, normalizeRecord(record)]),
|
||||
@@ -62,31 +66,37 @@ export function persistPlannerState({
|
||||
calendarViewDate,
|
||||
statsRangeStart,
|
||||
statsRangeEnd,
|
||||
includeRecords = true,
|
||||
}) {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
const serializableRecords = Object.fromEntries(
|
||||
Object.entries(plannerRecords).map(([key, record]) => [
|
||||
key,
|
||||
{
|
||||
...record,
|
||||
tasks: record.tasks.map((task) => ({ ...task })),
|
||||
memo: record.memo.map((item) => ({ ...item })),
|
||||
timetable: [...record.timetable],
|
||||
},
|
||||
]),
|
||||
)
|
||||
const previousState = readStorageState()
|
||||
const nextState = {
|
||||
...previousState,
|
||||
selectedDate: selectedDate.toISOString(),
|
||||
calendarViewDate: calendarViewDate.toISOString(),
|
||||
statsRangeStart,
|
||||
statsRangeEnd,
|
||||
}
|
||||
|
||||
if (includeRecords) {
|
||||
nextState.records = Object.fromEntries(
|
||||
Object.entries(plannerRecords).map(([key, record]) => [
|
||||
key,
|
||||
{
|
||||
...record,
|
||||
tasks: record.tasks.map((task) => ({ ...task })),
|
||||
memo: record.memo.map((item) => ({ ...item })),
|
||||
timetable: [...record.timetable],
|
||||
},
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
window.localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
selectedDate: selectedDate.toISOString(),
|
||||
calendarViewDate: calendarViewDate.toISOString(),
|
||||
statsRangeStart,
|
||||
statsRangeEnd,
|
||||
records: serializableRecords,
|
||||
}),
|
||||
JSON.stringify(nextState),
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user