refactor: replace common confirm dialogs with maintenance CRUD dialogs and streamline form handling in MasterDetailMntC.vue and SingleRecordMnt.vue

This commit is contained in:
skytek_xinliang
2026-03-26 16:01:20 +08:00
parent ec3fbace1a
commit 389ec56480
32 changed files with 2549 additions and 2763 deletions
+2 -1
View File
@@ -125,7 +125,8 @@ v-model="snackbar.visible" :color="snackbar.color" :location="snackbar.location"
import { mdiAccountGroup, mdiBellOutline, mdiCalendarOutline, mdiChartBoxOutline, mdiClose, mdiCloseCircle, mdiCog, mdiDomain, mdiFileDocumentOutline, mdiFileTreeOutline, mdiHome, mdiHomeCityOutline, mdiMenu, mdiPlusCircle, mdiSchoolOutline, mdiTableEdit, mdiViewDashboardVariant } from '@mdi/js' import { mdiAccountGroup, mdiBellOutline, mdiCalendarOutline, mdiChartBoxOutline, mdiClose, mdiCloseCircle, mdiCog, mdiDomain, mdiFileDocumentOutline, mdiFileTreeOutline, mdiHome, mdiHomeCityOutline, mdiMenu, mdiPlusCircle, mdiSchoolOutline, mdiTableEdit, mdiViewDashboardVariant } from '@mdi/js'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { SKAdminLayout, SKEmptyLayout } from '../src' import SKAdminLayout from '@/components/layouts/SKAdminLayout.vue'
import SKEmptyLayout from '@/components/layouts/SKEmptyLayout.vue'
import { HTTP_TOAST_EVENT } from './services/http-toast' import { HTTP_TOAST_EVENT } from './services/http-toast'
import { SESSION_FORCE_LOGOUT_EVENT } from './services/session' import { SESSION_FORCE_LOGOUT_EVENT } from './services/session'
import { useAuthStore } from './stores/auth' import { useAuthStore } from './stores/auth'

Before

Width:  |  Height:  |  Size: 439 B

After

Width:  |  Height:  |  Size: 439 B

