重构项目文件夹目录

This commit is contained in:
2026-06-15 15:53:55 +08:00
parent 8093e07190
commit 7cbe5b3de5
1098 changed files with 34 additions and 4441 deletions
@@ -0,0 +1,80 @@
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
/**
* Purpose: ADMIN_MOBILE_BREAKPOINT supports useAdminViewport.ts by holding or executing the admin mobile breakpoint page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const ADMIN_MOBILE_BREAKPOINT = 960
/**
* Purpose: viewportWidth supports useAdminViewport.ts by holding or executing the viewport width page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const viewportWidth = ref(
typeof window !== 'undefined' ? window.innerWidth : ADMIN_MOBILE_BREAKPOINT + 1
)
/**
* Purpose: listenerCount supports useAdminViewport.ts by holding or executing the listener count page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let listenerCount = 0
/**
* Purpose: updateViewportWidth supports useAdminViewport.ts by holding or executing the update viewport width page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const updateViewportWidth = () => {
if (typeof window === 'undefined') {
return
}
viewportWidth.value = window.innerWidth
}
/**
* Purpose: bindViewportListener supports useAdminViewport.ts by holding or executing the bind viewport listener page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const bindViewportListener = () => {
if (typeof window === 'undefined') {
return
}
if (listenerCount === 0) {
window.addEventListener('resize', updateViewportWidth, { passive: true })
}
listenerCount += 1
}
/**
* Purpose: unbindViewportListener supports useAdminViewport.ts by holding or executing the unbind viewport listener page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const unbindViewportListener = () => {
if (typeof window === 'undefined') {
return
}
listenerCount = Math.max(0, listenerCount - 1)
if (listenerCount === 0) {
window.removeEventListener('resize', updateViewportWidth)
}
}
/**
* Purpose: useAdminViewport supports useAdminViewport.ts by holding or executing the use admin viewport page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const useAdminViewport = () => {
onMounted(() => {
updateViewportWidth()
bindViewportListener()
})
onBeforeUnmount(() => {
unbindViewportListener()
})
return {
viewportWidth: computed(() => viewportWidth.value),
isMobile: computed(() => viewportWidth.value <= ADMIN_MOBILE_BREAKPOINT)
}
}
@@ -0,0 +1,274 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createApp } from 'vue'
import { useGlobalConfirmEnter } from './useConfirmEnter'
/**
* Purpose: visibleRects supports useConfirmEnter.test.ts by holding or executing the visible rects page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const visibleRects = [{
bottom: 100,
height: 100,
left: 0,
right: 100,
top: 0,
width: 100,
x: 0,
y: 0,
toJSON: () => ({})
}] as DOMRect[]
/**
* Purpose: makeVisible supports useConfirmEnter.test.ts by holding or executing the make visible page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const makeVisible = (element: HTMLElement) => {
vi.spyOn(element, 'getClientRects').mockReturnValue(visibleRects as unknown as DOMRectList)
}
/**
* Purpose: setDesktopViewport supports useConfirmEnter.test.ts by holding or executing the set desktop viewport page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const setDesktopViewport = () => {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
value: 1280
})
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
matches: query === '(pointer: coarse)' ? false : false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn()
}))
}
/**
* Purpose: setMobileViewport supports useConfirmEnter.test.ts by holding or executing the set mobile viewport page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const setMobileViewport = () => {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
value: 640
})
}
/**
* Purpose: setCoarsePointer supports useConfirmEnter.test.ts by holding or executing the set coarse pointer page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const setCoarsePointer = () => {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
value: 1280
})
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
matches: query === '(pointer: coarse)',
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn()
}))
}
/**
* Purpose: mountGlobalConfirmEnter supports useConfirmEnter.test.ts by holding or executing the mount global confirm enter page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const mountGlobalConfirmEnter = () => {
const host = document.createElement('div')
document.body.appendChild(host)
const app = createApp({
setup() {
useGlobalConfirmEnter()
return () => null
}
})
app.mount(host)
return () => {
app.unmount()
host.remove()
}
}
/**
* Purpose: createModal supports useConfirmEnter.test.ts by holding or executing the create modal page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const createModal = ({
zIndex = 1000,
buttonClass = '',
disabled = false,
ariaDisabled = false,
footerClass = 'ant-modal-footer'
}: {
zIndex?: number
buttonClass?: string
disabled?: boolean
ariaDisabled?: boolean
footerClass?: 'ant-modal-footer' | 'ant-modal-confirm-btns'
} = {}) => {
const wrap = document.createElement('div')
wrap.className = 'ant-modal-wrap'
wrap.style.zIndex = String(zIndex)
const footer = document.createElement('div')
footer.className = footerClass
const button = document.createElement('button')
button.type = 'button'
button.className = `ant-btn ant-btn-primary ${buttonClass}`.trim()
button.disabled = disabled
if (ariaDisabled) {
button.setAttribute('aria-disabled', 'true')
}
const onClick = vi.fn()
const click = vi.spyOn(button, 'click')
button.addEventListener('click', onClick)
footer.appendChild(button)
wrap.appendChild(footer)
document.body.appendChild(wrap)
makeVisible(wrap)
makeVisible(button)
return { wrap, button, click, onClick }
}
/**
* Purpose: createKeyboardEvent supports useConfirmEnter.test.ts by holding or executing the create keyboard event page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const createKeyboardEvent = () => new KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true,
cancelable: true
})
/**
* Purpose: pressEnter supports useConfirmEnter.test.ts by holding or executing the press enter page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const pressEnter = (target: EventTarget = document) => {
const event = createKeyboardEvent()
target.dispatchEvent(event)
return event
}
describe('useGlobalConfirmEnter', () => {
let unmount: (() => void) | undefined
beforeEach(() => {
document.body.innerHTML = ''
setDesktopViewport()
unmount = mountGlobalConfirmEnter()
})
afterEach(() => {
unmount?.()
document.body.innerHTML = ''
vi.restoreAllMocks()
})
it('clicks the visible top modal primary ok button when PC users press Enter', () => {
const { onClick } = createModal()
const event = pressEnter()
expect(onClick).toHaveBeenCalledTimes(1)
expect(event.defaultPrevented).toBe(true)
})
it('does not click the ok button when Enter starts inside textarea or contenteditable elements', () => {
const { onClick } = createModal()
const textarea = document.createElement('textarea')
document.body.appendChild(textarea)
pressEnter(textarea)
const editable = document.createElement('div')
editable.setAttribute('contenteditable', 'true')
document.body.appendChild(editable)
pressEnter(editable)
expect(onClick).not.toHaveBeenCalled()
})
it.each([
'ant-select-dropdown',
'ant-picker-dropdown',
'ant-dropdown',
'ant-popover'
])('does not click the ok button while %s is open', (dropdownClass) => {
const { onClick } = createModal()
const popup = document.createElement('div')
popup.className = dropdownClass
document.body.appendChild(popup)
pressEnter()
expect(onClick).not.toHaveBeenCalled()
})
it('does not click disabled or loading ok buttons', () => {
const disabledModal = createModal({ disabled: true })
pressEnter()
expect(disabledModal.click).not.toHaveBeenCalled()
expect(disabledModal.onClick).not.toHaveBeenCalled()
disabledModal.wrap.remove()
const ariaDisabledModal = createModal({ ariaDisabled: true })
pressEnter()
expect(ariaDisabledModal.click).not.toHaveBeenCalled()
expect(ariaDisabledModal.onClick).not.toHaveBeenCalled()
ariaDisabledModal.wrap.remove()
const loadingModal = createModal({ buttonClass: 'ant-btn-loading' })
pressEnter()
expect(loadingModal.click).not.toHaveBeenCalled()
expect(loadingModal.onClick).not.toHaveBeenCalled()
})
it('does not click the ok button on mobile width or coarse pointer devices', () => {
const mobileModal = createModal()
setMobileViewport()
pressEnter()
expect(mobileModal.onClick).not.toHaveBeenCalled()
mobileModal.wrap.remove()
const coarsePointerModal = createModal()
setCoarsePointer()
pressEnter()
expect(coarsePointerModal.onClick).not.toHaveBeenCalled()
})
it('clicks only the z-index and DOM-top modal when multiple modals are visible', () => {
const firstModal = createModal({ zIndex: 1000 })
const secondModal = createModal({ zIndex: 1000 })
const topZIndexModal = createModal({ zIndex: 1200 })
pressEnter()
expect(firstModal.onClick).not.toHaveBeenCalled()
expect(secondModal.onClick).not.toHaveBeenCalled()
expect(topZIndexModal.onClick).toHaveBeenCalledTimes(1)
topZIndexModal.wrap.remove()
pressEnter()
expect(firstModal.onClick).not.toHaveBeenCalled()
expect(secondModal.onClick).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,231 @@
/**
* Purpose: ComputedRef supports useConfirmEnter.ts by holding or executing the computed ref page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { computed, onBeforeUnmount, onMounted, type ComputedRef } from 'vue'
/**
* Purpose: UseConfirmEnterOptions supports useConfirmEnter.ts by holding or executing the use confirm enter options page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
interface UseConfirmEnterOptions {
enabled: ComputedRef<boolean>
onConfirm: (event: KeyboardEvent) => void
isConfirmDisabled?: () => boolean
isTopLayer?: () => boolean
}
/**
* Purpose: CONFIRM_ENTER_DISABLED_CLASS supports useConfirmEnter.ts by holding or executing the confirm enter disabled class page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const CONFIRM_ENTER_DISABLED_CLASS = 'confirm-enter-disabled'
/**
* Purpose: DESKTOP_MIN_WIDTH supports useConfirmEnter.ts by holding or executing the desktop min width page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DESKTOP_MIN_WIDTH = 960
/**
* Purpose: isEditableTarget supports useConfirmEnter.ts by holding or executing the is editable target page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const isEditableTarget = (target: EventTarget | null) => {
if (!(target instanceof HTMLElement)) {
return false
}
if (target.isContentEditable) {
return true
}
return target.tagName.toLowerCase() === 'textarea' || Boolean(target.closest('[contenteditable="true"]'))
}
/**
* Purpose: hasOpenPickerOrDropdown supports useConfirmEnter.ts by holding or executing the has open picker or dropdown page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const hasOpenPickerOrDropdown = () => {
return Boolean(document.querySelector([
'.ant-select-dropdown:not(.ant-select-dropdown-hidden)',
'.ant-picker-dropdown:not(.ant-picker-dropdown-hidden)',
'.ant-cascader-dropdown:not(.ant-cascader-dropdown-hidden)',
'.ant-dropdown:not(.ant-dropdown-hidden)',
'.ant-popover:not(.ant-popover-hidden)'
].join(',')))
}
/**
* Purpose: isDesktopViewport supports useConfirmEnter.ts by holding or executing the is desktop viewport page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const isDesktopViewport = () => {
if (typeof window === 'undefined') {
return false
}
const coarsePointer = window.matchMedia?.('(pointer: coarse)').matches ?? false
return window.innerWidth > DESKTOP_MIN_WIDTH && !coarsePointer
}
/**
* Purpose: isVisibleElement supports useConfirmEnter.ts by holding or executing the is visible element page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const isVisibleElement = (element: Element) => {
if (!(element instanceof HTMLElement)) {
return false
}
const style = window.getComputedStyle(element)
return style.display !== 'none'
&& style.visibility !== 'hidden'
&& style.opacity !== '0'
&& element.getClientRects().length > 0
}
/**
* Purpose: isDisabledButton supports useConfirmEnter.ts by holding or executing the is disabled button page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const isDisabledButton = (button: HTMLButtonElement) => {
return button.disabled
|| button.getAttribute('aria-disabled') === 'true'
|| button.classList.contains('ant-btn-loading')
|| button.classList.contains('ant-btn-disabled')
}
/**
* Purpose: getTopModalWrap supports useConfirmEnter.ts by holding or executing the get top modal wrap page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const getTopModalWrap = () => {
const modals = Array.from(document.querySelectorAll<HTMLElement>('.ant-modal-wrap'))
.filter(isVisibleElement)
if (!modals.length) {
return null
}
const sortedModals = modals
.map((modal, index) => {
const zIndex = Number.parseInt(window.getComputedStyle(modal).zIndex || '0', 10)
return {
modal,
index,
zIndex: Number.isNaN(zIndex) ? 0 : zIndex
}
})
.sort((left, right) => left.zIndex - right.zIndex || left.index - right.index)
return sortedModals[sortedModals.length - 1]?.modal ?? null
}
/**
* Purpose: getTopModalConfirmButton supports useConfirmEnter.ts by holding or executing the get top modal confirm button page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const getTopModalConfirmButton = () => {
const topModal = getTopModalWrap()
if (!topModal || topModal.classList.contains(CONFIRM_ENTER_DISABLED_CLASS)) {
return null
}
const button = topModal.querySelector<HTMLButtonElement>([
'.ant-modal-confirm-btns .ant-btn-primary',
'.ant-modal-footer .ant-btn-primary'
].join(','))
if (!button || !isVisibleElement(button) || isDisabledButton(button)) {
return null
}
return button
}
/**
* Purpose: useConfirmEnter supports useConfirmEnter.ts by holding or executing the use confirm enter page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const useConfirmEnter = ({
enabled,
onConfirm,
isConfirmDisabled,
isTopLayer
}: UseConfirmEnterOptions) => {
const canConfirm = computed(() => (
enabled.value
&& !(isConfirmDisabled?.() ?? false)
&& (isTopLayer?.() ?? true)
))
const handleKeydown = (event: KeyboardEvent) => {
if (
event.key !== 'Enter'
|| event.defaultPrevented
|| event.shiftKey
|| event.ctrlKey
|| event.altKey
|| event.metaKey
|| event.isComposing
|| !canConfirm.value
|| isEditableTarget(event.target)
|| hasOpenPickerOrDropdown()
) {
return
}
event.preventDefault()
onConfirm(event)
}
onMounted(() => {
document.addEventListener('keydown', handleKeydown)
})
onBeforeUnmount(() => {
document.removeEventListener('keydown', handleKeydown)
})
}
/**
* Purpose: useGlobalConfirmEnter supports useConfirmEnter.ts by holding or executing the use global confirm enter page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const useGlobalConfirmEnter = () => {
const handleKeydown = (event: KeyboardEvent) => {
if (
event.key !== 'Enter'
|| event.defaultPrevented
|| event.shiftKey
|| event.ctrlKey
|| event.altKey
|| event.metaKey
|| event.isComposing
|| (event as KeyboardEvent & { keyCode?: number }).keyCode === 229
|| !isDesktopViewport()
|| isEditableTarget(event.target)
|| hasOpenPickerOrDropdown()
) {
return
}
const confirmButton = getTopModalConfirmButton()
if (!confirmButton) {
return
}
event.preventDefault()
event.stopImmediatePropagation()
confirmButton.click()
}
onMounted(() => {
document.addEventListener('keydown', handleKeydown)
})
onBeforeUnmount(() => {
document.removeEventListener('keydown', handleKeydown)
})
}
@@ -0,0 +1,71 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('@/api/file', () => ({
fileApi: {
getSignedUrl: vi.fn()
}
}))
vi.mock('@/api/shop', () => ({
shopApi: {
getShopById: vi.fn()
}
}))
import { shopApi } from '@/api/shop'
import { DEFAULT_SHOP_THEME } from '@/utils/shop-theme'
import { useShopTheme } from './useShopTheme'
describe('useShopTheme', () => {
beforeEach(() => {
localStorage.clear()
sessionStorage.clear()
vi.clearAllMocks()
document.documentElement.removeAttribute('style')
})
it('uses the first preset as the default visible theme', async () => {
const { resetShopTheme } = useShopTheme()
resetShopTheme()
expect(DEFAULT_SHOP_THEME.primaryColor).toBe('#E8B4B8')
expect(DEFAULT_SHOP_THEME.secondaryColor).toBe('#C5A059')
expect(DEFAULT_SHOP_THEME.accentColor).toBe('#4A443F')
expect(DEFAULT_SHOP_THEME.pageBgColor).toBe('#FDFBF9')
expect(DEFAULT_SHOP_THEME.cardBgColor).toBe('#FFFFFF')
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#E8B4B8')
expect(document.documentElement.style.getPropertyValue('--theme-secondary')).toBe('#C5A059')
expect(document.documentElement.style.getPropertyValue('--theme-neutral')).toBe('#4A443F')
expect(document.documentElement.style.getPropertyValue('--theme-tertiary')).toBe('#FDFBF9')
})
it('refreshes the admin theme from the cached admin shop context', async () => {
localStorage.setItem('adminAccessToken', 'admin-token')
localStorage.setItem('adminUserInfo', JSON.stringify({ shopId: 42 }))
vi.mocked(shopApi.getShopById).mockResolvedValue({
themePrimaryColor: '#123456',
themeSecondaryColor: '#ABCDEF',
themeAccentColor: '#345678',
themePageBgColor: '#F7FAFC',
themeCardBgColor: '#FFFFFF'
} as never)
const { refreshShopTheme } = useShopTheme()
await refreshShopTheme({ mode: 'admin' })
expect(shopApi.getShopById).toHaveBeenCalledWith('42')
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#123456')
expect(document.documentElement.style.getPropertyValue('--theme-secondary')).toBe('#ABCDEF')
})
it('keeps the default theme for login pages without a shop context', async () => {
const { refreshShopTheme } = useShopTheme()
await refreshShopTheme({ mode: 'admin' })
expect(shopApi.getShopById).not.toHaveBeenCalled()
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#E8B4B8')
})
})
+194
View File
@@ -0,0 +1,194 @@
import { readonly, shallowRef } from 'vue'
import { fileApi } from '@/api/file'
/**
* Purpose: ShopVO supports useShopTheme.ts by holding or executing the shop vo page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { shopApi, type ShopVO } from '@/api/shop'
import {
applyShopTheme,
DEFAULT_SHOP_THEME,
resolveShopTheme,
SHOP_THEME_CHANGED_EVENT,
type ResolvedShopTheme
} from '@/utils/shop-theme'
type ShopThemeMode = 'auto' | 'admin' | 'customer'
export interface RefreshShopThemeOptions {
mode?: ShopThemeMode
shopId?: string | number | null
}
/**
* Purpose: currentTheme supports useShopTheme.ts by holding or executing the current theme page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const currentTheme = shallowRef<ResolvedShopTheme>(DEFAULT_SHOP_THEME)
let cleanupThemeSync: (() => void) | undefined
/**
* Purpose: refreshSequence supports useShopTheme.ts by holding or executing the refresh sequence page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let refreshSequence = 0
applyShopTheme(DEFAULT_SHOP_THEME)
/**
* Purpose: useShopTheme supports useShopTheme.ts by holding or executing the use shop theme page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
export function useShopTheme() {
return {
currentTheme: readonly(currentTheme),
refreshShopTheme,
resetShopTheme,
setupShopThemeSync
}
}
/**
* Purpose: refreshShopTheme supports useShopTheme.ts by holding or executing the refresh shop theme page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function refreshShopTheme(options: RefreshShopThemeOptions = {}) {
const mode = resolveThemeMode(options.mode)
const token = readToken(mode)
const userInfo = readStoredUserInfo(mode)
const shopId = options.shopId === undefined ? userInfo?.shopId : options.shopId
if (!token || !shopId) {
resetShopTheme()
return
}
const sequence = ++refreshSequence
try {
const shop = await shopApi.getShopById(String(shopId))
if (sequence !== refreshSequence) {
return
}
await applyThemeFromShop(shop)
} catch {
if (sequence === refreshSequence) {
resetShopTheme()
}
}
}
/**
* Purpose: resetShopTheme supports useShopTheme.ts by holding or executing the reset shop theme page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function resetShopTheme() {
refreshSequence += 1
currentTheme.value = DEFAULT_SHOP_THEME
applyShopTheme(DEFAULT_SHOP_THEME)
}
/**
* Purpose: setupShopThemeSync supports useShopTheme.ts by holding or executing the setup shop theme sync page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function setupShopThemeSync() {
if (cleanupThemeSync || typeof window === 'undefined') {
return cleanupThemeSync || (() => {})
}
const handleThemeEvent = () => {
void refreshShopTheme()
}
const handleStorage = (event: StorageEvent) => {
if ([
'accessToken',
'userInfo',
'refreshToken',
'adminAccessToken',
'adminRefreshToken',
'adminUserInfo'
].includes(event.key || '')) {
void refreshShopTheme()
}
}
window.addEventListener(SHOP_THEME_CHANGED_EVENT, handleThemeEvent)
window.addEventListener('storage', handleStorage)
window.addEventListener('focus', handleThemeEvent)
cleanupThemeSync = () => {
window.removeEventListener(SHOP_THEME_CHANGED_EVENT, handleThemeEvent)
window.removeEventListener('storage', handleStorage)
window.removeEventListener('focus', handleThemeEvent)
cleanupThemeSync = undefined
}
return cleanupThemeSync
}
/**
* Purpose: applyThemeFromShop supports useShopTheme.ts by holding or executing the apply theme from shop page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function applyThemeFromShop(shop: ShopVO) {
const theme = resolveShopTheme(shop)
currentTheme.value = theme
const backgroundImageUrl = await resolveBackgroundImageUrl(theme.backgroundImageFileId)
applyShopTheme(theme, backgroundImageUrl)
}
/**
* Purpose: resolveBackgroundImageUrl supports useShopTheme.ts by holding or executing the resolve background image url page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function resolveBackgroundImageUrl(fileId?: string) {
if (!fileId) {
return null
}
try {
return await fileApi.getSignedUrl(fileId, 120) as unknown as string
} catch {
return null
}
}
/**
* Purpose: readToken supports useShopTheme.ts by holding or executing the read token page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function resolveThemeMode(mode: ShopThemeMode = 'auto'): Exclude<ShopThemeMode, 'auto'> {
if (mode !== 'auto') {
return mode
}
if (typeof window !== 'undefined' && window.location.pathname.startsWith('/admin')) {
return 'admin'
}
return 'customer'
}
function readToken(mode: Exclude<ShopThemeMode, 'auto'>) {
if (typeof window === 'undefined') {
return ''
}
if (mode === 'admin') {
return localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken') || ''
}
return localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken') || ''
}
/**
* Purpose: readStoredUserInfo supports useShopTheme.ts by holding or executing the read stored user info page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function readStoredUserInfo(mode: Exclude<ShopThemeMode, 'auto'>): { shopId?: string | number } | null {
if (typeof window === 'undefined') {
return null
}
const raw = localStorage.getItem(mode === 'admin' ? 'adminUserInfo' : 'userInfo')
if (!raw) {
return null
}
try {
return JSON.parse(raw) as { shopId?: string | number }
} catch {
return null
}
}