import { computed, ref } from 'vue'; import { defineStore } from 'pinia'; /** 三套业务侧栏各自一份布局,互不影响 */ export type ColSidebarKind = 'company' | 'ec-shop' | 'pdd-shop'; export interface ColSidebarLayout { /** 展开宽度(百分比) */ width: number; collapsed: boolean; } const DEFAULT_LAYOUT: ColSidebarLayout = { width: 22, collapsed: false, }; function createDefaultLayouts(): Record { return { 'ec-shop': { ...DEFAULT_LAYOUT }, 'pdd-shop': { ...DEFAULT_LAYOUT }, company: { ...DEFAULT_LAYOUT }, }; } function clampWidth(width: number) { if (!Number.isFinite(width)) return DEFAULT_LAYOUT.width; return Math.min(50, Math.max(10, Math.round(width * 10) / 10)); } /** * 内部店铺 / 拼多多 / 公司侧栏的展开与宽度,localStorage 持久化。 */ export const useColSidebarLayoutStore = defineStore( 'col-sidebar-layout', () => { const layouts = ref(createDefaultLayouts()); function layoutOf(kind: ColSidebarKind): ColSidebarLayout { const current = layouts.value[kind]; if (current) return current; const created = { ...DEFAULT_LAYOUT }; layouts.value[kind] = created; return created; } function setWidth(kind: ColSidebarKind, width: number) { layoutOf(kind).width = clampWidth(width); } function setCollapsed(kind: ColSidebarKind, collapsed: boolean) { layoutOf(kind).collapsed = collapsed; } function $reset() { // 本机布局偏好,登出不清 } return { layouts, layoutOf, setWidth, setCollapsed, $reset, }; }, { persist: { pick: ['layouts'], }, }, ); /** 给 ColPage 用的双向绑定(宽 + 收起) */ export function useColSidebarLayout(kind: ColSidebarKind) { const store = useColSidebarLayoutStore(); const width = computed({ get: () => store.layoutOf(kind).width, set: (value) => store.setWidth(kind, value), }); const collapsed = computed({ get: () => store.layoutOf(kind).collapsed, set: (value) => store.setCollapsed(kind, value), }); return { width, collapsed }; }