-5
View File
@@ -1,5 +0,0 @@
<template>
<div class="d-flex align-center justify-center pa-8 text-body-1">
Hello World
</div>
</template>
+129 -256
View File
@@ -66,10 +66,10 @@ v-model:opened="opened" :is-shrink="isRail" :menu-items="menuItems"
<template v-if="isMobile"> <template v-if="isMobile">
<SkAdminDrawerMobileFavoritesPanel <SkAdminDrawerMobileFavoritesPanel
v-if="features.showFavorites && mobileFavoritesPanel" v-if="features.showFavorites && mobileFavoritesPanel"
:favorite-items="favoriteItems" @select="handleSelectFavorite" /> :favorite-items="favoriteItems" @select="onSelectFavorite" />
<SkAdminDrawerMobileMenuPanel <SkAdminDrawerMobileMenuPanel
v-else :mobile-current-items="mobileCurrentItems" v-else :mobile-current-items="mobileCurrentItems"
@item-click="handleMobileMenuClick" /> @item-click="onMobileMenuClick" />
</template> </template>
</v-navigation-drawer> </v-navigation-drawer>
@@ -145,11 +145,25 @@ aria-label="關閉說明" :icon="mdiClose" size="small" variant="text"
</v-app> </v-app>
</template> </template>
<script setup> <script setup lang="ts">
import { mdiClose, mdiHelpCircleOutline, mdiHome, mdiMenu, mdiMenuOpen } from '@mdi/js' import { mdiClose, mdiHelpCircleOutline, mdiHome, mdiMenu, mdiMenuOpen } from '@mdi/js'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { computed, ref } from 'vue'
import { useDisplay, useTheme } from 'vuetify' import { useAdminLayoutState } from '@/composables/layout/useAdminLayoutState'
import { getNextThemeName } from '@/utils/theme' import { useDisplay } from 'vuetify'
import { useThemeToggle } from '@/composables/layout/useThemeToggle'
import type {
AdminLayoutActionType,
AdminLayoutBreadcrumbConfig,
AdminLayoutBreadcrumbItem,
AdminLayoutDrawerConfig,
AdminLayoutFavoritesConfig,
AdminLayoutFeatures,
AdminLayoutMenuItem,
AdminLayoutSearchConfig,
AdminLayoutToolbarActions,
AdminLayoutToolbarCounts,
AdminLayoutUserProfile,
} from './sk-admin-layout/types'
import SkAdminAppBarBreadcrumbCol from './sk-admin-layout/SkAdminAppBarBreadcrumbCol.vue' import SkAdminAppBarBreadcrumbCol from './sk-admin-layout/SkAdminAppBarBreadcrumbCol.vue'
import SkAdminAppBarFavoritesCol from './sk-admin-layout/SkAdminAppBarFavoritesCol.vue' import SkAdminAppBarFavoritesCol from './sk-admin-layout/SkAdminAppBarFavoritesCol.vue'
import SkAdminAppBarTopCol from './sk-admin-layout/SkAdminAppBarTopCol.vue' import SkAdminAppBarTopCol from './sk-admin-layout/SkAdminAppBarTopCol.vue'
@@ -157,21 +171,21 @@ import SkAdminDrawerDesktopMenu from './sk-admin-layout/SkAdminDrawerDesktopMenu
import SkAdminDrawerMobileFavoritesPanel from './sk-admin-layout/SkAdminDrawerMobileFavoritesPanel.vue' import SkAdminDrawerMobileFavoritesPanel from './sk-admin-layout/SkAdminDrawerMobileFavoritesPanel.vue'
import SkAdminDrawerMobileMenuPanel from './sk-admin-layout/SkAdminDrawerMobileMenuPanel.vue' import SkAdminDrawerMobileMenuPanel from './sk-admin-layout/SkAdminDrawerMobileMenuPanel.vue'
const emit = defineEmits([ const emit = defineEmits<{
'logout', logout: []
'select', select: [item: AdminLayoutMenuItem]
'search', search: [keyword: string]
'action', action: [type: AdminLayoutActionType]
'toggle-sidebar', 'toggle-sidebar': [payload: { drawer: boolean, rail: boolean }]
'toggle-theme', 'toggle-theme': [themeName: string]
'add-favorite', 'add-favorite': []
'remove-favorite', 'remove-favorite': [item: AdminLayoutMenuItem]
'update:isRail', 'update:isRail': [value: boolean]
'update:favoritesBarVisible', 'update:favoritesBarVisible': [value: boolean]
'update:breadcrumbBarVisible', 'update:breadcrumbBarVisible': [value: boolean]
]) }>()
const defaultFeatures = { const defaultFeatures: AdminLayoutFeatures = {
showThemeToggle: false, showThemeToggle: false,
showFavorites: true, showFavorites: true,
showBreadcrumb: true, showBreadcrumb: true,
@@ -180,111 +194,91 @@ const defaultFeatures = {
showUserInfo: true, showUserInfo: true,
} }
const defaultBreadcrumbConfig = { const defaultBreadcrumbConfig: AdminLayoutBreadcrumbConfig = {
homeLabel: '首頁', homeLabel: '首頁',
homeDisabled: true, homeDisabled: true,
homeIcon: mdiHome, homeIcon: mdiHome,
} }
const props = defineProps({ interface Props {
systemTitle: { type: String, default: '管理系統' }, systemTitle?: string
systemSubtitle: { type: String, default: 'Campus System' }, systemSubtitle?: string
themeToggleLabel: { type: String, default: '切換主題' }, themeToggleLabel?: string
logoutLabel: { type: String, default: '登出' }, logoutLabel?: string
sidebarToggleLabel: { type: String, default: '切換側欄' }, sidebarToggleLabel?: string
favoriteHeaderLabel: { type: String, default: '我的最愛' }, favoriteHeaderLabel?: string
favoriteItems: { favoriteItems?: AdminLayoutMenuItem[]
type: Array, menuItems?: AdminLayoutMenuItem[]
default: () => [], userProfile?: AdminLayoutUserProfile
}, searchConfig?: AdminLayoutSearchConfig
menuItems: { toolbarActions?: AdminLayoutToolbarActions
type: Array, toolbarCounts?: AdminLayoutToolbarCounts
default: () => [ favoritesConfig?: AdminLayoutFavoritesConfig
breadcrumbConfig?: AdminLayoutBreadcrumbConfig
breadcrumbItems?: AdminLayoutBreadcrumbItem[]
favoritesBarVisible?: boolean | null
breadcrumbBarVisible?: boolean | null
isRail?: boolean | null
features?: Partial<AdminLayoutFeatures>
drawerConfig?: AdminLayoutDrawerConfig
}
const props = withDefaults(defineProps<Props>(), {
systemTitle: '管理系統',
systemSubtitle: 'Campus System',
themeToggleLabel: '切換主題',
logoutLabel: '登出',
sidebarToggleLabel: '切換側欄',
favoriteHeaderLabel: '我的最愛',
favoriteItems: () => [],
menuItems: () => [
{ title: '首頁', path: '/' }, { title: '首頁', path: '/' },
], ],
}, userProfile: () => ({
userProfile: {
type: Object,
default: () => ({
name: '王小明', name: '王小明',
role: '資訊工程系 - 學生', role: '資訊工程系 - 學生',
avatarText: '王', avatarText: '王',
}), }),
}, searchConfig: () => ({
searchConfig: {
type: Object,
default: () => ({
placeholder: '搜尋功能名稱... (試試「成績」、「選課」、「請假」)', placeholder: '搜尋功能名稱... (試試「成績」、「選課」、「請假」)',
label: '搜尋', label: '搜尋',
}), }),
}, toolbarActions: () => ({
toolbarActions: {
type: Object,
default: () => ({
notificationsLabel: '通知', notificationsLabel: '通知',
messagesLabel: '訊息', messagesLabel: '訊息',
helpLabel: '說明', helpLabel: '說明',
settingsLabel: '設定', settingsLabel: '設定',
}), }),
}, toolbarCounts: () => ({
toolbarCounts: {
type: Object,
default: () => ({
notifications: 0, notifications: 0,
messages: 0, messages: 0,
}), }),
}, favoritesConfig: () => ({
favoritesConfig: {
type: Object,
default: () => ({
label: '常用', label: '常用',
addLabel: '新增常用', addLabel: '新增常用',
showAdd: false, showAdd: false,
}), }),
}, breadcrumbConfig: () => ({
breadcrumbConfig: {
type: Object,
default: () => ({
homeLabel: '首頁', homeLabel: '首頁',
homeDisabled: true, homeDisabled: true,
homeIcon: mdiHome, homeIcon: mdiHome,
}), }),
}, breadcrumbItems: () => [],
breadcrumbItems: { favoritesBarVisible: null,
type: Array, breadcrumbBarVisible: null,
default: () => [], isRail: null,
}, features: () => ({
favoritesBarVisible: { showThemeToggle: false,
type: [Boolean, null], showFavorites: true,
default: null, showBreadcrumb: true,
}, showSearch: true,
breadcrumbBarVisible: { showToolbarActions: true,
type: [Boolean, null], showUserInfo: true,
default: null, }),
}, drawerConfig: () => ({
isRail: {
type: [Boolean, null],
default: null,
},
features: {
type: Object,
default: () => ({
showThemeToggle: false,
showFavorites: true,
showBreadcrumb: true,
showSearch: true,
showToolbarActions: true,
showUserInfo: true,
showMenuHeader: false,
}),
},
drawerConfig: {
type: Object,
default: () => ({
width: 280, width: 280,
railWidth: 56, railWidth: 56,
}), }),
},
}) })
// Feature toggle: UI 區塊顯示 // Feature toggle: UI 區塊顯示
@@ -296,39 +290,16 @@ const branding = computed(() => ({
subtitle: props.systemSubtitle, subtitle: props.systemSubtitle,
})) }))
// feature toggles & layout
const display = useDisplay() const display = useDisplay()
const isMobile = computed(() => display.mdAndDown.value) const isMobile = computed(() => display.mdAndDown.value)
const drawer = ref(true) const appBarRef = ref<HTMLElement | null>(null)
const mobileFavoritesPanel = ref(false)
const localIsRail = ref(false)
const isRail = computed({
get: () => (props.isRail ?? localIsRail.value),
set: (value) => {
if (props.isRail === null) {
localIsRail.value = value
return
}
emit('update:isRail', value)
},
})
const opened = ref([])
const appBarRef = ref(null)
const appBarHeight = ref(0)
const helpWidgetVisible = ref(false) const helpWidgetVisible = ref(false)
const drawerWidth = computed(() => props.drawerConfig?.width) const drawerWidth = computed(() => props.drawerConfig?.width)
const railWidth = computed(() => props.drawerConfig?.railWidth) const railWidth = computed(() => props.drawerConfig?.railWidth)
// i18n computed text
const searchValue = ref('') const searchValue = ref('')
const { toggleTheme: switchTheme } = useThemeToggle()
// links/settings refs
const theme = useTheme()
const availableThemeNames = computed(() =>
Object.keys(theme.themes.value ?? {}).filter((name) => name.startsWith('theme'))
)
// composed computed objects
const breadcrumbConfig = computed(() => ({ ...defaultBreadcrumbConfig, ...props.breadcrumbConfig })) const breadcrumbConfig = computed(() => ({ ...defaultBreadcrumbConfig, ...props.breadcrumbConfig }))
const breadcrumbItems = computed(() => { const breadcrumbItems = computed(() => {
@@ -342,31 +313,46 @@ const breadcrumbItems = computed(() => {
] ]
}) })
// event handlers / API const {
drawer,
goToMobileLevel,
handleMobileMenuClick,
handleSelectFavorite,
handleUnshrink,
isRail,
mainStyle,
mobileCurrentItems,
mobileCurrentLevel,
mobileFavoritesPanel,
mobileMenuLevels,
openMobileFavoritesPanel,
opened,
showBreadcrumbBar,
showFavoritesBar,
toggleFavoritesBar,
toggleSidebar,
} = useAdminLayoutState({
appBarRef,
breadcrumbBarVisible: props.breadcrumbBarVisible,
emitUpdateBreadcrumbBarVisible: (value) => emit('update:breadcrumbBarVisible', value),
emitUpdateFavoritesBarVisible: (value) => emit('update:favoritesBarVisible', value),
emitUpdateIsRail: (value) => emit('update:isRail', value),
favoritesBarVisible: props.favoritesBarVisible,
isMobile,
isRail: props.isRail,
menuItems: props.menuItems,
onToggleSidebar: (payload) => emit('toggle-sidebar', payload),
})
function toggleTheme () { function toggleTheme () {
const names = availableThemeNames.value const next = switchTheme()
if (names.length === 0) return
const current = theme.global.name.value
const next = getNextThemeName(names, current)
if (!next) return if (!next) return
theme.change(next)
emit('toggle-theme', next) emit('toggle-theme', next)
} }
function toggleSidebar () {
if (isMobile.value) {
drawer.value = !drawer.value
} else {
isRail.value = !isRail.value
}
emit('toggle-sidebar', { drawer: drawer.value, rail: isRail.value })
}
const emitLogout = () => emit('logout') const emitLogout = () => emit('logout')
// 將工具列按鈕行為轉成統一的 action 事件,交由外層應用處理 function handleAction (type: AdminLayoutActionType) {
function handleAction (type) {
if (type === 'help') { if (type === 'help') {
helpWidgetVisible.value = true helpWidgetVisible.value = true
} }
@@ -385,143 +371,30 @@ function emitAddFavorite () {
emit('add-favorite') emit('add-favorite')
} }
function emitRemoveFavorite (item) { function emitRemoveFavorite (item: AdminLayoutMenuItem) {
emit('remove-favorite', item) emit('remove-favorite', item)
} }
function handleSelectFavorite (item) { function onSelectFavorite (item: AdminLayoutMenuItem) {
handleSelect(item) handleSelectFavorite(item, handleSelect)
mobileFavoritesPanel.value = false
} }
const mobileMenuPath = ref([]) function onMobileMenuClick (item: AdminLayoutMenuItem) {
const mobileCurrentItems = computed(() => handleMobileMenuClick(item, handleSelect)
mobileMenuPath.value.reduce((items, currentItem) => currentItem?.subItems ?? [], props.menuItems || [])
)
const mobileCurrentLevel = computed(() => mobileMenuPath.value.length + 1)
const mobileMenuLevels = computed(() =>
Array.from({ length: mobileCurrentLevel.value }, (_, index) => ({
level: index + 1,
title: index === 0 ? '主選單' : (mobileMenuPath.value[index - 1]?.title ?? `${index + 1}`),
}))
)
function goToMobileLevel (level) {
mobileFavoritesPanel.value = false
mobileMenuPath.value = mobileMenuPath.value.slice(0, Math.max(0, level - 1))
} }
function openMobileFavoritesPanel () { function handleSelect (item: AdminLayoutMenuItem) {
mobileMenuPath.value = []
mobileFavoritesPanel.value = true
}
function handleMobileMenuClick (item) {
if (item?.subItems?.length) {
mobileMenuPath.value = [...mobileMenuPath.value, item]
return
}
handleSelect(item)
}
const localFavoritesBarVisible = ref(true)
const localBreadcrumbBarVisible = ref(true)
const showFavoritesBar = computed({
get: () => (props.favoritesBarVisible ?? localFavoritesBarVisible.value),
set: (value) => {
if (props.favoritesBarVisible === null) {
localFavoritesBarVisible.value = value
return
}
emit('update:favoritesBarVisible', value)
},
})
const showBreadcrumbBar = computed({
get: () => (props.breadcrumbBarVisible ?? localBreadcrumbBarVisible.value),
set: (value) => {
if (props.breadcrumbBarVisible === null) {
localBreadcrumbBarVisible.value = value
return
}
emit('update:breadcrumbBarVisible', value)
},
})
function toggleFavoritesBar (nextValue) {
showFavoritesBar.value = typeof nextValue === 'boolean' ? nextValue : !showFavoritesBar.value
}
let appBarObserver
// 量測 v-app-bar 實際高度(常用功能/麵包屑顯示時會改變)
function updateAppBarHeight () {
const el = appBarRef.value?.$el ?? appBarRef.value
if (!el) return
appBarHeight.value = Math.round(el.getBoundingClientRect().height || 0)
}
onMounted(() => {
// 初次量測高度
updateAppBarHeight()
if (typeof ResizeObserver === 'undefined') return
const el = appBarRef.value?.$el ?? appBarRef.value
if (!el) return
// 監聽高度變化,讓 v-main paddingTop 同步更新
appBarObserver = new ResizeObserver(() => updateAppBarHeight())
appBarObserver.observe(el)
})
onBeforeUnmount(() => {
if (!appBarObserver) return
appBarObserver.disconnect()
appBarObserver = null
})
function handleUnshrink () {
isRail.value = false
}
function handleSelect (item) {
emit('select', item) emit('select', item)
if (isMobile.value) drawer.value = false if (isMobile.value) drawer.value = false
} }
const mainStyle = computed(() => { function getMobileMenuBtnVariant (level: number) {
const appBarHeightValue = appBarHeight.value
return {
// 以 paddingTop 騰出 appBar 空間,避免內容被遮擋
paddingTop: appBarHeightValue ? `${appBarHeightValue}px` : undefined,
// 固定 v-main 高度,讓內容區塊能在固定高度內滾動
height: '100vh',
minHeight: 0,
flex: '1 1 0',
}
})
// watch(isMobile, (value) => {
// if (value) {
// isRail.value = false
// }
// })
watch(isMobile, (value) => {
if (!value) {
mobileFavoritesPanel.value = false
mobileMenuPath.value = []
}
})
watch(drawer, (value) => {
if (!value) {
mobileFavoritesPanel.value = false
mobileMenuPath.value = []
}
})
function getMobileMenuBtnVariant (level) {
return !mobileFavoritesPanel.value && level === mobileCurrentLevel.value return !mobileFavoritesPanel.value && level === mobileCurrentLevel.value
? 'flat' ? 'flat'
: 'outlined' : 'outlined'
} }
function getMobileMenuBtnColor (level) { function getMobileMenuBtnColor (level: number) {
return level === mobileCurrentLevel.value ? 'primary' : 'secondary' return level === mobileCurrentLevel.value ? 'primary' : 'secondary'
} }
</script> </script>
+48 -238
View File
@@ -1,252 +1,62 @@
<template> <template>
<v-app> <SKAdminLayout
<v-navigation-drawer v-model="drawer"> :favorite-items="favoriteItems"
<v-list v-model:opened="opened" color="primary" density="compact" prepend-gap="8"> :favorites-config="favoritesConfig"
<!-- 收藏項目區塊 --> :menu-items="menuItems"
<template v-if="favoriteItems?.length"> :system-title="systemTitle"
<v-list-subheader class="bg-primary-variant" color="on-primary"> :theme-toggle-label="themeToggleLabel"
<div class="d-flex align-center w-100"> :logout-label="logoutLabel"
<span class="flex-grow-1">{{ favoriteHeaderLabel }}</span> :features="features"
<v-btn @logout="$emit('logout')"
density="compact" :icon="mdiUnfoldLessHorizontal" :ripple="false" variant="text" @select="$emit('select', $event)"
@click.stop="collapseFavoriteGroups" /> >
</div> <slot />
</v-list-subheader> </SKAdminLayout>
<template v-for="item in favoriteItems" :key="item.path ?? item.title">
<!-- 第一層有子項目的群組 -->
<v-list-group v-if="item.subItems?.length" :value="`fav:${item.path ?? item.title}`">
<template #activator="{ props }">
<v-list-item v-bind="props" :link="isNavigable(item)" :to="isNavigable(item) ? item.path : undefined">
<!-- 第一層 title父層 -->
<template #title>
<span class="text-body-2 nav-text-overflow">{{ item.title }}</span>
</template>
</v-list-item>
</template>
<template v-for="subItem in item.subItems" :key="subItem.path ?? subItem.title">
<!-- 第二層無子項目的單一項目 -->
<v-list-item :link="!!subItem.path" :to="subItem.path">
<!-- 第二層 title葉節點 -->
<template #title>
<v-tooltip location="end" :text="subItem.title">
<template #activator="{ props: tooltipProps }">
<span v-bind="tooltipProps" class="text-body-2 nav-text-overflow">{{ subItem.title }}</span>
</template>
</v-tooltip>
</template>
</v-list-item>
</template>
</v-list-group>
<!-- 第一層無子項目的單一項目 -->
<v-list-item v-else :link="!!item.path" :to="item.path">
<!-- 第一層 title葉節點 -->
<template #title>
<v-tooltip location="end" :text="item.title">
<template #activator="{ props: tooltipProps }">
<span v-bind="tooltipProps" class="text-body-2 nav-text-overflow">{{ item.title }}</span>
</template>
</v-tooltip>
</template>
</v-list-item>
</template>
</template>
<v-list-subheader class="bg-primary" color="on-primary">
<div class="d-flex align-center w-100">
<span class="flex-grow-1">{{ menuHeaderLabel }}</span>
<v-btn
density="compact" :icon="mdiUnfoldLessHorizontal" :ripple="false" variant="text"
@click.stop="collapseMenuGroups" />
</div>
</v-list-subheader>
<!-- 主選單區塊 -->
<template v-for="item in menuItems" :key="item.path ?? item.title">
<!-- 第一層有子項目的群組 -->
<v-list-group v-if="item.subItems?.length" :value="`menu:${item.path ?? item.title}`">
<template #activator="{ props }">
<v-list-item
v-bind="props" :link="isNavigable(item) && !!item.path"
:to="isNavigable(item) ? item.path : undefined">
<!-- 第一層 title父層 -->
<template #title>
<span class="text-body-2 nav-text-overflow">{{ item.title }}</span>
</template>
</v-list-item>
</template>
<template v-for="subItem in item.subItems" :key="subItem.path ?? subItem.title">
<!-- 第二層有子項目的群組 -->
<v-list-group
v-if="subItem.subItems?.length"
:value="`menu:${item.path ?? item.title}::${subItem.path ?? subItem.title}`">
<template #activator="{ props: subProps }">
<v-list-item
v-bind="subProps" :link="isNavigable(subItem)"
:to="isNavigable(subItem) ? subItem.path : undefined">
<!-- 第二層 title父層 -->
<template #title>
<span class="text-body-2 nav-text-overflow">{{ subItem.title }}</span>
</template>
</v-list-item>
</template>
<!-- 第三層最底層項目 -->
<v-list-item
v-for="subSubItem in subItem.subItems" :key="subSubItem.path ?? subSubItem.title"
:link="!!subSubItem.path" :to="subSubItem.path">
<!-- 第三層 title葉節點 -->
<template #title>
<v-tooltip location="end" :text="subSubItem.title">
<template #activator="{ props: tooltipProps }">
<span v-bind="tooltipProps" class="text-body-2 nav-text-overflow">{{ subSubItem.title }}</span>
</template>
</v-tooltip>
</template>
</v-list-item>
</v-list-group>
<!-- 第二層無子項目的單一項目 -->
<v-list-item v-else :link="!!subItem.path" :to="subItem.path">
<!-- 第二層 title葉節點 -->
<template #title>
<v-tooltip location="end" :text="subItem.title">
<template #activator="{ props: tooltipProps }">
<span v-bind="tooltipProps" class="text-body-2 nav-text-overflow">{{ subItem.title }}</span>
</template>
</v-tooltip>
</template>
</v-list-item>
</template>
</v-list-group>
<!-- 第一層無子項目的單一項目 -->
<v-list-item v-else :link="!!item.path" :to="item.path">
<!-- 第一層 title葉節點 -->
<template #title>
<v-tooltip location="end" :text="item.title">
<template #activator="{ props: tooltipProps }">
<span v-bind="tooltipProps" class="text-body-2 nav-text-overflow">{{ item.title }}</span>
</template>
</v-tooltip>
</template>
</v-list-item>
</template>
</v-list>
</v-navigation-drawer>
<v-app-bar density="compact">
<v-app-bar-nav-icon @click="drawer = !drawer" />
<v-toolbar-title>{{ systemTitle }}</v-toolbar-title>
<v-spacer />
<v-tooltip location="bottom" :text="themeToggleLabel">
<template #activator="{ props }">
<v-btn v-bind="props" :aria-label="themeToggleLabel" :icon="mdiPalette" variant="text" @click="toggleTheme" />
</template>
</v-tooltip>
<v-tooltip location="bottom" :text="logoutLabel">
<template #activator="{ props }">
<v-btn v-bind="props" :aria-label="logoutLabel" :icon="mdiLogout" variant="text" @click="$emit('logout')" />
</template>
</v-tooltip>
</v-app-bar>
<v-main>
<v-container class="pa-2" fluid height="100%">
<slot></slot>
</v-container>
</v-main>
</v-app>
</template> </template>
<script setup> <script setup lang="ts">
import { mdiLogout, mdiPalette, mdiUnfoldLessHorizontal } from '@mdi/js' import { computed } from 'vue'
import { computed, ref } from 'vue' import type { AdminLayoutFavoritesConfig, AdminLayoutMenuItem } from './sk-admin-layout/types'
import { useTheme } from 'vuetify' import SKAdminLayout from './SKAdminLayout.vue'
import { getNextThemeName } from '@/utils/theme'
defineEmits(['logout']) interface Props {
systemTitle?: string
themeToggleLabel?: string
logoutLabel?: string
favoriteHeaderLabel?: string
favoriteItems?: AdminLayoutMenuItem[]
menuItems?: AdminLayoutMenuItem[]
}
defineProps({ const props = withDefaults(defineProps<Props>(), {
systemTitle: { type: String, default: '管理系統' }, systemTitle: '管理系統',
themeToggleLabel: { type: String, default: '切換主題' }, themeToggleLabel: '切換主題',
logoutLabel: { type: String, default: '登出' }, logoutLabel: '登出',
favoriteHeaderLabel: { type: String, default: '我的最愛' }, favoriteHeaderLabel: '我的最愛',
menuHeaderLabel: { type: String, default: '選單' }, favoriteItems: () => [],
favoriteItems: { menuItems: () => [
type: Array,
default: () => [],
},
menuItems: {
type: Array,
default: () => [
{ title: '首頁', path: '/' }, { title: '首頁', path: '/' },
{ title: '設定', path: '/settings' }, { title: '設定', path: '/settings' },
], ],
},
}) })
const drawer = ref(true) defineEmits<{
logout: []
select: [item: AdminLayoutMenuItem]
}>()
const opened = ref([]) const features = {
showThemeToggle: true,
const theme = useTheme() showFavorites: true,
showBreadcrumb: false,
const availableThemeNames = computed(() => showSearch: false,
Object.keys(theme.themes.value ?? {}).filter((name) => name.startsWith('theme')) showToolbarActions: false,
) showUserInfo: false,
function toggleTheme () {
const names = availableThemeNames.value
if (names.length === 0) return
const current = theme.global.name.value
const next = getNextThemeName(names, current)
if (!next) return
theme.change(next)
} }
function collapseFavoriteGroups () { const favoritesConfig = computed<AdminLayoutFavoritesConfig>(() => ({
opened.value = opened.value.filter((key) => !String(key).startsWith('fav:')) label: props.favoriteHeaderLabel,
} addLabel: props.favoriteHeaderLabel,
showAdd: false,
function collapseMenuGroups () { }))
opened.value = opened.value.filter((key) => !String(key).startsWith('menu:'))
}
const isNavigable = (item) => item?.navigable !== false
</script> </script>
<style scoped>
.nav-text-overflow {
display: inline-block;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* 確保 v-list-group 的 activator 也有 hover 效果 */
:deep(.v-list-group > .v-list-item) {
cursor: pointer;
transition: background-color 0.2s ease, color 0.2s ease;
}
:deep(.v-list-group > .v-list-item:hover) {
background: rgb(var(--v-theme-on-surface-variant));
color: rgb(var(--v-theme-on-surface));
}
/* 為所有 v-list-item 加上 transition */
:deep(.v-list-item) {
transition: background-color 0.2s ease, color 0.2s ease;
}
:deep(.v-navigation-drawer__content) {
scrollbar-gutter: stable;
}
@supports not (scrollbar-gutter: stable) {
:deep(.v-navigation-drawer__content) {
overflow-y: scroll;
}
}
</style>
+27 -110
View File
@@ -1,119 +1,36 @@
<template> <template>
<v-app> <SKAdminLayout
<v-app-bar color="surface"> :menu-items="menuItems"
<v-toolbar-title>{{ systemTitle }}</v-toolbar-title> :system-title="systemTitle"
<v-spacer /> :features="features"
<v-menu @select="$emit('select', $event)"
v-model="menuOpen" >
:close-on-content-click="false" <slot />
:location="menuLocation" </SKAdminLayout>
:max-height="menuMaxHeight"
offset="8"
scroll-strategy="reposition"
:width="menuWidth"
>
<template #activator="{ props }">
<v-btn v-bind="props" :icon="mdiDotsVertical" />
</template>
<v-list :density="menuDensity">
<template v-for="(item, index) in menuItems" :key="item?.key ?? item?.path ?? index">
<v-list-group
v-if="smAndDown && item?.subItems?.length"
:value="item?.key ?? item?.path ?? index"
>
<template #activator="{ props }">
<v-list-item v-bind="props" :prepend-icon="item.icon" :title="item.title" />
</template>
<v-list-item
v-for="(subItem, subIndex) in item.subItems"
:key="subItem?.key ?? subItem?.path ?? subIndex"
class="pl-6"
:prepend-icon="subItem.icon"
:title="subItem.title"
@click="handleSelect(subItem)"
/>
</v-list-group>
<v-menu
v-else-if="item?.subItems?.length"
close-delay="120"
:close-on-content-click="false"
location="end top"
offset="0"
open-delay="80"
:open-on-hover="submenuOpenOnHover"
origin="start top"
scroll-strategy="reposition"
submenu
>
<template #activator="{ props }">
<v-list-item
v-bind="props"
:append-icon="mdiChevronRight"
:prepend-icon="item.icon"
:title="item.title"
/>
</template>
<v-list :density="menuDensity">
<v-list-item
v-for="(subItem, subIndex) in item.subItems"
:key="subItem?.key ?? subItem?.path ?? subIndex"
:prepend-icon="subItem.icon"
:title="subItem.title"
@click="handleSelect(subItem)"
/>
</v-list>
</v-menu>
<v-list-item
v-else
:prepend-icon="item.icon"
:title="item.title"
@click="handleSelect(item)"
/>
</template>
</v-list>
</v-menu>
</v-app-bar>
<v-main>
<v-container fluid height="100%">
<slot></slot>
</v-container>
</v-main>
</v-app>
</template> </template>
<script setup> <script setup lang="ts">
import { mdiChevronRight, mdiDotsVertical } from '@mdi/js' import type { AdminLayoutMenuItem } from './sk-admin-layout/types'
import { computed, ref } from 'vue' import SKAdminLayout from './SKAdminLayout.vue'
import { useDisplay } from 'vuetify'
const emit = defineEmits(['select']) withDefaults(defineProps<{
systemTitle?: string
defineProps({ menuItems?: AdminLayoutMenuItem[]
systemTitle: { type: String, default: '簡潔模式' }, }>(), {
menuItems: { systemTitle: '簡潔模式',
type: Array, menuItems: () => [],
default: () => [],
},
}) })
const menuOpen = ref(false) defineEmits<{
select: [item: AdminLayoutMenuItem]
}>()
const { smAndDown } = useDisplay() const features = {
showThemeToggle: false,
const menuDensity = computed(() => (smAndDown.value ? 'default' : 'compact')) showFavorites: false,
const menuWidth = computed(() => (smAndDown.value ? 280 : 240)) showBreadcrumb: false,
const menuMaxHeight = computed(() => (smAndDown.value ? 420 : 360)) showSearch: false,
const menuLocation = computed(() => (smAndDown.value ? 'bottom end' : 'bottom end')) showToolbarActions: false,
const submenuOpenOnHover = computed(() => !smAndDown.value) showUserInfo: false,
function handleSelect (item) {
menuOpen.value = false
emit('select', item)
} }
</script> </script>
@@ -12,8 +12,8 @@ v-if="features.showFavorites && !showFavoritesBar" class="mr-2" color="primary"
</template> </template>
<template #item="{ item }"> <template #item="{ item }">
<div class="d-flex align-center ga-1"> <div class="d-flex align-center ga-1">
<v-icon v-if="item.icon" class="mr-1" size="14" :icon="item.icon" /> <v-icon v-if="getBreadcrumbIcon(item)" class="mr-1" size="14" :icon="getBreadcrumbIcon(item)" />
<span class="text-caption text-no-wrap">{{ item.title }}</span> <span class="text-caption text-no-wrap">{{ getBreadcrumbTitle(item) }}</span>
</div> </div>
</template> </template>
<template #divider> <template #divider>
@@ -26,15 +26,51 @@ v-if="features.showFavorites && !showFavoritesBar" class="mr-2" color="primary"
</v-col> </v-col>
</template> </template>
<script setup> <script setup lang="ts">
import { mdiChevronRight } from '@mdi/js' import { mdiChevronRight } from '@mdi/js'
defineProps({ import type { AdminLayoutBreadcrumbItem, AdminLayoutFeatures } from './types'
features: { type: Object, default: () => ({}) },
showBreadcrumbBar: { type: Boolean, default: true }, interface Props {
isMobile: { type: Boolean, default: false }, features?: AdminLayoutFeatures
breadcrumbItems: { type: Array, default: () => [] }, showBreadcrumbBar?: boolean
showFavoritesBar: { type: Boolean, default: true }, isMobile?: boolean
breadcrumbItems?: AdminLayoutBreadcrumbItem[]
showFavoritesBar?: boolean
}
withDefaults(defineProps<Props>(), {
features: () => ({
showThemeToggle: false,
showFavorites: true,
showBreadcrumb: true,
showSearch: true,
showToolbarActions: true,
showUserInfo: true,
}),
showBreadcrumbBar: true,
isMobile: false,
breadcrumbItems: () => [],
showFavoritesBar: true,
}) })
const emit = defineEmits(['toggle-favorites-bar']) const emit = defineEmits<{
'toggle-favorites-bar': [value: boolean]
}>()
function getBreadcrumbItem (item: unknown): AdminLayoutBreadcrumbItem | null {
if (typeof item !== 'object' || item === null) return null
const raw = (item as { raw?: unknown }).raw
if (typeof raw !== 'object' || raw === null) return null
return raw as AdminLayoutBreadcrumbItem
}
function getBreadcrumbIcon (item: unknown) {
return getBreadcrumbItem(item)?.icon
}
function getBreadcrumbTitle (item: unknown) {
return getBreadcrumbItem(item)?.title ?? ''
}
</script> </script>
@@ -28,17 +28,43 @@ v-if="favoritesConfig.showAdd" class="favorite-add" color="primary" size="small"
</v-col> </v-col>
</template> </template>
<script setup> <script setup lang="ts">
import { mdiEyeOff, mdiPlus } from '@mdi/js' import { mdiEyeOff, mdiPlus } from '@mdi/js'
defineProps({ import type { AdminLayoutFavoritesConfig, AdminLayoutFeatures, AdminLayoutMenuItem } from './types'
features: { type: Object, default: () => ({}) },
showFavoritesBar: { type: Boolean, default: true }, interface Props {
isMobile: { type: Boolean, default: false }, features?: AdminLayoutFeatures
favoritesConfig: { type: Object, default: () => ({}) }, showFavoritesBar?: boolean
favoriteItems: { type: Array, default: () => [] }, isMobile?: boolean
favoritesConfig?: AdminLayoutFavoritesConfig
favoriteItems?: AdminLayoutMenuItem[]
}
withDefaults(defineProps<Props>(), {
features: () => ({
showThemeToggle: false,
showFavorites: true,
showBreadcrumb: true,
showSearch: true,
showToolbarActions: true,
showUserInfo: true,
}),
showFavoritesBar: true,
isMobile: false,
favoritesConfig: () => ({
label: '',
addLabel: '',
showAdd: false,
}),
favoriteItems: () => [],
}) })
const emit = defineEmits(['select', 'add-favorite', 'remove-favorite', 'toggle-favorites-bar']) const emit = defineEmits<{
select: [item: AdminLayoutMenuItem]
'add-favorite': []
'remove-favorite': [item: AdminLayoutMenuItem]
'toggle-favorites-bar': [value: boolean]
}>()
</script> </script>
<style scoped> <style scoped>
@@ -117,33 +117,65 @@ v-bind="{ ...menuProps, ...tooltipProps }" :aria-label="toolbarActions.settingsL
</v-col> </v-col>
</template> </template>
<script setup> <script setup lang="ts">
import { mdiBellOutline, mdiCogOutline, mdiHelp, mdiLogout, mdiMagnify, mdiMenu, mdiMessageTextOutline, mdiPaletteOutline } from '@mdi/js' import { mdiBellOutline, mdiCogOutline, mdiHelp, mdiLogout, mdiMagnify, mdiMenu, mdiMessageTextOutline, mdiPaletteOutline } from '@mdi/js'
import { computed } from 'vue' import { computed } from 'vue'
import type { AdminLayoutActionType, AdminLayoutFeatures, AdminLayoutSearchConfig, AdminLayoutToolbarActions, AdminLayoutToolbarCounts } from './types'
const props = defineProps({ interface Props {
isMobile: { type: Boolean, default: false }, isMobile?: boolean
features: { type: Object, default: () => ({}) }, features?: AdminLayoutFeatures
searchValue: { type: String, default: '' }, searchValue?: string
searchConfig: { type: Object, default: () => ({}) }, searchConfig?: AdminLayoutSearchConfig
toolbarActions: { type: Object, default: () => ({}) }, toolbarActions?: AdminLayoutToolbarActions
toolbarCounts: { type: Object, default: () => ({}) }, toolbarCounts?: AdminLayoutToolbarCounts
logoutLabel: { type: String, default: '' }, logoutLabel?: string
themeToggleLabel: { type: String, default: '' }, themeToggleLabel?: string
showFavoritesBar: { type: Boolean, default: true }, showFavoritesBar?: boolean
showBreadcrumbBar: { type: Boolean, default: true }, showBreadcrumbBar?: boolean
}
const props = withDefaults(defineProps<Props>(), {
isMobile: false,
features: () => ({
showThemeToggle: false,
showFavorites: true,
showBreadcrumb: true,
showSearch: true,
showToolbarActions: true,
showUserInfo: true,
}),
searchValue: '',
searchConfig: () => ({
placeholder: '',
label: '',
}),
toolbarActions: () => ({
notificationsLabel: '',
messagesLabel: '',
helpLabel: '',
settingsLabel: '',
}),
toolbarCounts: () => ({
notifications: 0,
messages: 0,
}),
logoutLabel: '',
themeToggleLabel: '',
showFavoritesBar: true,
showBreadcrumbBar: true,
}) })
const emit = defineEmits([ const emit = defineEmits<{
'toggle-drawer', 'toggle-drawer': []
'update:searchValue', 'update:searchValue': [value: string]
'search', search: []
'action', action: [type: AdminLayoutActionType]
'logout', logout: []
'toggle-theme', 'toggle-theme': []
'update:showFavoritesBar', 'update:showFavoritesBar': [value: boolean]
'update:showBreadcrumbBar', 'update:showBreadcrumbBar': [value: boolean]
]) }>()
const searchValueModel = computed({ const searchValueModel = computed({
get: () => props.searchValue, get: () => props.searchValue,
@@ -95,19 +95,11 @@ v-else :link="!!subItem.path" :prepend-icon="subItem.icon || mdiMenuRight" :to="
<script setup lang="ts"> <script setup lang="ts">
import { mdiCircleSmall, mdiMenuRight } from '@mdi/js' import { mdiCircleSmall, mdiMenuRight } from '@mdi/js'
import { computed, watch } from 'vue' import { computed, watch } from 'vue'
import type { AdminLayoutMenuItem } from './types'
interface MenuItem {
title?: string
path?: string
icon?: string
navigable?: boolean
subItems?: MenuItem[]
[key: string]: unknown
}
interface Props { interface Props {
opened?: string[] opened?: string[]
menuItems?: MenuItem[] menuItems?: AdminLayoutMenuItem[]
isShrink?: boolean isShrink?: boolean
} }
@@ -119,7 +111,7 @@ const props = withDefaults(defineProps<Props>(), {
const emit = defineEmits<{ const emit = defineEmits<{
'update:opened': [value: string[]] 'update:opened': [value: string[]]
select: [item: MenuItem] select: [item: AdminLayoutMenuItem]
unshrink: [] unshrink: []
}>() }>()
@@ -139,9 +131,9 @@ watch(() => props.isShrink, (newVal) => {
} }
}) })
const isNavigable = (item: MenuItem) => item?.navigable !== false const isNavigable = (item: AdminLayoutMenuItem) => item?.navigable !== false
function emitSelect (item: MenuItem) { function emitSelect (item: AdminLayoutMenuItem) {
// 收縮狀態下點擊選單項目時,先解除收縮再進行選擇 // 收縮狀態下點擊選單項目時,先解除收縮再進行選擇
// 這樣可以讓使用者看到完整的選單結構和導航結果 // 這樣可以讓使用者看到完整的選單結構和導航結果
if (props.isShrink) { if (props.isShrink) {
@@ -150,10 +142,10 @@ function emitSelect (item: MenuItem) {
emit('select', item) emit('select', item)
} }
function getItemCount (item: MenuItem) { function getItemCount (item: AdminLayoutMenuItem) {
if (!item?.subItems?.length) return 0 if (!item?.subItems?.length) return 0
const countLeaf = (list: MenuItem[]): number => const countLeaf = (list: AdminLayoutMenuItem[]): number =>
(list || []).reduce((total: number, current: MenuItem) => { (list || []).reduce((total: number, current: AdminLayoutMenuItem) => {
if (current?.subItems?.length) return total + countLeaf(current.subItems) if (current?.subItems?.length) return total + countLeaf(current.subItems)
return total + 1 return total + 1
}, 0) }, 0)
@@ -10,15 +10,18 @@ v-for="item in favoriteItems" :key="item.path ?? item.title" class="mb-1" rounde
</v-sheet> </v-sheet>
</template> </template>
<script setup> <script setup lang="ts">
defineProps({ import type { AdminLayoutMenuItem } from './types'
favoriteItems: {
type: Array, withDefaults(defineProps<{
default: () => [], favoriteItems?: AdminLayoutMenuItem[]
}, }>(), {
favoriteItems: () => [],
}) })
const emit = defineEmits(['select']) const emit = defineEmits<{
select: [item: AdminLayoutMenuItem]
}>()
</script> </script>
<style scoped> <style scoped>
@@ -13,16 +13,19 @@ v-for="item in mobileCurrentItems" :key="item.path ?? item.title" class="mb-1" r
</v-sheet> </v-sheet>
</template> </template>
<script setup> <script setup lang="ts">
import { mdiArrowTopRight, mdiChevronRight } from '@mdi/js' import { mdiArrowTopRight, mdiChevronRight } from '@mdi/js'
defineProps({ import type { AdminLayoutMenuItem } from './types'
mobileCurrentItems: {
type: Array, withDefaults(defineProps<{
default: () => [], mobileCurrentItems?: AdminLayoutMenuItem[]
}, }>(), {
mobileCurrentItems: () => [],
}) })
const emit = defineEmits(['item-click']) const emit = defineEmits<{
'item-click': [item: AdminLayoutMenuItem]
}>()
</script> </script>
<style scoped> <style scoped>
@@ -0,0 +1,71 @@
export type AdminLayoutIcon = string
export interface AdminLayoutMenuItem {
title: string
path?: string
icon?: AdminLayoutIcon
navigable?: boolean
subItems?: AdminLayoutMenuItem[]
}
export interface AdminLayoutUserProfile {
name: string
role: string
avatarText: string
}
export interface AdminLayoutSearchConfig {
placeholder: string
label: string
}
export interface AdminLayoutToolbarActions {
notificationsLabel: string
messagesLabel: string
helpLabel: string
settingsLabel: string
}
export interface AdminLayoutToolbarCounts {
notifications: number
messages: number
}
export interface AdminLayoutFavoritesConfig {
label: string
addLabel: string
showAdd: boolean
}
export interface AdminLayoutBreadcrumbConfig {
homeLabel: string
homeDisabled: boolean
homeIcon?: AdminLayoutIcon
}
export interface AdminLayoutBreadcrumbItem {
title: string
disabled?: boolean
icon?: AdminLayoutIcon
href?: string
to?: string
}
export interface AdminLayoutFeatures {
showThemeToggle: boolean
showFavorites: boolean
showBreadcrumb: boolean
showSearch: boolean
showToolbarActions: boolean
showUserInfo: boolean
}
export interface AdminLayoutDrawerConfig {
width: number
railWidth: number
}
export type AdminLayoutActionType =
| 'notifications'
| 'messages'
| 'help'
@@ -0,0 +1,349 @@
<template>
<div class="d-flex flex-column">
<v-card variant="flat">
<v-card-title class="d-flex flex-wrap align-center py-0 ga-2">
<span class="text-h6">可編輯表格維護示範</span>
<v-chip :color="hasAnyChange ? 'warning' : 'success'" variant="tonal">
{{ hasAnyChange ? '有未儲存變更' : '已同步' }}
</v-chip>
<v-chip color="info" variant="tonal">筆數 {{ filteredStudents.length }}</v-chip>
<v-spacer />
<v-btn flat :prepend-icon="mdiMagnify" @click="isSearchVisible = !isSearchVisible">條件搜尋</v-btn>
<v-switch v-model="isBulkEditEnabled" color="primary" hide-details label="啟用編輯" />
</v-card-title>
<v-divider />
<v-card-text class="pb-0 pt-2">
<v-row v-if="isSearchVisible" class="mb-2" dense>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">學號</div>
<v-text-field
v-model="search.studentId"
clearable
density="compact"
hide-details
placeholder="例如:S2024001"
variant="outlined"
/>
</v-col>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">姓名</div>
<v-text-field
v-model="search.name"
clearable
density="compact"
hide-details
placeholder="例如:王小明"
variant="outlined"
/>
</v-col>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">系所</div>
<v-select
v-model="search.department"
:class="{ 'select-hide-arrow': !isBulkEditEnabled }"
clearable
density="compact"
hide-details
:items="departments"
variant="outlined"
/>
</v-col>
</v-row>
<v-row v-if="isBulkEditEnabled" align="center" class="mb-2 ga-1" dense>
<v-btn
:disabled="!hasSelectedRows"
:prepend-icon="mdiDelete"
variant="outlined"
@click="deleteSelectedRows"
>
批次刪除
</v-btn>
<v-spacer />
<v-btn
color="primary"
:disabled="!hasAnyChange"
:prepend-icon="mdiContentSave"
variant="outlined"
@click="saveAllRows"
>
儲存變更
</v-btn>
<v-btn
:disabled="!hasAnyChange"
:prepend-icon="mdiRestore"
variant="text"
@click="resetAllRows"
>
取消變更
</v-btn>
</v-row>
<div ref="tableContainerRef">
<v-data-table
density="comfortable"
fixed-header
:headers="tableHeaders"
:height="tableHeight"
item-value="id"
:items="filteredStudents"
:items-per-page="10"
items-per-page-text="每頁筆數"
page-text=" {0}-{1} / {2} "
>
<template #[`header.select`]>
<v-checkbox-btn
:disabled="!isBulkEditEnabled"
:indeterminate="isPartiallyVisibleSelected"
:model-value="isAllVisibleSelected"
@update:model-value="toggleSelectAll"
/>
</template>
<template #[`item.select`]="{ item }">
<v-checkbox-btn
:disabled="!isBulkEditEnabled"
:model-value="selectedRowIds.includes(item.id)"
@update:model-value="(checked) => toggleSingleRowSelection(item.id, checked)"
/>
</template>
<template #[`item.studentId`]="{ item }">
<v-text-field
:model-value="getDraftRow(item.id)?.studentId ?? ''"
density="compact"
flat
hide-details
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.studentId = String(value)
}
"
/>
</template>
<template #[`item.name`]="{ item }">
<v-text-field
:model-value="getDraftRow(item.id)?.name ?? ''"
density="compact"
flat
hide-details
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.name = String(value)
}
"
/>
</template>
<template #[`item.department`]="{ item }">
<v-select
:model-value="getDraftRow(item.id)?.department ?? ''"
:class="{ 'select-hide-arrow': !isBulkEditEnabled }"
density="compact"
flat
hide-details
:items="departments"
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.department = String(value)
}
"
/>
</template>
<template #[`item.grade`]="{ item }">
<v-select
:model-value="getDraftRow(item.id)?.grade ?? null"
:class="{ 'select-hide-arrow': !isBulkEditEnabled }"
density="compact"
flat
hide-details
item-title="title"
item-value="value"
:items="gradeOptions"
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.grade = Number(value) || 0
}
"
/>
</template>
<template #[`item.enrollYear`]="{ item }">
<v-select
:model-value="getDraftRow(item.id)?.enrollYear ?? null"
:class="{ 'select-hide-arrow': !isBulkEditEnabled }"
density="compact"
flat
hide-details
:items="enrollYears"
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.enrollYear = Number(value) || 0
}
"
/>
</template>
<template #[`item.credits`]="{ item }">
<v-text-field
:model-value="getDraftRow(item.id)?.credits ?? 0"
density="compact"
flat
hide-details
min="0"
:readonly="!isBulkEditEnabled"
type="number"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.credits = Number(value) || 0
}
"
/>
</template>
<template #[`item.advisor`]="{ item }">
<v-text-field
:model-value="getDraftRow(item.id)?.advisor ?? ''"
density="compact"
flat
hide-details
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.advisor = String(value)
}
"
/>
</template>
<template #[`item.email`]="{ item }">
<v-text-field
:model-value="getDraftRow(item.id)?.email ?? ''"
density="compact"
flat
hide-details
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.email = String(value)
}
"
/>
</template>
<template #[`item.phone`]="{ item }">
<v-text-field
:model-value="getDraftRow(item.id)?.phone ?? ''"
density="compact"
flat
hide-details
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.phone = String(value)
}
"
/>
</template>
<template #[`item.status`]="{ item }">
<v-select
:model-value="getDraftRow(item.id)?.status ?? ''"
:class="{ 'select-hide-arrow': !isBulkEditEnabled }"
density="compact"
flat
hide-details
:items="statuses"
:readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'"
@update:model-value="
(value) => {
const row = getDraftRow(item.id)
if (row) row.status = String(value)
}
"
/>
</template>
<template #[`item.actions`]="{ item }">
<div class="d-flex ga-1 justify-end">
<v-btn
color="error"
:disabled="!isBulkEditEnabled"
size="small"
variant="text"
@click="deleteSingleRow(item.id)"
>
刪除
</v-btn>
</div>
</template>
</v-data-table>
</div>
</v-card-text>
</v-card>
</div>
</template>
<script setup lang="ts">
import { mdiContentSave, mdiDelete, mdiMagnify, mdiRestore } from '@mdi/js'
import { useEditableStudentGrid } from '@/composables/maintenance/useEditableStudentGrid'
const {
departments,
draftRows,
enrollYears,
filteredStudents,
getDraftRow,
gradeOptions,
hasAnyChange,
hasSelectedRows,
isAllVisibleSelected,
isBulkEditEnabled,
isPartiallyVisibleSelected,
isSearchVisible,
saveAllRows,
search,
selectedRowIds,
statuses,
tableContainerRef,
tableHeaders,
tableHeight,
toggleSelectAll,
toggleSingleRowSelection,
deleteSelectedRows,
deleteSingleRow,
resetAllRows,
} = useEditableStudentGrid()
</script>
<style scoped>
:deep(.select-hide-arrow .v-field__append-inner) {
display: none;
}
:deep(.v-table__wrapper .v-field__input) {
padding-top: 0 !important;
padding-bottom: 0 !important;
min-height: 32px;
}
:deep(.v-data-table-footer) {
padding: 4px 0 0;
}
</style>
@@ -0,0 +1,120 @@
<template>
<common-confirm-dialog
v-model="closeVisibleModel"
confirm-color="error"
confirm-text="關閉不儲存"
message="目前有尚未儲存的內容,確定要關閉嗎?"
title="未儲存變更"
@confirm="emit('confirm-close')"
/>
<common-confirm-dialog
v-model="saveVisibleModel"
:confirm-loading="props.isSaving"
confirm-text="確認儲存"
max-width="520"
title="確認儲存變更"
@confirm="emit('confirm-save')"
>
<div v-if="props.saveSummary.length > 0" class="d-flex flex-column ga-2">
<div v-for="item in props.saveSummary" :key="item.label" class="d-flex flex-column">
<div class="text-caption text-medium-emphasis">{{ item.label }}</div>
<div v-if="item.before !== null" class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': item.before === '—' }">
{{ item.before }}
</span>
</div>
<div class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': item.after === '—' }">
{{ item.after }}
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="deleteVisibleModel"
confirm-color="error"
confirm-text="確定刪除"
:message="`確定要刪除 ${props.pendingDeleteLabel} 嗎?此操作無法復原。`"
title="確認刪除"
@confirm="emit('confirm-delete')"
/>
<common-confirm-dialog
v-model="switchVisibleModel"
confirm-text="確定切換"
max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?"
title="未儲存變更"
@confirm="emit('confirm-switch')"
/>
<common-confirm-dialog
v-model="navigateVisibleModel"
confirm-text="確定切換"
max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?"
title="未儲存變更"
@confirm="emit('confirm-navigate')"
/>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { SaveSummaryItem } from '@/composables/maintenance/useStudentMaintenanceForm'
import CommonConfirmDialog from './CommonConfirmDialog.vue'
const props = defineProps<{
closeVisible: boolean
deleteVisible: boolean
isSaving: boolean
navigateVisible: boolean
pendingDeleteLabel: string
saveSummary: SaveSummaryItem[]
saveVisible: boolean
switchVisible: boolean
}>()
const emit = defineEmits<{
(event: 'confirm-close'): void
(event: 'confirm-delete'): void
(event: 'confirm-navigate'): void
(event: 'confirm-save'): void
(event: 'confirm-switch'): void
(event: 'update:close-visible', value: boolean): void
(event: 'update:delete-visible', value: boolean): void
(event: 'update:navigate-visible', value: boolean): void
(event: 'update:save-visible', value: boolean): void
(event: 'update:switch-visible', value: boolean): void
}>()
const closeVisibleModel = computed({
get: () => props.closeVisible,
set: (value: boolean) => emit('update:close-visible', value),
})
const saveVisibleModel = computed({
get: () => props.saveVisible,
set: (value: boolean) => emit('update:save-visible', value),
})
const deleteVisibleModel = computed({
get: () => props.deleteVisible,
set: (value: boolean) => emit('update:delete-visible', value),
})
const switchVisibleModel = computed({
get: () => props.switchVisible,
set: (value: boolean) => emit('update:switch-visible', value),
})
const navigateVisibleModel = computed({
get: () => props.navigateVisible,
set: (value: boolean) => emit('update:navigate-visible', value),
})
</script>
@@ -0,0 +1,127 @@
<template>
<v-row dense>
<v-col cols="12" md="3">
<v-text-field
id="field-studentId"
v-model="props.form.studentId"
density="comfortable"
:disabled="props.isFormLocked"
:error-messages="props.fieldErrors.studentId"
label="學號"
placeholder="例如:S2024008"
:readonly="props.isFormReadonly"
variant="outlined"
@update:model-value="emit('clear-field', 'studentId')"
/>
</v-col>
<v-col cols="12" md="3">
<v-text-field
id="field-name"
v-model="props.form.name"
density="comfortable"
:disabled="props.isFormLocked"
:error-messages="props.fieldErrors.name"
label="姓名"
placeholder="例如:陳怡君"
:readonly="props.isFormReadonly"
variant="outlined"
@update:model-value="emit('clear-field', 'name')"
/>
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-department"
v-model="props.form.department"
density="comfortable"
:disabled="props.isFormLocked"
:error-messages="props.fieldErrors.department"
:items="props.departments"
label="系所"
:readonly="props.isFormReadonly"
variant="outlined"
@update:model-value="emit('clear-field', 'department')"
/>
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-grade"
v-model="props.form.grade"
density="comfortable"
:disabled="props.isFormLocked"
:error-messages="props.fieldErrors.grade"
item-title="title"
item-value="value"
:items="props.gradeOptions"
label="年級"
:readonly="props.isFormReadonly"
variant="outlined"
@update:model-value="emit('clear-field', 'grade')"
/>
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-enrollYear"
v-model="props.form.enrollYear"
density="comfortable"
:disabled="props.isFormLocked"
:error-messages="props.fieldErrors.enrollYear"
:items="props.enrollYears"
label="入學年度"
:readonly="props.isFormReadonly"
variant="outlined"
@update:model-value="emit('clear-field', 'enrollYear')"
/>
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-status"
v-model="props.form.status"
density="comfortable"
:disabled="props.isFormLocked"
:error-messages="props.fieldErrors.status"
:items="props.statuses"
label="狀態"
:readonly="props.isFormReadonly"
variant="outlined"
@update:model-value="emit('clear-field', 'status')"
/>
</v-col>
<v-col cols="12" md="3">
<v-text-field
id="field-email"
v-model="props.form.email"
density="comfortable"
:disabled="props.isFormLocked"
:error-messages="props.fieldErrors.email"
label="Email"
:readonly="props.isFormReadonly"
variant="outlined"
@update:model-value="emit('clear-field', 'email')"
/>
</v-col>
</v-row>
</template>
<script setup lang="ts">
import type { StudentFormState } from '@/composables/maintenance/useStudentMaintenanceForm'
interface GradeOption {
title: string
value: number
}
const props = defineProps<{
departments: string[]
enrollYears: number[]
fieldErrors: Record<string, string[]>
form: StudentFormState
gradeOptions: GradeOption[]
isFormLocked: boolean
isFormReadonly: boolean
statuses: string[]
}>()
const emit = defineEmits<{
(event: 'clear-field', field: keyof StudentFormState): void
}>()
</script>
@@ -27,7 +27,12 @@
</div> </div>
<template v-if="isViewMode"> <template v-if="isViewMode">
<v-card v-for="course in semester.courses" :key="course.code" class="pa-3" variant="outlined"> <v-card
v-for="course in semester.courses"
:key="course.code"
class="pa-3"
variant="outlined"
>
<div class="d-flex align-start justify-space-between ga-3"> <div class="d-flex align-start justify-space-between ga-3">
<div> <div>
<div class="text-body-1 font-weight-medium">{{ course.name }}</div> <div class="text-body-1 font-weight-medium">{{ course.name }}</div>
@@ -42,7 +47,10 @@
</div> </div>
</v-card> </v-card>
<div v-if="semester.courses.length === 0" class="text-center text-medium-emphasis py-6 border border-dashed rounded"> <div
v-if="semester.courses.length === 0"
class="text-center text-medium-emphasis py-6 border border-dashed rounded"
>
尚無課程資料 尚無課程資料
</div> </div>
</template> </template>
@@ -55,7 +63,7 @@
label="學期名稱" label="學期名稱"
:model-value="semester.semesterName" :model-value="semester.semesterName"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-semester', semester.id, { semesterName: String(value) })" @update:model-value="(value) => updateSemester({ semesterName: String(value) })"
/> />
<v-text-field <v-text-field
@@ -66,7 +74,7 @@
:model-value="semester.rank" :model-value="semester.rank"
type="number" type="number"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-semester', semester.id, { rank: Number(value) || 0 })" @update:model-value="(value) => updateSemester({ rank: Number(value) || 0 })"
/> />
<v-text-field <v-text-field
@@ -93,7 +101,12 @@
</v-btn> </v-btn>
</div> </div>
<v-card v-for="(course, idx) in semester.courses" :key="`${course.code}-${idx}`" class="pa-3" variant="outlined"> <v-card
v-for="(course, idx) in semester.courses"
:key="`${course.code}-${idx}`"
class="pa-3"
variant="outlined"
>
<div class="d-flex align-center mb-3"> <div class="d-flex align-center mb-3">
<div class="text-subtitle-2 font-weight-bold">課程 {{ idx + 1 }}</div> <div class="text-subtitle-2 font-weight-bold">課程 {{ idx + 1 }}</div>
<v-spacer /> <v-spacer />
@@ -115,7 +128,7 @@
label="課程名稱" label="課程名稱"
:model-value="course.name" :model-value="course.name"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-course', semester.id, idx, { name: String(value) })" @update:model-value="(value) => updateCourse(idx, { name: String(value) })"
/> />
<v-text-field <v-text-field
density="comfortable" density="comfortable"
@@ -124,7 +137,7 @@
label="代碼" label="代碼"
:model-value="course.code" :model-value="course.code"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-course', semester.id, idx, { code: String(value) })" @update:model-value="(value) => updateCourse(idx, { code: String(value) })"
/> />
<v-text-field <v-text-field
density="comfortable" density="comfortable"
@@ -134,7 +147,7 @@
:model-value="course.credits" :model-value="course.credits"
type="number" type="number"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-course', semester.id, idx, { credits: Number(value) || 0 })" @update:model-value="(value) => updateCourse(idx, { credits: Number(value) || 0 })"
/> />
<v-text-field <v-text-field
density="comfortable" density="comfortable"
@@ -144,12 +157,15 @@
:model-value="course.score" :model-value="course.score"
type="number" type="number"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-course', semester.id, idx, { score: Number(value) || 0 })" @update:model-value="(value) => updateCourse(idx, { score: Number(value) || 0 })"
/> />
</div> </div>
</v-card> </v-card>
<div v-if="semester.courses.length === 0" class="text-center text-medium-emphasis py-6 border border-dashed rounded"> <div
v-if="semester.courses.length === 0"
class="text-center text-medium-emphasis py-6 border border-dashed rounded"
>
尚無課程資料 尚無課程資料
</div> </div>
</template> </template>
@@ -159,9 +175,8 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { mdiArrowLeft, mdiDelete, mdiPlus } from '@mdi/js'
import type { CourseRecord, SemesterRecord } from '@/stores/semesters' import type { CourseRecord, SemesterRecord } from '@/stores/semesters'
import { mdiArrowLeft, mdiDelete, mdiPlus } from '@mdi/js'
import { computed } from 'vue' import { computed } from 'vue'
const props = defineProps<{ const props = defineProps<{
@@ -170,15 +185,30 @@ const props = defineProps<{
isFormLocked: boolean isFormLocked: boolean
}>() }>()
defineEmits<{ const emit = defineEmits<{
(event: 'close'): void (event: 'close'): void
(event: 'add-course', semesterId: number): void (event: 'add-course', semesterId: number): void
(event: 'update-semester', semesterId: number, payload: Partial<SemesterRecord>): void (event: 'update-semester', semesterId: number, payload: Partial<SemesterRecord>): void
(event: 'update-course', semesterId: number, courseIndex: number, payload: Partial<CourseRecord>): void (
event: 'update-course',
semesterId: number,
courseIndex: number,
payload: Partial<CourseRecord>
): void
(event: 'delete-course', semesterId: number, courseIndex: number, courseName: string): void (event: 'delete-course', semesterId: number, courseIndex: number, courseName: string): void
}>() }>()
const totalCredits = computed(() => const totalCredits = computed(
props.semester?.courses.reduce((sum, course) => sum + course.credits, 0) ?? 0, () => props.semester?.courses.reduce((sum, course) => sum + course.credits, 0) ?? 0
) )
function updateSemester (payload: Partial<SemesterRecord>) {
if (!props.semester) return
emit('update-semester', props.semester.id, payload)
}
function updateCourse (courseIndex: number, payload: Partial<CourseRecord>) {
if (!props.semester) return
emit('update-course', props.semester.id, courseIndex, payload)
}
</script> </script>
@@ -29,7 +29,9 @@
<div class="d-flex align-center"> <div class="d-flex align-center">
<div> <div>
<div class="text-subtitle-2 font-weight-bold">課程列表</div> <div class="text-subtitle-2 font-weight-bold">課程列表</div>
<div class="text-caption text-medium-emphasis">手機版改用卡片式維護不使用扁平表格</div> <div class="text-caption text-medium-emphasis">
手機版改用卡片式維護不使用扁平表格
</div>
</div> </div>
<v-spacer /> <v-spacer />
<v-btn <v-btn
@@ -46,14 +48,23 @@
</div> </div>
<template v-if="semester.courses.length > 0"> <template v-if="semester.courses.length > 0">
<v-card v-for="(course, idx) in semester.courses" :key="`${course.code}-${idx}`" class="pa-3" variant="outlined"> <v-card
v-for="(course, idx) in semester.courses"
:key="`${course.code}-${idx}`"
class="pa-3"
variant="outlined"
>
<template v-if="isViewMode"> <template v-if="isViewMode">
<div class="d-flex align-start justify-space-between ga-3"> <div class="d-flex align-start justify-space-between ga-3">
<div> <div>
<div class="text-body-1 font-weight-medium">{{ course.name }}</div> <div class="text-body-1 font-weight-medium">{{ course.name }}</div>
<div class="text-caption text-medium-emphasis">{{ course.code }}</div> <div class="text-caption text-medium-emphasis">{{ course.code }}</div>
</div> </div>
<v-chip :color="course.score < 60 ? 'error' : 'success'" size="small" variant="tonal"> <v-chip
:color="course.score < 60 ? 'error' : 'success'"
size="small"
variant="tonal"
>
{{ course.score }} {{ course.score }}
</v-chip> </v-chip>
</div> </div>
@@ -84,7 +95,7 @@
label="課程名稱" label="課程名稱"
:model-value="course.name" :model-value="course.name"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-course', semester.id, idx, { name: String(value) })" @update:model-value="(value) => updateCourse(idx, { name: String(value) })"
/> />
<v-text-field <v-text-field
density="comfortable" density="comfortable"
@@ -93,7 +104,7 @@
label="代碼" label="代碼"
:model-value="course.code" :model-value="course.code"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-course', semester.id, idx, { code: String(value) })" @update:model-value="(value) => updateCourse(idx, { code: String(value) })"
/> />
<v-text-field <v-text-field
density="comfortable" density="comfortable"
@@ -103,7 +114,7 @@
:model-value="course.credits" :model-value="course.credits"
type="number" type="number"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-course', semester.id, idx, { credits: Number(value) || 0 })" @update:model-value="(value) => updateCourse(idx, { credits: Number(value) || 0 })"
/> />
<v-text-field <v-text-field
density="comfortable" density="comfortable"
@@ -113,7 +124,7 @@
:model-value="course.score" :model-value="course.score"
type="number" type="number"
variant="outlined" variant="outlined"
@update:model-value="(value) => $emit('update-course', semester.id, idx, { score: Number(value) || 0 })" @update:model-value="(value) => updateCourse(idx, { score: Number(value) || 0 })"
/> />
</div> </div>
</template> </template>
@@ -129,9 +140,8 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { mdiArrowLeft, mdiDelete, mdiPlus } from '@mdi/js'
import type { CourseRecord, SemesterRecord } from '@/stores/semesters' import type { CourseRecord, SemesterRecord } from '@/stores/semesters'
import { mdiArrowLeft, mdiDelete, mdiPlus } from '@mdi/js'
import { computed } from 'vue' import { computed } from 'vue'
const props = defineProps<{ const props = defineProps<{
@@ -140,14 +150,24 @@ const props = defineProps<{
isFormLocked: boolean isFormLocked: boolean
}>() }>()
defineEmits<{ const emit = defineEmits<{
(event: 'close'): void (event: 'close'): void
(event: 'add-course', semesterId: number): void (event: 'add-course', semesterId: number): void
(event: 'update-course', semesterId: number, courseIndex: number, payload: Partial<CourseRecord>): void (
event: 'update-course',
semesterId: number,
courseIndex: number,
payload: Partial<CourseRecord>
): void
(event: 'delete-course', semesterId: number, courseIndex: number): void (event: 'delete-course', semesterId: number, courseIndex: number): void
}>() }>()
const totalCredits = computed(() => const totalCredits = computed(
props.semester?.courses.reduce((sum, course) => sum + course.credits, 0) ?? 0, () => props.semester?.courses.reduce((sum, course) => sum + course.credits, 0) ?? 0
) )
function updateCourse (courseIndex: number, payload: Partial<CourseRecord>) {
if (!props.semester) return
emit('update-course', props.semester.id, courseIndex, payload)
}
</script> </script>
@@ -0,0 +1,211 @@
import { computed, onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
import type { AdminLayoutMenuItem } from '@/components/layouts/sk-admin-layout/types'
type ToggleSidebarPayload = {
drawer: boolean
rail: boolean
}
type UseAdminLayoutStateOptions = {
appBarRef: Ref<unknown>
breadcrumbBarVisible: boolean | null
emitUpdateBreadcrumbBarVisible: (value: boolean) => void
emitUpdateFavoritesBarVisible: (value: boolean) => void
emitUpdateIsRail: (value: boolean) => void
favoritesBarVisible: boolean | null
isMobile: Ref<boolean>
isRail: boolean | null
menuItems: AdminLayoutMenuItem[]
onToggleSidebar: (payload: ToggleSidebarPayload) => void
}
export function useAdminLayoutState (options: UseAdminLayoutStateOptions) {
const drawer = ref(true)
const mobileFavoritesPanel = ref(false)
const mobileMenuPath = ref<AdminLayoutMenuItem[]>([])
const localBreadcrumbBarVisible = ref(true)
const localFavoritesBarVisible = ref(true)
const localIsRail = ref(false)
const opened = ref<string[]>([])
const appBarHeight = ref(0)
const isRail = computed({
get: () => (options.isRail ?? localIsRail.value),
set: (value: boolean) => {
if (options.isRail === null) {
localIsRail.value = value
return
}
options.emitUpdateIsRail(value)
},
})
const showFavoritesBar = computed({
get: () => (options.favoritesBarVisible ?? localFavoritesBarVisible.value),
set: (value: boolean) => {
if (options.favoritesBarVisible === null) {
localFavoritesBarVisible.value = value
return
}
options.emitUpdateFavoritesBarVisible(value)
},
})
const showBreadcrumbBar = computed({
get: () => (options.breadcrumbBarVisible ?? localBreadcrumbBarVisible.value),
set: (value: boolean) => {
if (options.breadcrumbBarVisible === null) {
localBreadcrumbBarVisible.value = value
return
}
options.emitUpdateBreadcrumbBarVisible(value)
},
})
const mobileCurrentItems = computed(() =>
mobileMenuPath.value.reduce(
(items, currentItem) => currentItem?.subItems ?? [],
options.menuItems || []
)
)
const mobileCurrentLevel = computed(() => mobileMenuPath.value.length + 1)
const mobileMenuLevels = computed(() =>
Array.from({ length: mobileCurrentLevel.value }, (_, index) => ({
level: index + 1,
title: index === 0 ? '主選單' : (mobileMenuPath.value[index - 1]?.title ?? `${index + 1}`),
}))
)
function resetMobilePanels () {
mobileFavoritesPanel.value = false
mobileMenuPath.value = []
}
function toggleSidebar () {
if (options.isMobile.value) {
drawer.value = !drawer.value
} else {
isRail.value = !isRail.value
}
options.onToggleSidebar({
drawer: drawer.value,
rail: isRail.value,
})
}
function goToMobileLevel (level: number) {
mobileFavoritesPanel.value = false
mobileMenuPath.value = mobileMenuPath.value.slice(0, Math.max(0, level - 1))
}
function openMobileFavoritesPanel () {
mobileMenuPath.value = []
mobileFavoritesPanel.value = true
}
function handleMobileMenuClick (
item: AdminLayoutMenuItem,
onSelect: (selectedItem: AdminLayoutMenuItem) => void
) {
if (item?.subItems?.length) {
mobileMenuPath.value = [...mobileMenuPath.value, item]
return
}
onSelect(item)
}
function handleSelectFavorite (
item: AdminLayoutMenuItem,
onSelect: (selectedItem: AdminLayoutMenuItem) => void
) {
onSelect(item)
mobileFavoritesPanel.value = false
}
function toggleFavoritesBar (nextValue?: boolean) {
showFavoritesBar.value =
typeof nextValue === 'boolean' ? nextValue : !showFavoritesBar.value
}
function handleUnshrink () {
isRail.value = false
}
let appBarObserver: ResizeObserver | null = null
function resolveObservedElement () {
const target = options.appBarRef.value as HTMLElement | { $el?: HTMLElement } | null
if (!target) return null
if (target instanceof HTMLElement) return target
return target.$el ?? null
}
function updateAppBarHeight () {
const el = resolveObservedElement()
if (!el) return
appBarHeight.value = Math.round(el.getBoundingClientRect().height || 0)
}
onMounted(() => {
updateAppBarHeight()
if (typeof ResizeObserver === 'undefined') return
const el = resolveObservedElement()
if (!el) return
appBarObserver = new ResizeObserver(() => updateAppBarHeight())
appBarObserver.observe(el)
})
onBeforeUnmount(() => {
if (!appBarObserver) return
appBarObserver.disconnect()
appBarObserver = null
})
watch(options.isMobile, (value) => {
if (!value) {
resetMobilePanels()
}
})
watch(drawer, (value) => {
if (!value) {
resetMobilePanels()
}
})
const mainStyle = computed(() => ({
paddingTop: appBarHeight.value ? `${appBarHeight.value}px` : undefined,
height: '100vh',
minHeight: 0,
flex: '1 1 0',
}))
return {
drawer,
goToMobileLevel,
handleMobileMenuClick,
handleSelectFavorite,
handleUnshrink,
isRail,
mainStyle,
mobileCurrentItems,
mobileCurrentLevel,
mobileFavoritesPanel,
mobileMenuLevels,
openMobileFavoritesPanel,
opened,
showBreadcrumbBar,
showFavoritesBar,
toggleFavoritesBar,
toggleSidebar,
}
}
+28
View File
@@ -0,0 +1,28 @@
import { computed } from 'vue'
import { useTheme } from 'vuetify'
import { getNextThemeName } from '@/utils/theme'
export function useThemeToggle () {
const theme = useTheme()
const availableThemeNames = computed(() =>
Object.keys(theme.themes.value ?? {}).filter((name) => name.startsWith('theme'))
)
function toggleTheme () {
const names = availableThemeNames.value
if (names.length === 0) return null
const current = theme.global.name.value
const next = getNextThemeName(names, current)
if (!next) return null
theme.change(next)
return next
}
return {
availableThemeNames,
toggleTheme,
}
}
@@ -0,0 +1,267 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { type StudentRecord, useStudentStore } from '@/stores/students'
type StudentPayload = Omit<StudentRecord, 'id'>
const departments = ['資訊工程', '企業管理', '應用外語', '視覺設計', '財務金融']
const gradeOptions = [
{ title: '大一', value: 1 },
{ title: '大二', value: 2 },
{ title: '大三', value: 3 },
{ title: '大四', value: 4 },
{ title: '研究所', value: 5 },
]
const enrollYears = [2024, 2023, 2022, 2021, 2020, 2019]
const statuses = ['在學', '休學', '畢業']
const tableHeaders = [
{ title: '', key: 'select', sortable: false, nowrap: true },
{ title: '學號', key: 'studentId', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '姓名', key: 'name', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '系所', key: 'department', sortable: true, minWidth: 140, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '年級', key: 'grade', sortable: true, minWidth: 140, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '入學年度', key: 'enrollYear', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '已修學分', key: 'credits', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '指導老師', key: 'advisor', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: 'Email', key: 'email', sortable: true, minWidth: 200, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '電話', key: 'phone', sortable: true, minWidth: 150, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '狀態', key: 'status', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '操作', key: 'actions', sortable: false, width: 'auto', nowrap: true, cellProps: { class: 'bg-background' } },
] as const
const TABLE_BOTTOM_GAP = 64
const TABLE_MIN_HEIGHT = 240
export function useEditableStudentGrid () {
const studentStore = useStudentStore()
const students = computed(() => studentStore.students)
const search = ref({
studentId: '',
name: '',
department: '',
})
const isBulkEditEnabled = ref(false)
const isSearchVisible = ref(false)
const tableContainerRef = ref<HTMLElement | null>(null)
const tableScrollParentRef = ref<HTMLElement | null>(null)
const tableResizeObserver = ref<ResizeObserver | null>(null)
const tableHeight = ref(300)
const draftRows = ref<Record<number, StudentPayload>>({})
const selectedRowIds = ref<number[]>([])
function toPayload (student: StudentRecord): StudentPayload {
return {
studentId: student.studentId,
name: student.name,
department: student.department,
grade: student.grade,
enrollYear: student.enrollYear,
credits: student.credits,
advisor: student.advisor,
email: student.email,
phone: student.phone,
status: student.status,
}
}
function rebuildDraftRows () {
draftRows.value = Object.fromEntries(students.value.map((item) => [item.id, toPayload(item)]))
}
function getDraftRow (id: number) {
return draftRows.value[id] ?? null
}
const getSourceRow = (id: number) => students.value.find((item) => item.id === id) || null
function isRowDirty (id: number) {
const source = getSourceRow(id)
const draft = getDraftRow(id)
if (!source || !draft) return false
return (
source.studentId !== draft.studentId ||
source.name !== draft.name ||
source.department !== draft.department ||
source.grade !== draft.grade ||
source.enrollYear !== draft.enrollYear ||
source.credits !== draft.credits ||
source.advisor !== draft.advisor ||
source.email !== draft.email ||
source.phone !== draft.phone ||
source.status !== draft.status
)
}
const filteredStudents = computed(() => {
const keywordStudentId = search.value.studentId.trim().toLowerCase()
const keywordName = search.value.name.trim().toLowerCase()
const selectedDepartment = search.value.department
return students.value.filter((item) => {
if (studentStore.isMarkedAsDeleted(item.id)) return false
const matchesStudentId = keywordStudentId
? item.studentId.toLowerCase().includes(keywordStudentId)
: true
const matchesName = keywordName ? item.name.toLowerCase().includes(keywordName) : true
const matchesDepartment = selectedDepartment ? item.department === selectedDepartment : true
return matchesStudentId && matchesName && matchesDepartment
})
})
const visibleStudentIds = computed(() => filteredStudents.value.map((item) => item.id))
const isAllVisibleSelected = computed(() =>
visibleStudentIds.value.length > 0 &&
visibleStudentIds.value.every((id) => selectedRowIds.value.includes(id))
)
const isPartiallyVisibleSelected = computed(() =>
visibleStudentIds.value.some((id) => selectedRowIds.value.includes(id)) &&
!isAllVisibleSelected.value
)
const hasAnyChange = computed(() =>
students.value.some((item) => isRowDirty(item.id)) || studentStore.deletedIds.size > 0
)
const hasSelectedRows = computed(() => selectedRowIds.value.length > 0)
function toggleSelectAll (checked: boolean | null) {
if (isPartiallyVisibleSelected.value) {
selectedRowIds.value = selectedRowIds.value.filter((id) => !visibleStudentIds.value.includes(id))
return
}
if (!checked) {
selectedRowIds.value = selectedRowIds.value.filter((id) => !visibleStudentIds.value.includes(id))
return
}
selectedRowIds.value = Array.from(new Set([...selectedRowIds.value, ...visibleStudentIds.value]))
}
function toggleSingleRowSelection (id: number, checked: boolean | null) {
if (checked) {
if (!selectedRowIds.value.includes(id)) {
selectedRowIds.value = [...selectedRowIds.value, id]
}
return
}
selectedRowIds.value = selectedRowIds.value.filter((selectedId) => selectedId !== id)
}
function deleteSingleRow (id: number) {
selectedRowIds.value = selectedRowIds.value.filter((selectedId) => selectedId !== id)
studentStore.markAsDeleted(id)
rebuildDraftRows()
}
function deleteSelectedRows () {
if (selectedRowIds.value.length === 0) return
for (const id of selectedRowIds.value) {
studentStore.markAsDeleted(id)
}
selectedRowIds.value = []
rebuildDraftRows()
}
function saveAllRows () {
for (const item of students.value) {
const draft = getDraftRow(item.id)
if (!draft) continue
if (!isRowDirty(item.id)) continue
studentStore.updateStudent(item.id, draft)
}
studentStore.commitDeleted()
rebuildDraftRows()
}
function resetAllRows () {
studentStore.restoreDeleted()
selectedRowIds.value = []
rebuildDraftRows()
}
function recalculateTableHeight () {
const container = tableContainerRef.value
if (!container) return
const scrollParent = tableScrollParentRef.value || (container.closest('.overflow-auto') as HTMLElement | null)
tableScrollParentRef.value = scrollParent
const parentBottom = scrollParent
? scrollParent.getBoundingClientRect().bottom
: window.innerHeight
const top = container.getBoundingClientRect().top
const availableHeight = parentBottom - top - TABLE_BOTTOM_GAP
tableHeight.value = Math.max(TABLE_MIN_HEIGHT, Math.floor(availableHeight))
}
watch(students, () => {
const currentIds = new Set(students.value.map((item) => item.id))
selectedRowIds.value = selectedRowIds.value.filter((id) => currentIds.has(id))
})
watch(students, rebuildDraftRows, { immediate: true })
watch([isSearchVisible, isBulkEditEnabled], async () => {
await nextTick()
requestAnimationFrame(() => {
recalculateTableHeight()
})
})
onMounted(() => {
const container = tableContainerRef.value
if (container) {
tableScrollParentRef.value = container.closest('.overflow-auto') as HTMLElement | null
tableResizeObserver.value = new ResizeObserver(() => {
recalculateTableHeight()
})
tableResizeObserver.value.observe(container)
if (tableScrollParentRef.value) {
tableResizeObserver.value.observe(tableScrollParentRef.value)
}
}
requestAnimationFrame(() => {
recalculateTableHeight()
})
window.addEventListener('resize', recalculateTableHeight)
})
onBeforeUnmount(() => {
tableResizeObserver.value?.disconnect()
window.removeEventListener('resize', recalculateTableHeight)
})
return {
departments,
draftRows,
enrollYears,
filteredStudents,
getDraftRow,
gradeOptions,
hasAnyChange,
hasSelectedRows,
isAllVisibleSelected,
isBulkEditEnabled,
isPartiallyVisibleSelected,
isSearchVisible,
saveAllRows,
search,
selectedRowIds,
statuses,
tableContainerRef,
tableHeaders,
tableHeight,
toggleSelectAll,
toggleSingleRowSelection,
deleteSelectedRows,
deleteSingleRow,
resetAllRows,
}
}
@@ -0,0 +1,245 @@
import { computed, ref, type ComputedRef, type Ref } from 'vue'
type DialogMode = 'create' | 'edit' | 'view'
interface UseMaintenanceCrudFlowOptions<T extends { id: number }> {
records: ComputedRef<T[]>
editingId: Ref<number | null>
dialogMode: Ref<DialogMode>
dialogVisible: Ref<boolean>
isLoading: Ref<boolean>
isSaving: Ref<boolean>
isDirty: Readonly<Ref<boolean>> | ComputedRef<boolean>
clearAllErrors: () => void
resetForm: () => void
openEditDialog: (record: T) => void
openViewDialog: (record: T) => void
removeRecord: (id: number) => void
describeRecord: (record: T) => string
onCloseReset?: () => void
onAfterDelete?: (deletedId: number) => void
}
interface UseMaintenanceCrudFlowResult<T extends { id: number }> {
confirmCloseVisible: Ref<boolean>
confirmSaveVisible: Ref<boolean>
confirmDeleteVisible: Ref<boolean>
confirmSwitchVisible: Ref<boolean>
confirmNavigateVisible: Ref<boolean>
pendingDelete: Ref<T | null>
pendingDeleteLabel: ComputedRef<string>
currentRecordIndex: ComputedRef<number>
currentEditingRecord: ComputedRef<T | null>
hasPrevRecord: ComputedRef<boolean>
hasNextRecord: ComputedRef<boolean>
isEditMode: ComputedRef<boolean>
isViewMode: ComputedRef<boolean>
openAdjacentRecord: (direction: 'prev' | 'next') => void
openEdgeRecord: (position: 'first' | 'last') => void
switchToEditMode: () => void
switchToViewMode: () => void
confirmSwitch: () => void
confirmNavigate: () => void
requestDeleteConfirmation: (record: T) => void
requestDeleteCurrent: () => void
confirmDelete: () => void
requestCloseDialog: () => void
confirmClose: () => void
closeDialog: () => void
handleDialogVisibility: (nextValue: boolean) => void
}
export function useMaintenanceCrudFlow<T extends { id: number }> (
options: UseMaintenanceCrudFlowOptions<T>,
): UseMaintenanceCrudFlowResult<T> {
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
const pendingDelete = ref<T | null>(null) as Ref<T | null>
const pendingSwitchTarget = ref<T | null>(null)
const pendingNavigateTarget = ref<T | null>(null)
const isEditMode = computed(() => options.dialogMode.value === 'edit')
const isViewMode = computed(() => options.dialogMode.value === 'view')
const currentRecordIndex = computed(() =>
options.records.value.findIndex((item) => item.id === options.editingId.value),
)
const currentEditingRecord = computed(
() => options.records.value.find((item) => item.id === options.editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() =>
currentRecordIndex.value >= 0
&& currentRecordIndex.value < options.records.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return options.describeRecord(pendingDelete.value)
})
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = options.records.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (options.isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
options.openEditDialog(target)
return
}
options.openViewDialog(target)
}
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (options.records.value.length === 0) return
const target = position === 'first' ? options.records.value[0] : options.records.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (options.isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
options.openEditDialog(target)
return
}
options.openViewDialog(target)
}
function switchToEditMode () {
if (!isViewMode.value) return
const current = currentEditingRecord.value
if (!current) return
options.openEditDialog(current)
}
function switchToViewMode () {
if (!isEditMode.value) return
const current = currentEditingRecord.value
if (!current) return
if (options.isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
options.openViewDialog(current)
}
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
options.openViewDialog(target)
}
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
options.openEditDialog(target)
}
function requestDeleteConfirmation (record: T) {
pendingDelete.value = record
confirmDeleteVisible.value = true
}
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
function closeDialog () {
options.dialogVisible.value = false
options.isLoading.value = false
options.isSaving.value = false
confirmCloseVisible.value = false
confirmSaveVisible.value = false
confirmDeleteVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
pendingDelete.value = null
pendingSwitchTarget.value = null
pendingNavigateTarget.value = null
options.dialogMode.value = 'create'
options.editingId.value = null
options.clearAllErrors()
options.resetForm()
options.onCloseReset?.()
}
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
options.removeRecord(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
options.onAfterDelete?.(deletedId)
if (options.editingId.value === deletedId) {
closeDialog()
}
}
function requestCloseDialog () {
if (options.isDirty.value && !options.isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
options.dialogVisible.value = true
return
}
requestCloseDialog()
}
return {
confirmCloseVisible,
confirmSaveVisible,
confirmDeleteVisible,
confirmSwitchVisible,
confirmNavigateVisible,
pendingDelete,
pendingDeleteLabel,
currentRecordIndex,
currentEditingRecord,
hasPrevRecord,
hasNextRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
switchToEditMode,
switchToViewMode,
confirmSwitch,
confirmNavigate,
requestDeleteConfirmation,
requestDeleteCurrent,
confirmDelete,
requestCloseDialog,
confirmClose,
closeDialog,
handleDialogVisibility,
}
}
@@ -0,0 +1,228 @@
import { computed, ref, type ComputedRef, type Ref } from 'vue'
import type { StudentRecord } from '@/stores/students'
interface GradeOption {
title: string
value: number
}
interface StudentFormState {
studentId: string
name: string
department: string
grade: number
enrollYear: number
credits: number
advisor: string
email: string
phone: string
status: string
}
interface UseStudentMaintenanceFormOptions {
departments: string[]
gradeOptions: GradeOption[]
enrollYears: number[]
statuses: string[]
students: ComputedRef<StudentRecord[]>
editingId: Ref<number | null>
highlightedId: Ref<number | null>
}
type SaveSummaryItem = {
key: string
label: string
before: string | null
after: string
}
const fieldLabels: Record<keyof StudentFormState, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
function createDefaultForm (
departments: string[],
gradeOptions: GradeOption[],
enrollYears: number[],
statuses: string[],
): StudentFormState {
return {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
}
function createEmptyFieldErrors () {
return {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
} as Record<keyof StudentFormState, string[]>
}
export function useStudentMaintenanceForm (options: UseStudentMaintenanceFormOptions) {
const form = ref<StudentFormState>(
createDefaultForm(options.departments, options.gradeOptions, options.enrollYears, options.statuses),
)
const initialForm = ref<StudentFormState>({ ...form.value })
const fieldErrors = ref(createEmptyFieldErrors())
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
function gradeLabel (grade: number) {
return options.gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
const saveSummary = computed<SaveSummaryItem[]>(() => {
const before = initialForm.value
const after = form.value
const entries = Object.keys(fieldLabels).map((key) => {
const fieldKey = key as keyof StudentFormState
return {
key,
label: fieldLabels[fieldKey],
before: options.editingId.value ? formatSummaryValue(key, before[fieldKey]) : null,
after: formatSummaryValue(key, after[fieldKey]),
}
})
if (!options.editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function setForm (nextForm: StudentFormState) {
form.value = { ...nextForm }
}
function syncInitialForm () {
initialForm.value = { ...form.value }
}
function resetForm () {
form.value = createDefaultForm(
options.departments,
options.gradeOptions,
options.enrollYears,
options.statuses,
)
syncInitialForm()
clearAllErrors()
}
function clearAllErrors () {
fieldErrors.value = createEmptyFieldErrors()
}
function clearFieldError (field: keyof StudentFormState | string) {
if (!fieldErrors.value[field as keyof StudentFormState]?.length) return
fieldErrors.value[field as keyof StudentFormState] = []
}
function validateForm () {
const errors: Array<{ field: keyof StudentFormState; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = options.students.value.find(
(item) => item.studentId === studentId && item.id !== options.editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === options.highlightedId.value ? 'is-highlighted' : '',
}
}
const isPlaceholderValue = (value: string | null) => value === '—'
return {
errorSummary,
fieldErrors,
form,
initialForm,
isDirty,
isPlaceholderValue,
saveSummary,
clearAllErrors,
clearFieldError,
formatSummaryValue,
gradeLabel,
resetForm,
rowProps,
setForm,
statusColor,
syncInitialForm,
validateForm,
}
}
export type { StudentFormState, SaveSummaryItem }
+12 -4
View File
@@ -1,4 +1,4 @@
import { ref } from 'vue' import { ref, type Ref } from 'vue'
import { type ApiRequestError, normalizeError } from '@/services/error' import { type ApiRequestError, normalizeError } from '@/services/error'
import { useSnackbarStore } from '@/stores/snackbar' import { useSnackbarStore } from '@/stores/snackbar'
@@ -9,6 +9,15 @@ type Options = {
errorToastLevel?: (error: ApiRequestError) => ToastLevel errorToastLevel?: (error: ApiRequestError) => ToastLevel
} }
interface UseApiCallResult<TResult, TArgs extends unknown[]> {
loading: Ref<boolean>
data: Ref<TResult | null>
error: Ref<ApiRequestError | null>
execute: (...args: TArgs) => Promise<TResult>
executeSafe: (...args: TArgs) => Promise<TResult | null>
reset: () => void
}
function getDefaultToastLevel (error: ApiRequestError): ToastLevel { function getDefaultToastLevel (error: ApiRequestError): ToastLevel {
if (typeof error.status === 'number' && error.status >= 500) return 'error' if (typeof error.status === 'number' && error.status >= 500) return 'error'
return 'warning' return 'warning'
@@ -21,9 +30,9 @@ function levelToColor (level: ToastLevel): string {
} }
export function useApiCall <TResult, TArgs extends unknown[]>(action: (...args: TArgs) => Promise<TResult>, export function useApiCall <TResult, TArgs extends unknown[]>(action: (...args: TArgs) => Promise<TResult>,
options?: Options) { options?: Options): UseApiCallResult<TResult, TArgs> {
const loading = ref(false) const loading = ref(false)
const data = ref<TResult | null>(null) const data = ref<TResult | null>(null) as Ref<TResult | null>
const error = ref<ApiRequestError | null>(null) const error = ref<ApiRequestError | null>(null)
const snackbar = useSnackbarStore() const snackbar = useSnackbarStore()
@@ -80,4 +89,3 @@ export function useApiCall <TResult, TArgs extends unknown[]>(action: (...args:
reset, reset,
} }
} }
-2
View File
@@ -1,2 +0,0 @@
export { default as SKAdminLayout } from '@/components/layouts/SKAdminLayout.vue'
export { default as SKEmptyLayout } from '@/components/layouts/SKEmptyLayout.vue'
-7
View File
@@ -1,7 +0,0 @@
<template>
<HelloWorld />
</template>
<script lang="ts" setup>
import HelloWorld from '@/components/HelloWorld.vue'
</script>
+6
View File
@@ -0,0 +1,6 @@
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<Record<string, never>, Record<string, never>, unknown>
export default component
}
+2 -388
View File
@@ -1,393 +1,7 @@
<template> <template>
<div class="d-flex flex-column"> <EditableStudentGrid />
<v-card variant="flat">
<v-card-title class="d-flex flex-wrap align-center py-0 ga-2">
<span class="text-h6">可編輯表格維護示範</span>
<v-chip :color="hasAnyChange ? 'warning' : 'success'" variant="tonal">
{{ hasAnyChange ? '有未儲存變更' : '已同步' }}
</v-chip>
<v-chip color="info" variant="tonal">筆數 {{ filteredStudents.length }}</v-chip>
<v-spacer />
<v-btn flat :prepend-icon="mdiMagnify" @click="isSearchVisible = !isSearchVisible">條件搜尋</v-btn>
<v-switch v-model="isBulkEditEnabled" color="primary" hide-details label="啟用編輯" />
</v-card-title>
<v-divider />
<v-card-text class="pb-0 pt-2">
<!-- 搜尋條件 -->
<v-row v-if="isSearchVisible" class="mb-2" dense>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">學號</div>
<v-text-field
v-model="search.studentId" clearable density="compact" hide-details
placeholder="例如:S2024001" variant="outlined" />
</v-col>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">姓名</div>
<v-text-field
v-model="search.name" clearable density="compact" hide-details placeholder="例如:王小明"
variant="outlined" />
</v-col>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">系所</div>
<v-select
v-model="search.department" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" clearable density="compact" hide-details
:items="departments" variant="outlined" />
</v-col>
</v-row>
<!-- 操作 -->
<v-row v-if="isBulkEditEnabled" align="center" class="mb-2 ga-1" dense>
<v-btn :disabled="!hasSelectedRows" :prepend-icon="mdiDelete" variant="outlined" @click="deleteSelectedRows">
批次刪除
</v-btn>
<v-spacer></v-spacer>
<v-btn
color="primary" :disabled="!hasAnyChange" :prepend-icon="mdiContentSave" variant="outlined"
@click="saveAllRows">
儲存變更
</v-btn>
<v-btn :disabled="!hasAnyChange" :prepend-icon="mdiRestore" variant="text" @click="resetAllRows">
取消變更
</v-btn>
</v-row>
<div ref="tableContainerRef">
<v-data-table
density="comfortable" fixed-header :headers="tableHeaders" :height="tableHeight"
item-value="id" :items="filteredStudents" :items-per-page="10" items-per-page-text="每頁筆數"
page-text=" {0}-{1} / {2} ">
<template #[`header.select`]>
<v-checkbox-btn
:disabled="!isBulkEditEnabled" :indeterminate="isPartiallyVisibleSelected"
:model-value="isAllVisibleSelected" @update:model-value="toggleSelectAll" />
</template>
<template #[`item.select`]="{ item }">
<v-checkbox-btn
:disabled="!isBulkEditEnabled" :model-value="selectedRowIds.includes(item.id)"
@update:model-value="(checked) => toggleSingleRowSelection(item.id, checked)" />
</template>
<template #[`item.studentId`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.studentId" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.name`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.name" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.department`]="{ item }">
<v-select
v-model="draftRows[item.id]!.department" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="departments" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.grade`]="{ item }">
<v-select
v-model="draftRows[item.id]!.grade" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details item-title="title" item-value="value" :items="gradeOptions"
:readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.enrollYear`]="{ item }">
<v-select
v-model="draftRows[item.id]!.enrollYear" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="enrollYears" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.credits`]="{ item }">
<v-text-field
v-model.number="draftRows[item.id]!.credits" density="compact" flat hide-details min="0"
:readonly="!isBulkEditEnabled" type="number" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.advisor`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.advisor" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.email`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.email" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.phone`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.phone" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.status`]="{ item }">
<v-select
v-model="draftRows[item.id]!.status" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="statuses" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.actions`]="{ item }">
<div class="d-flex ga-1 justify-end">
<v-btn
color="error" :disabled="!isBulkEditEnabled" size="small" variant="text"
@click="deleteSingleRow(item.id)">
刪除
</v-btn>
</div>
</template>
</v-data-table>
</div>
</v-card-text>
</v-card>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { mdiContentSave, mdiDelete, mdiMagnify, mdiRestore } from '@mdi/js' import EditableStudentGrid from '@/components/maintenance/EditableStudentGrid.vue'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { type StudentRecord, useStudentStore } from '@/stores/students'
type StudentPayload = Omit<StudentRecord, 'id'>
const studentStore = useStudentStore()
const students = computed(() => studentStore.students)
const departments = ['資訊工程', '企業管理', '應用外語', '視覺設計', '財務金融']
const gradeOptions = [
{ title: '大一', value: 1 },
{ title: '大二', value: 2 },
{ title: '大三', value: 3 },
{ title: '大四', value: 4 },
{ title: '研究所', value: 5 },
]
const enrollYears = [2024, 2023, 2022, 2021, 2020, 2019]
const statuses = ['在學', '休學', '畢業']
const tableHeaders = [
{ title: '', key: 'select', sortable: false, nowrap: true },
{ title: '學號', key: 'studentId', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '姓名', key: 'name', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '系所', key: 'department', sortable: true, minWidth: 140, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '年級', key: 'grade', sortable: true, minWidth: 140, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '入學年度', key: 'enrollYear', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '已修學分', key: 'credits', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '指導老師', key: 'advisor', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: 'Email', key: 'email', sortable: true, minWidth: 200, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '電話', key: 'phone', sortable: true, minWidth: 150, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '狀態', key: 'status', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '操作', key: 'actions', sortable: false, width: 'auto', nowrap: true, cellProps: { class: 'bg-background' } },
] as const
const search = ref({
studentId: '',
name: '',
department: '',
})
const isBulkEditEnabled = ref(false)
const isSearchVisible = ref(false)
const tableContainerRef = ref<HTMLElement | null>(null)
const tableScrollParentRef = ref<HTMLElement | null>(null)
const tableResizeObserver = ref<ResizeObserver | null>(null)
const tableHeight = ref(300)
const draftRows = ref<Record<number, StudentPayload>>({})
const selectedRowIds = ref<number[]>([])
const TABLE_BOTTOM_GAP = 64
const TABLE_MIN_HEIGHT = 240
function toPayload (student: StudentRecord): StudentPayload {
return {
studentId: student.studentId,
name: student.name,
department: student.department,
grade: student.grade,
enrollYear: student.enrollYear,
credits: student.credits,
advisor: student.advisor,
email: student.email,
phone: student.phone,
status: student.status,
}
}
function rebuildDraftRows () {
draftRows.value = Object.fromEntries(students.value.map((item) => [item.id, toPayload(item)]))
}
const getSourceRow = (id: number) => students.value.find((item) => item.id === id) || null
function isRowDirty (id: number) {
const source = getSourceRow(id)
const draft = draftRows.value[id]
if (!source || !draft) return false
return (
source.studentId !== draft.studentId ||
source.name !== draft.name ||
source.department !== draft.department ||
source.grade !== draft.grade ||
source.enrollYear !== draft.enrollYear ||
source.credits !== draft.credits ||
source.advisor !== draft.advisor ||
source.email !== draft.email ||
source.phone !== draft.phone ||
source.status !== draft.status
)
}
const filteredStudents = computed(() => {
const keywordStudentId = search.value.studentId.trim().toLowerCase()
const keywordName = search.value.name.trim().toLowerCase()
const selectedDepartment = search.value.department
return students.value.filter((item) => {
if (studentStore.isMarkedAsDeleted(item.id)) return false
const matchesStudentId = keywordStudentId
? item.studentId.toLowerCase().includes(keywordStudentId)
: true
const matchesName = keywordName ? item.name.toLowerCase().includes(keywordName) : true
const matchesDepartment = selectedDepartment ? item.department === selectedDepartment : true
return matchesStudentId && matchesName && matchesDepartment
})
})
const visibleStudentIds = computed(() => filteredStudents.value.map((item) => item.id))
const isAllVisibleSelected = computed(() =>
visibleStudentIds.value.length > 0 && visibleStudentIds.value.every((id) => selectedRowIds.value.includes(id))
)
const isPartiallyVisibleSelected = computed(() =>
visibleStudentIds.value.some((id) => selectedRowIds.value.includes(id)) && !isAllVisibleSelected.value
)
function toggleSelectAll (checked: boolean | null) {
if (isPartiallyVisibleSelected.value) {
selectedRowIds.value = selectedRowIds.value.filter((id) => !visibleStudentIds.value.includes(id))
return
}
if (!checked) {
selectedRowIds.value = selectedRowIds.value.filter((id) => !visibleStudentIds.value.includes(id))
return
}
selectedRowIds.value = Array.from(new Set([...selectedRowIds.value, ...visibleStudentIds.value]))
}
function toggleSingleRowSelection (id: number, checked: boolean | null) {
if (checked) {
if (!selectedRowIds.value.includes(id)) {
selectedRowIds.value = [...selectedRowIds.value, id]
}
return
}
selectedRowIds.value = selectedRowIds.value.filter((selectedId) => selectedId !== id)
}
const hasAnyChange = computed(() =>
students.value.some((item) => isRowDirty(item.id)) || studentStore.deletedIds.size > 0
)
const hasSelectedRows = computed(() => selectedRowIds.value.length > 0)
function deleteSingleRow (id: number) {
selectedRowIds.value = selectedRowIds.value.filter((selectedId) => selectedId !== id)
studentStore.markAsDeleted(id)
rebuildDraftRows()
}
function deleteSelectedRows () {
if (selectedRowIds.value.length === 0) return
for (const id of selectedRowIds.value) {
studentStore.markAsDeleted(id)
}
selectedRowIds.value = []
rebuildDraftRows()
}
function saveAllRows () {
for (const item of students.value) {
const draft = draftRows.value[item.id]
if (!draft) continue
if (!isRowDirty(item.id)) continue
studentStore.updateStudent(item.id, draft)
}
studentStore.commitDeleted()
rebuildDraftRows()
}
function resetAllRows () {
studentStore.restoreDeleted()
selectedRowIds.value = []
rebuildDraftRows()
}
function recalculateTableHeight () {
const container = tableContainerRef.value
if (!container) return
const scrollParent = tableScrollParentRef.value || (container.closest('.overflow-auto') as HTMLElement | null)
tableScrollParentRef.value = scrollParent
const parentBottom = scrollParent
? scrollParent.getBoundingClientRect().bottom
: window.innerHeight
const top = container.getBoundingClientRect().top
const availableHeight = parentBottom - top - TABLE_BOTTOM_GAP
tableHeight.value = Math.max(TABLE_MIN_HEIGHT, Math.floor(availableHeight))
}
watch(students, () => {
const currentIds = new Set(students.value.map((item) => item.id))
selectedRowIds.value = selectedRowIds.value.filter((id) => currentIds.has(id))
})
watch(students, rebuildDraftRows, { immediate: true })
watch([isSearchVisible, isBulkEditEnabled], async () => {
await nextTick()
requestAnimationFrame(() => {
recalculateTableHeight()
})
})
onMounted(() => {
const container = tableContainerRef.value
if (container) {
tableScrollParentRef.value = container.closest('.overflow-auto') as HTMLElement | null
tableResizeObserver.value = new ResizeObserver(() => {
recalculateTableHeight()
})
tableResizeObserver.value.observe(container)
if (tableScrollParentRef.value) {
tableResizeObserver.value.observe(tableScrollParentRef.value)
}
}
requestAnimationFrame(() => {
recalculateTableHeight()
})
window.addEventListener('resize', recalculateTableHeight)
})
onBeforeUnmount(() => {
tableResizeObserver.value?.disconnect()
window.removeEventListener('resize', recalculateTableHeight)
})
</script> </script>
<style scoped>
:deep(.select-hide-arrow .v-field__append-inner) {
display: none;
}
:deep(.v-table__wrapper .v-field__input) {
padding-top: 0 !important;
padding-bottom: 0 !important;
min-height: 32px;
}
:deep(.v-data-table-footer) {
padding: 4px 0 0;
}
</style>
+115 -427
View File
@@ -123,54 +123,17 @@ v-for="error in errorSummary" :key="error.field" color="error" size="small" vari
<!-- 學生主檔表單檢視模式時會自動套用 readonly 樣式 --> <!-- 學生主檔表單檢視模式時會自動套用 readonly 樣式 -->
<v-form v-else :class="{ 'form-readonly': isFormReadonly }" @submit.prevent="requestSaveConfirmation"> <v-form v-else :class="{ 'form-readonly': isFormReadonly }" @submit.prevent="requestSaveConfirmation">
<v-row dense> <maintenance-student-form-fields
<v-col cols="12" md="6"> :departments="departments"
<v-text-field :enroll-years="enrollYears"
id="field-studentId" v-model="form.studentId" density="comfortable" :disabled="isFormLocked" :field-errors="fieldErrors"
:error-messages="fieldErrors.studentId" label="學號" placeholder="例如:S2024008" :form="form"
:readonly="isFormReadonly" variant="outlined" :grade-options="gradeOptions"
@update:model-value="clearFieldError('studentId')" /> :is-form-locked="isFormLocked"
</v-col> :is-form-readonly="isFormReadonly"
<v-col cols="12" md="6"> :statuses="statuses"
<v-text-field @clear-field="clearFieldError"
id="field-name" v-model="form.name" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.name" />
label="姓名" placeholder="例如:陳怡君" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('name')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-department" v-model="form.department" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.department" :items="departments" label="系所"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('department')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-grade" v-model="form.grade" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.grade"
item-title="title" item-value="value" :items="gradeOptions" label="年級"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('grade')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-enrollYear" v-model="form.enrollYear" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.enrollYear" :items="enrollYears" label="入學年度"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('enrollYear')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-status" v-model="form.status" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.status"
:items="statuses" label="狀態" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('status')" />
</v-col>
<v-col cols="12">
<v-text-field
id="field-email" v-model="form.email" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.email" label="Email" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('email')" />
</v-col>
</v-row>
<v-divider /> <v-divider />
@@ -217,44 +180,26 @@ v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="i
</v-overlay> </v-overlay>
</teleport> </teleport>
<common-confirm-dialog <maintenance-crud-dialogs
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?" :close-visible="confirmCloseVisible"
title="未儲存變更" @confirm="confirmClose" /> :delete-visible="confirmDeleteVisible"
:is-saving="isSaving"
<common-confirm-dialog :navigate-visible="confirmNavigateVisible"
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520" :pending-delete-label="pendingDeleteLabel"
title="確認儲存變更" @confirm="confirmSave"> :save-summary="saveSummary"
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2"> :save-visible="confirmSaveVisible"
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column"> :switch-visible="confirmSwitchVisible"
<div class="text-caption text-medium-emphasis">{{ item.label }}</div> @confirm-close="confirmClose"
<div v-if="item.before !== null" class="text-body-2"> @confirm-delete="confirmDelete"
<span class="text-medium-emphasis"></span> @confirm-navigate="confirmNavigate"
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }"> @confirm-save="confirmSave"
{{ item.before }} @confirm-switch="confirmSwitch"
</span> @update:close-visible="confirmCloseVisible = $event"
</div> @update:delete-visible="confirmDeleteVisible = $event"
<div class="text-body-2"> @update:navigate-visible="confirmNavigateVisible = $event"
<span class="text-medium-emphasis"></span> @update:save-visible="confirmSaveVisible = $event"
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }"> @update:switch-visible="confirmSwitchVisible = $event"
{{ item.after }} />
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<!-- 成功提示 --> <!-- 成功提示 -->
<v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200"> <v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200">
@@ -267,12 +212,15 @@ import { mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil } from '@mdi/js'
import { computed, nextTick, ref } from 'vue' import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify' import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue' import MaintenanceCrudDialogs from '@/components/maintenance/MaintenanceCrudDialogs.vue'
import MaintenanceStudentFormFields from '@/components/maintenance/MaintenanceStudentFormFields.vue'
import MasterDetailSemesterList from '@/components/maintenance/master-detail/MasterDetailSemesterList.vue' import MasterDetailSemesterList from '@/components/maintenance/master-detail/MasterDetailSemesterList.vue'
import MasterDetailSemesterPanel from '@/components/maintenance/master-detail/MasterDetailSemesterPanel.vue' import MasterDetailSemesterPanel from '@/components/maintenance/master-detail/MasterDetailSemesterPanel.vue'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue' import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue' import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue' import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
import { useMaintenanceCrudFlow } from '@/composables/maintenance/useMaintenanceCrudFlow'
import { useStudentMaintenanceForm } from '@/composables/maintenance/useStudentMaintenanceForm'
import { type SemesterRecord, useSemesterStore } from '@/stores/semesters' import { type SemesterRecord, useSemesterStore } from '@/stores/semesters'
import { type StudentRecord, useStudentStore } from '@/stores/students' import { type StudentRecord, useStudentStore } from '@/stores/students'
@@ -329,21 +277,11 @@ const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create') const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false) const isLoading = ref(false)
const isSaving = ref(false) const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋 // UI 回饋
const snackbarVisible = ref(false) const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null) const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋 // 防止快速切換導致的異步覆蓋
const loadSequence = ref(0) const loadSequence = ref(0)
// 暫存待處理的目標
const pendingDelete = ref<StudentRecord | null>(null)
const pendingSwitchTarget = ref<StudentRecord | null>(null)
const pendingNavigateTarget = ref<StudentRecord | null>(null)
// Master-Detail 擴充 // Master-Detail 擴充
const studentSemesters = ref<SemesterRecord[]>([]) const studentSemesters = ref<SemesterRecord[]>([])
@@ -433,32 +371,29 @@ function removeCourseFromDetail (index: number) {
} }
// 表單資料與初始快照(用於 dirty 判斷) const {
const form = ref({ errorSummary,
studentId: '', fieldErrors,
name: '', form,
department: departments[0] ?? '', isDirty,
grade: gradeOptions[0]?.value ?? 1, saveSummary,
enrollYear: enrollYears[0] ?? 2024, clearAllErrors,
credits: 0, clearFieldError,
advisor: '', gradeLabel,
email: '', resetForm,
phone: '', rowProps,
status: statuses[0] ?? '', setForm,
}) statusColor,
const initialForm = ref({ ...form.value }) syncInitialForm,
// 欄位錯誤訊息(僅保存一則) validateForm,
const fieldErrors = ref<Record<string, string[]>>({ } = useStudentMaintenanceForm({
studentId: [], departments,
name: [], gradeOptions,
department: [], enrollYears,
grade: [], statuses,
enrollYear: [], students,
credits: [], editingId,
advisor: [], highlightedId,
email: [],
phone: [],
status: [],
}) })
// 表單欄位簡單排版(無分組) // 表單欄位簡單排版(無分組)
@@ -473,60 +408,59 @@ const dialogSubtitle = computed(() => {
if (!editingId.value) return '' if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}` return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
}) })
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示) // 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly // 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value) const isFormLocked = computed(() => isLoading.value || isSaving.value)
const {
closeDialog,
confirmClose,
confirmCloseVisible,
confirmDelete,
confirmDeleteVisible,
confirmNavigate,
confirmNavigateVisible,
confirmSaveVisible,
confirmSwitch,
confirmSwitchVisible,
currentEditingRecord,
handleDialogVisibility,
hasNextRecord,
hasPrevRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
pendingDeleteLabel,
requestCloseDialog,
requestDeleteConfirmation,
requestDeleteCurrent,
switchToEditMode,
switchToViewMode,
} = useMaintenanceCrudFlow<StudentRecord>({
records: students,
editingId,
dialogMode,
dialogVisible,
isLoading,
isSaving,
isDirty,
clearAllErrors,
resetForm,
openEditDialog,
openViewDialog,
removeRecord: (id) => {
studentStore.removeStudent(id)
semesterStore.removeByStudentId(id)
},
describeRecord: (student) => `${student.studentId} ${student.name}`,
onCloseReset: () => {
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
isDetailEditing.value = false
detailForm.value = null
},
})
const isFormReadonly = computed(() => isViewMode.value) const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件 // 重設查詢條件
function resetSearch () { function resetSearch () {
search.value = { search.value = {
@@ -538,25 +472,6 @@ function resetSearch () {
} }
} }
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
isDetailEditing.value = false
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值 // 新增:開啟彈窗,使用預設值
function openAddDialog () { function openAddDialog () {
loadSequence.value += 1 loadSequence.value += 1
@@ -566,6 +481,7 @@ function openAddDialog () {
selectedSemesterId.value = null selectedSemesterId.value = null
activeMobilePanel.value = 'master' activeMobilePanel.value = 'master'
resetForm() resetForm()
isDetailEditing.value = false
isLoading.value = false isLoading.value = false
dialogVisible.value = true dialogVisible.value = true
} }
@@ -584,7 +500,7 @@ function openEditDialog (student: StudentRecord) {
clearAllErrors() clearAllErrors()
setTimeout(() => { setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = { setForm({
studentId: student.studentId, studentId: student.studentId,
name: student.name, name: student.name,
department: student.department, department: student.department,
@@ -595,8 +511,8 @@ function openEditDialog (student: StudentRecord) {
email: student.email, email: student.email,
phone: student.phone, phone: student.phone,
status: student.status, status: student.status,
} })
initialForm.value = { ...form.value } syncInitialForm()
isLoading.value = false isLoading.value = false
}, 350) }, 350)
} }
@@ -615,7 +531,7 @@ function openViewDialog (student: StudentRecord) {
clearAllErrors() clearAllErrors()
setTimeout(() => { setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = { setForm({
studentId: student.studentId, studentId: student.studentId,
name: student.name, name: student.name,
department: student.department, department: student.department,
@@ -626,89 +542,12 @@ function openViewDialog (student: StudentRecord) {
email: student.email, email: student.email,
phone: student.phone, phone: student.phone,
status: student.status, status: student.status,
} })
initialForm.value = { ...form.value } syncInitialForm()
isLoading.value = false isLoading.value = false
}, 350) }, 350)
} }
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認 // 先檢核再提示儲存確認
async function requestSaveConfirmation () { async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
@@ -761,7 +600,7 @@ async function saveStudent () {
highlightedId.value = createdId highlightedId.value = createdId
} }
initialForm.value = { ...form.value } syncInitialForm()
dialogVisible.value = false dialogVisible.value = false
snackbarVisible.value = true snackbarVisible.value = true
isSaving.value = false isSaving.value = false
@@ -770,163 +609,12 @@ async function saveStudent () {
}, 1600) }, 1600)
} }
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
semesterStore.removeByStudentId(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) { function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`) const target = document.getElementById(`field-${field}`)
if (!target) return if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' }) target.scrollIntoView({ behavior: 'smooth', block: 'center' })
} }
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
isDetailEditing.value = false
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
function handleSemesterSelect (id: number) { function handleSemesterSelect (id: number) {
if (isMobile.value) { if (isMobile.value) {
selectedSemesterId.value = id selectedSemesterId.value = id
+113 -427
View File
@@ -113,54 +113,17 @@ v-else :class="[
{ 'form-readonly': isFormReadonly }, { 'form-readonly': isFormReadonly },
isMobile ? '' : 'd-flex flex-column h-100', isMobile ? '' : 'd-flex flex-column h-100',
]" @submit.prevent="requestSaveConfirmation"> ]" @submit.prevent="requestSaveConfirmation">
<v-row dense> <maintenance-student-form-fields
<v-col cols="12" md="3"> :departments="departments"
<v-text-field :enroll-years="enrollYears"
id="field-studentId" v-model="form.studentId" density="comfortable" :disabled="isFormLocked" :field-errors="fieldErrors"
:error-messages="fieldErrors.studentId" label="學號" placeholder="例如:S2024008" :form="form"
:readonly="isFormReadonly" variant="outlined" :grade-options="gradeOptions"
@update:model-value="clearFieldError('studentId')" /> :is-form-locked="isFormLocked"
</v-col> :is-form-readonly="isFormReadonly"
<v-col cols="12" md="3"> :statuses="statuses"
<v-text-field @clear-field="clearFieldError"
id="field-name" v-model="form.name" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.name" />
label="姓名" placeholder="例如:陳怡君" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('name')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-department" v-model="form.department" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.department" :items="departments" label="系所"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('department')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-grade" v-model="form.grade" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.grade"
item-title="title" item-value="value" :items="gradeOptions" label="年級"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('grade')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-enrollYear" v-model="form.enrollYear" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.enrollYear" :items="enrollYears" label="入學年度"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('enrollYear')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-status" v-model="form.status" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.status"
:items="statuses" label="狀態" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('status')" />
</v-col>
<v-col cols="12" md="3">
<v-text-field
id="field-email" v-model="form.email" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.email" label="Email" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('email')" />
</v-col>
</v-row>
<v-divider /> <v-divider />
@@ -206,44 +169,26 @@ v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="i
</v-overlay> </v-overlay>
</teleport> </teleport>
<common-confirm-dialog <maintenance-crud-dialogs
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?" :close-visible="confirmCloseVisible"
title="未儲存變更" @confirm="confirmClose" /> :delete-visible="confirmDeleteVisible"
:is-saving="isSaving"
<common-confirm-dialog :navigate-visible="confirmNavigateVisible"
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520" :pending-delete-label="pendingDeleteLabel"
title="確認儲存變更" @confirm="confirmSave"> :save-summary="saveSummary"
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2"> :save-visible="confirmSaveVisible"
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column"> :switch-visible="confirmSwitchVisible"
<div class="text-caption text-medium-emphasis">{{ item.label }}</div> @confirm-close="confirmClose"
<div v-if="item.before !== null" class="text-body-2"> @confirm-delete="confirmDelete"
<span class="text-medium-emphasis"></span> @confirm-navigate="confirmNavigate"
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }"> @confirm-save="confirmSave"
{{ item.before }} @confirm-switch="confirmSwitch"
</span> @update:close-visible="confirmCloseVisible = $event"
</div> @update:delete-visible="confirmDeleteVisible = $event"
<div class="text-body-2"> @update:navigate-visible="confirmNavigateVisible = $event"
<span class="text-medium-emphasis"></span> @update:save-visible="confirmSaveVisible = $event"
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }"> @update:switch-visible="confirmSwitchVisible = $event"
{{ item.after }} />
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<!-- 刪除課程確認 --> <!-- 刪除課程確認 -->
<common-confirm-dialog <common-confirm-dialog
@@ -294,12 +239,15 @@ import { mdiBookPlus, mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil } from
import { computed, nextTick, ref } from 'vue' import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify' import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue' import MaintenanceCrudDialogs from '@/components/maintenance/MaintenanceCrudDialogs.vue'
import MaintenanceStudentFormFields from '@/components/maintenance/MaintenanceStudentFormFields.vue'
import MasterDetailBSemesterMobilePanel from '@/components/maintenance/master-detail-b/MasterDetailBSemesterMobilePanel.vue' import MasterDetailBSemesterMobilePanel from '@/components/maintenance/master-detail-b/MasterDetailBSemesterMobilePanel.vue'
import MasterDetailBSemesterSection from '@/components/maintenance/master-detail-b/MasterDetailBSemesterSection.vue' import MasterDetailBSemesterSection from '@/components/maintenance/master-detail-b/MasterDetailBSemesterSection.vue'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue' import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue' import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue' import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
import { useMaintenanceCrudFlow } from '@/composables/maintenance/useMaintenanceCrudFlow'
import { useStudentMaintenanceForm } from '@/composables/maintenance/useStudentMaintenanceForm'
import { type CourseRecord, type SemesterRecord, useSemesterStore } from '@/stores/semesters' import { type CourseRecord, type SemesterRecord, useSemesterStore } from '@/stores/semesters'
import { type StudentRecord, useStudentStore } from '@/stores/students' import { type StudentRecord, useStudentStore } from '@/stores/students'
@@ -356,21 +304,11 @@ const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create') const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false) const isLoading = ref(false)
const isSaving = ref(false) const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋 // UI 回饋
const snackbarVisible = ref(false) const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null) const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋 // 防止快速切換導致的異步覆蓋
const loadSequence = ref(0) const loadSequence = ref(0)
// 暫存待處理的目標
const pendingDelete = ref<StudentRecord | null>(null)
const pendingSwitchTarget = ref<StudentRecord | null>(null)
const pendingNavigateTarget = ref<StudentRecord | null>(null)
// Master-Detail 擴充 // Master-Detail 擴充
const studentSemesters = ref<SemesterRecord[]>([]) const studentSemesters = ref<SemesterRecord[]>([])
@@ -495,32 +433,29 @@ function handleUpdateCourse (semesterId: number, courseIndex: number, payload: P
} }
// 表單資料與初始快照(用於 dirty 判斷) const {
const form = ref({ errorSummary,
studentId: '', fieldErrors,
name: '', form,
department: departments[0] ?? '', isDirty,
grade: gradeOptions[0]?.value ?? 1, saveSummary,
enrollYear: enrollYears[0] ?? 2024, clearAllErrors,
credits: 0, clearFieldError,
advisor: '', gradeLabel,
email: '', resetForm,
phone: '', rowProps,
status: statuses[0] ?? '', setForm,
}) statusColor,
const initialForm = ref({ ...form.value }) syncInitialForm,
// 欄位錯誤訊息(僅保存一則) validateForm,
const fieldErrors = ref<Record<string, string[]>>({ } = useStudentMaintenanceForm({
studentId: [], departments,
name: [], gradeOptions,
department: [], enrollYears,
grade: [], statuses,
enrollYear: [], students,
credits: [], editingId,
advisor: [], highlightedId,
email: [],
phone: [],
status: [],
}) })
// 表單欄位簡單排版(無分組) // 表單欄位簡單排版(無分組)
@@ -535,60 +470,58 @@ const dialogSubtitle = computed(() => {
if (!editingId.value) return '' if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}` return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
}) })
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示) // 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly // 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value) const isFormLocked = computed(() => isLoading.value || isSaving.value)
const {
closeDialog,
confirmClose,
confirmCloseVisible,
confirmDelete,
confirmDeleteVisible,
confirmNavigate,
confirmNavigateVisible,
confirmSaveVisible,
confirmSwitch,
confirmSwitchVisible,
currentEditingRecord,
handleDialogVisibility,
hasNextRecord,
hasPrevRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
pendingDeleteLabel,
requestCloseDialog,
requestDeleteConfirmation,
requestDeleteCurrent,
switchToEditMode,
switchToViewMode,
} = useMaintenanceCrudFlow<StudentRecord>({
records: students,
editingId,
dialogMode,
dialogVisible,
isLoading,
isSaving,
isDirty,
clearAllErrors,
resetForm,
openEditDialog,
openViewDialog,
removeRecord: (id) => {
studentStore.removeStudent(id)
semesterStore.removeByStudentId(id)
},
describeRecord: (student) => `${student.studentId} ${student.name}`,
onCloseReset: () => {
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
studentSemesters.value = []
},
})
const isFormReadonly = computed(() => isViewMode.value) const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件 // 重設查詢條件
function resetSearch () { function resetSearch () {
search.value = { search.value = {
@@ -600,24 +533,6 @@ function resetSearch () {
} }
} }
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值 // 新增:開啟彈窗,使用預設值
function openAddDialog () { function openAddDialog () {
loadSequence.value += 1 loadSequence.value += 1
@@ -645,7 +560,7 @@ function openEditDialog (student: StudentRecord) {
clearAllErrors() clearAllErrors()
setTimeout(() => { setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = { setForm({
studentId: student.studentId, studentId: student.studentId,
name: student.name, name: student.name,
department: student.department, department: student.department,
@@ -656,8 +571,8 @@ function openEditDialog (student: StudentRecord) {
email: student.email, email: student.email,
phone: student.phone, phone: student.phone,
status: student.status, status: student.status,
} })
initialForm.value = { ...form.value } syncInitialForm()
isLoading.value = false isLoading.value = false
}, 350) }, 350)
} }
@@ -676,7 +591,7 @@ function openViewDialog (student: StudentRecord) {
clearAllErrors() clearAllErrors()
setTimeout(() => { setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = { setForm({
studentId: student.studentId, studentId: student.studentId,
name: student.name, name: student.name,
department: student.department, department: student.department,
@@ -687,89 +602,12 @@ function openViewDialog (student: StudentRecord) {
email: student.email, email: student.email,
phone: student.phone, phone: student.phone,
status: student.status, status: student.status,
} })
initialForm.value = { ...form.value } syncInitialForm()
isLoading.value = false isLoading.value = false
}, 350) }, 350)
} }
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認 // 先檢核再提示儲存確認
async function requestSaveConfirmation () { async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
@@ -822,7 +660,7 @@ async function saveStudent () {
highlightedId.value = createdId highlightedId.value = createdId
} }
initialForm.value = { ...form.value } syncInitialForm()
dialogVisible.value = false dialogVisible.value = false
snackbarVisible.value = true snackbarVisible.value = true
isSaving.value = false isSaving.value = false
@@ -831,163 +669,11 @@ async function saveStudent () {
}, 1600) }, 1600)
} }
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
semesterStore.removeByStudentId(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) { function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`) const target = document.getElementById(`field-${field}`)
if (!target) return if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' }) target.scrollIntoView({ behavior: 'smooth', block: 'center' })
} }
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
studentSemesters.value = []
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
</script> </script>
<style scoped> <style scoped>
+113 -427
View File
@@ -113,54 +113,17 @@ v-else :class="[
{ 'form-readonly': isFormReadonly }, { 'form-readonly': isFormReadonly },
isMobile ? '' : 'd-flex flex-column h-100', isMobile ? '' : 'd-flex flex-column h-100',
]" @submit.prevent="requestSaveConfirmation"> ]" @submit.prevent="requestSaveConfirmation">
<v-row dense> <maintenance-student-form-fields
<v-col cols="12" md="3"> :departments="departments"
<v-text-field :enroll-years="enrollYears"
id="field-studentId" v-model="form.studentId" density="comfortable" :disabled="isFormLocked" :field-errors="fieldErrors"
:error-messages="fieldErrors.studentId" label="學號" placeholder="例如:S2024008" :form="form"
:readonly="isFormReadonly" variant="outlined" :grade-options="gradeOptions"
@update:model-value="clearFieldError('studentId')" /> :is-form-locked="isFormLocked"
</v-col> :is-form-readonly="isFormReadonly"
<v-col cols="12" md="3"> :statuses="statuses"
<v-text-field @clear-field="clearFieldError"
id="field-name" v-model="form.name" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.name" />
label="姓名" placeholder="例如:陳怡君" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('name')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-department" v-model="form.department" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.department" :items="departments" label="系所"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('department')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-grade" v-model="form.grade" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.grade"
item-title="title" item-value="value" :items="gradeOptions" label="年級"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('grade')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-enrollYear" v-model="form.enrollYear" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.enrollYear" :items="enrollYears" label="入學年度"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('enrollYear')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-status" v-model="form.status" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.status"
:items="statuses" label="狀態" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('status')" />
</v-col>
<v-col cols="12" md="3">
<v-text-field
id="field-email" v-model="form.email" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.email" label="Email" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('email')" />
</v-col>
</v-row>
<v-divider /> <v-divider />
<master-detail-c-course-section <master-detail-c-course-section
@@ -205,44 +168,26 @@ v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="i
</v-overlay> </v-overlay>
</teleport> </teleport>
<common-confirm-dialog <maintenance-crud-dialogs
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?" :close-visible="confirmCloseVisible"
title="未儲存變更" @confirm="confirmClose" /> :delete-visible="confirmDeleteVisible"
:is-saving="isSaving"
<common-confirm-dialog :navigate-visible="confirmNavigateVisible"
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520" :pending-delete-label="pendingDeleteLabel"
title="確認儲存變更" @confirm="confirmSave"> :save-summary="saveSummary"
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2"> :save-visible="confirmSaveVisible"
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column"> :switch-visible="confirmSwitchVisible"
<div class="text-caption text-medium-emphasis">{{ item.label }}</div> @confirm-close="confirmClose"
<div v-if="item.before !== null" class="text-body-2"> @confirm-delete="confirmDelete"
<span class="text-medium-emphasis"></span> @confirm-navigate="confirmNavigate"
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }"> @confirm-save="confirmSave"
{{ item.before }} @confirm-switch="confirmSwitch"
</span> @update:close-visible="confirmCloseVisible = $event"
</div> @update:delete-visible="confirmDeleteVisible = $event"
<div class="text-body-2"> @update:navigate-visible="confirmNavigateVisible = $event"
<span class="text-medium-emphasis"></span> @update:save-visible="confirmSaveVisible = $event"
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }"> @update:switch-visible="confirmSwitchVisible = $event"
{{ item.after }} />
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<!-- 成功提示 --> <!-- 成功提示 -->
<v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200"> <v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200">
@@ -284,12 +229,15 @@ import { mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil, mdiSchool } from '@
import { computed, nextTick, ref } from 'vue' import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify' import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue' import MaintenanceCrudDialogs from '@/components/maintenance/MaintenanceCrudDialogs.vue'
import MaintenanceStudentFormFields from '@/components/maintenance/MaintenanceStudentFormFields.vue'
import MasterDetailCCourseMobilePanel from '@/components/maintenance/master-detail-c/MasterDetailCCourseMobilePanel.vue' import MasterDetailCCourseMobilePanel from '@/components/maintenance/master-detail-c/MasterDetailCCourseMobilePanel.vue'
import MasterDetailCCourseSection from '@/components/maintenance/master-detail-c/MasterDetailCCourseSection.vue' import MasterDetailCCourseSection from '@/components/maintenance/master-detail-c/MasterDetailCCourseSection.vue'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue' import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue' import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue' import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
import { useMaintenanceCrudFlow } from '@/composables/maintenance/useMaintenanceCrudFlow'
import { useStudentMaintenanceForm } from '@/composables/maintenance/useStudentMaintenanceForm'
import { type CourseRecord, type SemesterRecord, useSemesterStore } from '@/stores/semesters' import { type CourseRecord, type SemesterRecord, useSemesterStore } from '@/stores/semesters'
import { type StudentRecord, useStudentStore } from '@/stores/students' import { type StudentRecord, useStudentStore } from '@/stores/students'
@@ -346,21 +294,11 @@ const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create') const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false) const isLoading = ref(false)
const isSaving = ref(false) const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋 // UI 回饋
const snackbarVisible = ref(false) const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null) const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋 // 防止快速切換導致的異步覆蓋
const loadSequence = ref(0) const loadSequence = ref(0)
// 暫存待處理的目標
const pendingDelete = ref<StudentRecord | null>(null)
const pendingSwitchTarget = ref<StudentRecord | null>(null)
const pendingNavigateTarget = ref<StudentRecord | null>(null)
// Master-Detail 擴充 // Master-Detail 擴充
const studentSemesters = ref<SemesterRecord[]>([]) const studentSemesters = ref<SemesterRecord[]>([])
@@ -505,32 +443,29 @@ function removeCourseFromSemester (semesterId: number, courseIndex: number) {
} }
// 表單資料與初始快照(用於 dirty 判斷) const {
const form = ref({ errorSummary,
studentId: '', fieldErrors,
name: '', form,
department: departments[0] ?? '', isDirty,
grade: gradeOptions[0]?.value ?? 1, saveSummary,
enrollYear: enrollYears[0] ?? 2024, clearAllErrors,
credits: 0, clearFieldError,
advisor: '', gradeLabel,
email: '', resetForm,
phone: '', rowProps,
status: statuses[0] ?? '', setForm,
}) statusColor,
const initialForm = ref({ ...form.value }) syncInitialForm,
// 欄位錯誤訊息(僅保存一則) validateForm,
const fieldErrors = ref<Record<string, string[]>>({ } = useStudentMaintenanceForm({
studentId: [], departments,
name: [], gradeOptions,
department: [], enrollYears,
grade: [], statuses,
enrollYear: [], students,
credits: [], editingId,
advisor: [], highlightedId,
email: [],
phone: [],
status: [],
}) })
// 表單欄位簡單排版(無分組) // 表單欄位簡單排版(無分組)
@@ -545,60 +480,58 @@ const dialogSubtitle = computed(() => {
if (!editingId.value) return '' if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}` return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
}) })
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示) // 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly // 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value) const isFormLocked = computed(() => isLoading.value || isSaving.value)
const {
closeDialog,
confirmClose,
confirmCloseVisible,
confirmDelete,
confirmDeleteVisible,
confirmNavigate,
confirmNavigateVisible,
confirmSaveVisible,
confirmSwitch,
confirmSwitchVisible,
currentEditingRecord,
handleDialogVisibility,
hasNextRecord,
hasPrevRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
pendingDeleteLabel,
requestCloseDialog,
requestDeleteConfirmation,
requestDeleteCurrent,
switchToEditMode,
switchToViewMode,
} = useMaintenanceCrudFlow<StudentRecord>({
records: students,
editingId,
dialogMode,
dialogVisible,
isLoading,
isSaving,
isDirty,
clearAllErrors,
resetForm,
openEditDialog,
openViewDialog,
removeRecord: (id) => {
studentStore.removeStudent(id)
semesterStore.removeByStudentId(id)
},
describeRecord: (student) => `${student.studentId} ${student.name}`,
onCloseReset: () => {
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
studentSemesters.value = []
},
})
const isFormReadonly = computed(() => isViewMode.value) const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件 // 重設查詢條件
function resetSearch () { function resetSearch () {
search.value = { search.value = {
@@ -610,24 +543,6 @@ function resetSearch () {
} }
} }
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值 // 新增:開啟彈窗,使用預設值
function openAddDialog () { function openAddDialog () {
loadSequence.value += 1 loadSequence.value += 1
@@ -655,7 +570,7 @@ function openEditDialog (student: StudentRecord) {
clearAllErrors() clearAllErrors()
setTimeout(() => { setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = { setForm({
studentId: student.studentId, studentId: student.studentId,
name: student.name, name: student.name,
department: student.department, department: student.department,
@@ -666,8 +581,8 @@ function openEditDialog (student: StudentRecord) {
email: student.email, email: student.email,
phone: student.phone, phone: student.phone,
status: student.status, status: student.status,
} })
initialForm.value = { ...form.value } syncInitialForm()
isLoading.value = false isLoading.value = false
}, 350) }, 350)
} }
@@ -686,7 +601,7 @@ function openViewDialog (student: StudentRecord) {
clearAllErrors() clearAllErrors()
setTimeout(() => { setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = { setForm({
studentId: student.studentId, studentId: student.studentId,
name: student.name, name: student.name,
department: student.department, department: student.department,
@@ -697,89 +612,12 @@ function openViewDialog (student: StudentRecord) {
email: student.email, email: student.email,
phone: student.phone, phone: student.phone,
status: student.status, status: student.status,
} })
initialForm.value = { ...form.value } syncInitialForm()
isLoading.value = false isLoading.value = false
}, 350) }, 350)
} }
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認 // 先檢核再提示儲存確認
async function requestSaveConfirmation () { async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
@@ -832,7 +670,7 @@ async function saveStudent () {
highlightedId.value = createdId highlightedId.value = createdId
} }
initialForm.value = { ...form.value } syncInitialForm()
dialogVisible.value = false dialogVisible.value = false
snackbarVisible.value = true snackbarVisible.value = true
isSaving.value = false isSaving.value = false
@@ -841,163 +679,11 @@ async function saveStudent () {
}, 1600) }, 1600)
} }
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
semesterStore.removeByStudentId(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) { function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`) const target = document.getElementById(`field-${field}`)
if (!target) return if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' }) target.scrollIntoView({ behavior: 'smooth', block: 'center' })
} }
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
studentSemesters.value = []
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
</script> </script>
<style scoped> <style scoped>
+95 -372
View File
@@ -192,44 +192,26 @@ v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="i
<common-confirm-dialog <maintenance-crud-dialogs
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?" :close-visible="confirmCloseVisible"
title="未儲存變更" @confirm="confirmClose" /> :delete-visible="confirmDeleteVisible"
:is-saving="isSaving"
<common-confirm-dialog :navigate-visible="confirmNavigateVisible"
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520" :pending-delete-label="pendingDeleteLabel"
title="確認儲存變更" @confirm="confirmSave"> :save-summary="saveSummary"
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2"> :save-visible="confirmSaveVisible"
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column"> :switch-visible="confirmSwitchVisible"
<div class="text-caption text-medium-emphasis">{{ item.label }}</div> @confirm-close="confirmClose"
<div v-if="item.before !== null" class="text-body-2"> @confirm-delete="confirmDelete"
<span class="text-medium-emphasis"></span> @confirm-navigate="confirmNavigate"
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }"> @confirm-save="confirmSave"
{{ item.before }} @confirm-switch="confirmSwitch"
</span> @update:close-visible="confirmCloseVisible = $event"
</div> @update:delete-visible="confirmDeleteVisible = $event"
<div class="text-body-2"> @update:navigate-visible="confirmNavigateVisible = $event"
<span class="text-medium-emphasis"></span> @update:save-visible="confirmSaveVisible = $event"
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }"> @update:switch-visible="confirmSwitchVisible = $event"
{{ item.after }} />
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<!-- 成功提示 --> <!-- 成功提示 -->
<v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200"> <v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200">
@@ -241,7 +223,9 @@ v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
import { mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil } from '@mdi/js' import { mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil } from '@mdi/js'
import { computed, nextTick, ref } from 'vue' import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify' import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue' import MaintenanceCrudDialogs from '@/components/maintenance/MaintenanceCrudDialogs.vue'
import { useMaintenanceCrudFlow } from '@/composables/maintenance/useMaintenanceCrudFlow'
import { useStudentMaintenanceForm } from '@/composables/maintenance/useStudentMaintenanceForm'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue' import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue' import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue' import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
@@ -298,47 +282,34 @@ const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create') const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false) const isLoading = ref(false)
const isSaving = ref(false) const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋 // UI 回饋
const snackbarVisible = ref(false) const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null) const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋 // 防止快速切換導致的異步覆蓋
const loadSequence = ref(0) const loadSequence = ref(0)
// 暫存待處理的目標 const {
const pendingDelete = ref<StudentRecord | null>(null) errorSummary,
const pendingSwitchTarget = ref<StudentRecord | null>(null) fieldErrors,
const pendingNavigateTarget = ref<StudentRecord | null>(null) form,
// 表單資料與初始快照(用於 dirty 判斷) isDirty,
const form = ref({ saveSummary,
studentId: '', clearAllErrors,
name: '', clearFieldError,
department: departments[0] ?? '', gradeLabel,
grade: gradeOptions[0]?.value ?? 1, resetForm,
enrollYear: enrollYears[0] ?? 2024, rowProps,
credits: 0, setForm,
advisor: '', statusColor,
email: '', syncInitialForm,
phone: '', validateForm,
status: statuses[0] ?? '', } = useStudentMaintenanceForm({
}) departments,
const initialForm = ref({ ...form.value }) gradeOptions,
// 欄位錯誤訊息(僅保存一則) enrollYears,
const fieldErrors = ref<Record<string, string[]>>({ statuses,
studentId: [], students,
name: [], editingId,
department: [], highlightedId,
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}) })
// 表單欄位簡單排版(無分組) // 表單欄位簡單排版(無分組)
@@ -353,59 +324,52 @@ const dialogSubtitle = computed(() => {
if (!editingId.value) return '' if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}` return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
}) })
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示) // 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly // 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value) const isFormLocked = computed(() => isLoading.value || isSaving.value)
const {
closeDialog,
confirmClose,
confirmCloseVisible,
confirmDelete,
confirmDeleteVisible,
confirmNavigate,
confirmNavigateVisible,
confirmSaveVisible,
confirmSwitch,
confirmSwitchVisible,
currentEditingRecord,
handleDialogVisibility,
hasNextRecord,
hasPrevRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
pendingDeleteLabel,
requestCloseDialog,
requestDeleteConfirmation,
requestDeleteCurrent,
switchToEditMode,
switchToViewMode,
} = useMaintenanceCrudFlow<StudentRecord>({
records: students,
editingId,
dialogMode,
dialogVisible,
isLoading,
isSaving,
isDirty,
clearAllErrors,
resetForm,
openEditDialog,
openViewDialog,
removeRecord: (id) => {
studentStore.removeStudent(id)
},
describeRecord: (student) => `${student.studentId} ${student.name}`,
})
const isFormReadonly = computed(() => isViewMode.value) const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件 // 重設查詢條件
function resetSearch () { function resetSearch () {
@@ -418,24 +382,6 @@ function resetSearch () {
} }
} }
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值 // 新增:開啟彈窗,使用預設值
function openAddDialog () { function openAddDialog () {
loadSequence.value += 1 loadSequence.value += 1
@@ -457,7 +403,7 @@ function openEditDialog (student: StudentRecord) {
clearAllErrors() clearAllErrors()
setTimeout(() => { setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = { setForm({
studentId: student.studentId, studentId: student.studentId,
name: student.name, name: student.name,
department: student.department, department: student.department,
@@ -468,8 +414,8 @@ function openEditDialog (student: StudentRecord) {
email: student.email, email: student.email,
phone: student.phone, phone: student.phone,
status: student.status, status: student.status,
} })
initialForm.value = { ...form.value } syncInitialForm()
isLoading.value = false isLoading.value = false
}, 350) }, 350)
} }
@@ -485,7 +431,7 @@ function openViewDialog (student: StudentRecord) {
clearAllErrors() clearAllErrors()
setTimeout(() => { setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = { setForm({
studentId: student.studentId, studentId: student.studentId,
name: student.name, name: student.name,
department: student.department, department: student.department,
@@ -496,89 +442,12 @@ function openViewDialog (student: StudentRecord) {
email: student.email, email: student.email,
phone: student.phone, phone: student.phone,
status: student.status, status: student.status,
} })
initialForm.value = { ...form.value } syncInitialForm()
isLoading.value = false isLoading.value = false
}, 350) }, 350)
} }
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認 // 先檢核再提示儲存確認
async function requestSaveConfirmation () { async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
@@ -630,7 +499,7 @@ async function saveStudent () {
highlightedId.value = createdId highlightedId.value = createdId
} }
initialForm.value = { ...form.value } syncInitialForm()
dialogVisible.value = false dialogVisible.value = false
snackbarVisible.value = true snackbarVisible.value = true
isSaving.value = false isSaving.value = false
@@ -639,158 +508,12 @@ async function saveStudent () {
}, 1600) }, 1600)
} }
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) { function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`) const target = document.getElementById(`field-${field}`)
if (!target) return if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' }) target.scrollIntoView({ behavior: 'smooth', block: 'center' })
} }
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
</script> </script>
<style scoped> <style scoped>