Files
webapp/app/layouts/catalog.vue
Ruslan Bakiev 7ea96a97b3
All checks were successful
Build Docker Image / build (push) Successful in 4m1s
Refactor catalog layout: replace Teleport with provide/inject
- Create useCatalogLayout composable for data transfer from pages to layout
- Layout now owns SearchBar and CatalogMap components directly
- Pages provide data via provideCatalogLayout()
- Fixes navigation glitches (multiple SearchBars) when switching tabs
- Support custom subNavItems for clientarea pages
- Unify 6 pages to use catalog layout:
  - catalog/offers, suppliers, hubs
  - clientarea/orders, addresses, offers
2026-01-15 10:49:40 +07:00

339 lines
11 KiB
Vue

<template>
<div class="min-h-screen bg-base-300">
<!-- Layer 1+2: MainNavigation + SubNavigation (slides up on scroll) -->
<div
class="fixed left-0 right-0 z-50"
:style="{ top: `${headerOffset}px` }"
>
<MainNavigation
class="bg-base-200"
:session-checked="sessionChecked"
:logged-in="isLoggedIn"
:user-avatar-svg="userAvatarSvg"
:user-name="userName"
:user-initials="userInitials"
:theme="theme"
:user-data="userData"
:is-seller="isSeller"
@toggle-theme="toggleTheme"
@sign-out="onClickSignOut"
@sign-in="signIn()"
@switch-team="switchToTeam"
/>
<!-- SubNavigation -->
<div class="h-[54px] bg-base-200 border-b border-base-300 flex items-center">
<div class="flex items-center gap-1 px-4 lg:px-6">
<NuxtLink
v-for="item in subNavItems"
:key="item.path"
:to="localePath(item.path)"
class="px-4 py-2 rounded-full text-sm font-medium transition-colors whitespace-nowrap text-base-content/70 hover:text-base-content hover:bg-base-300"
:class="{ 'text-primary bg-primary/10': isSubNavActive(item.path) }"
>
{{ item.label }}
</NuxtLink>
</div>
</div>
</div>
<!-- Layer 3: SearchBar (fixed, slides to top:0) -->
<div
class="fixed left-0 right-0 z-40 h-14 bg-base-100 border-b border-base-300 flex items-center"
:style="{ top: `${searchBarTop}px` }"
>
<!-- Chevron button inside SearchBar -->
<button
class="btn btn-ghost btn-xs btn-circle ml-4 flex-shrink-0"
@click="isCollapsed ? expand() : collapse()"
>
<Icon :name="isCollapsed ? 'lucide:chevron-down' : 'lucide:chevron-up'" size="16" />
</button>
<!-- SearchBar from page via inject -->
<div class="flex-1 min-w-0 px-4 lg:px-6 py-2">
<CatalogSearchBar
v-if="catalogData"
v-model:search-query="catalogData.searchQuery.value"
:active-filters="toValue(catalogData.activeFilters)"
:displayed-count="toValue(catalogData.displayedCount)"
:total-count="toValue(catalogData.totalCount)"
@remove-filter="catalogData.onRemoveFilter"
@search="catalogData.onSearch"
>
<template v-if="catalogData.filterComponent" #filters>
<component :is="catalogData.filterComponent" />
</template>
</CatalogSearchBar>
</div>
</div>
<!-- Layer 4: Map (fixed, right side, to bottom) -->
<div
class="fixed right-0 bottom-0 w-3/5 z-20 hidden lg:block"
:style="{ top: `${mapTop}px` }"
>
<div v-if="catalogData" class="h-full w-full relative">
<!-- Search with map checkbox -->
<label class="absolute top-4 left-4 z-10 bg-white/90 backdrop-blur px-3 py-2 rounded-lg shadow flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="catalogData.searchWithMap.value" class="checkbox checkbox-sm" />
<span class="text-sm">{{ t('catalogMap.searchWithMap') }}</span>
</label>
<ClientOnly>
<CatalogMap
ref="mapRef"
:map-id="catalogData.mapId"
:items="catalogData.useServerClustering ? [] : toValue(catalogData.mapItems)"
:clustered-points="catalogData.useServerClustering ? toValue(catalogData.clusteredNodes || []) : []"
:use-server-clustering="catalogData.useServerClustering || false"
:point-color="catalogData.pointColor"
:hovered-item-id="catalogData.hoveredItemId.value"
:hovered-item="toValue(catalogData.hoveredItem)"
@select-item="catalogData.onMapSelect"
@bounds-change="catalogData.onBoundsChange"
/>
</ClientOnly>
</div>
</div>
<!-- Content area (left side, with dynamic padding for fixed header) -->
<div
class="lg:w-2/5 min-h-screen"
:style="{ paddingTop: `${contentPaddingTop}px` }"
>
<div class="px-4 lg:px-6 py-4">
<slot />
</div>
</div>
<!-- Mobile: Full width content + bottom toggle for map -->
<div class="lg:hidden fixed bottom-4 left-1/2 -translate-x-1/2 z-30">
<div class="btn-group shadow-lg">
<button
class="btn btn-sm"
:class="{ 'btn-active': mobileView === 'list' }"
@click="mobileView = 'list'"
>
{{ $t('common.list') }}
</button>
<button
class="btn btn-sm"
:class="{ 'btn-active': mobileView === 'map' }"
@click="mobileView = 'map'"
>
{{ $t('common.map') }}
</button>
</div>
</div>
<!-- Mobile map view -->
<div
v-if="mobileView === 'map' && catalogData"
class="lg:hidden fixed inset-0 z-20"
:style="{ top: `${mapTop}px` }"
>
<div class="h-full w-full relative">
<!-- Search with map checkbox -->
<label class="absolute top-4 left-4 z-10 bg-white/90 backdrop-blur px-3 py-2 rounded-lg shadow flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="catalogData.searchWithMap.value" class="checkbox checkbox-sm" />
<span class="text-sm">{{ t('catalogMap.searchWithMap') }}</span>
</label>
<ClientOnly>
<CatalogMap
:map-id="`${catalogData.mapId}-mobile`"
:items="catalogData.useServerClustering ? [] : toValue(catalogData.mapItems)"
:clustered-points="catalogData.useServerClustering ? toValue(catalogData.clusteredNodes || []) : []"
:use-server-clustering="catalogData.useServerClustering || false"
:point-color="catalogData.pointColor"
:hovered-item-id="catalogData.hoveredItemId.value"
:hovered-item="toValue(catalogData.hoveredItem)"
@select-item="catalogData.onMapSelect"
@bounds-change="catalogData.onBoundsChange"
/>
</ClientOnly>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { toValue } from 'vue'
import { useCatalogLayoutData } from '~/composables/useCatalogLayout'
const runtimeConfig = useRuntimeConfig()
const siteUrl = runtimeConfig.public.siteUrl || 'https://optovia.ru/'
const { signIn, signOut, loggedIn, fetch: fetchSession } = useAuth()
const route = useRoute()
const localePath = useLocalePath()
const { t } = useI18n()
// Inject catalog data from page
const catalogData = useCatalogLayoutData()
// Map ref for external flyTo access
const mapRef = ref<{ flyTo: (lat: number, lng: number, zoom?: number) => void } | null>(null)
// Smooth collapsible header
// MainNav: 64px (h-16)
// SubNav: 40px (py-2 + links)
// Total header = 104px, SearchBar = 48px
const {
headerOffset,
searchBarTop,
mapTop,
contentPaddingTop,
isCollapsed,
expand,
collapse
} = useScrollCollapse(118, 56)
// Mobile view toggle
const mobileView = ref<'list' | 'map'>('list')
// Theme state
const theme = useState<'default' | 'night'>('theme', () => 'default')
// User data state (shared across layouts)
const userData = useState<{
id?: string
firstName?: string
lastName?: string
avatarId?: string
activeTeam?: { name?: string; teamType?: string; logtoOrgId?: string; selectedLocation?: any }
activeTeamId?: string
teams?: Array<{ id?: string; name?: string; logtoOrgId?: string }>
} | null>('me', () => null)
const sessionChecked = ref(false)
const userAvatarSvg = useState('user-avatar-svg', () => '')
const lastAvatarSeed = useState('user-avatar-seed', () => '')
const isSeller = computed(() => {
return userData.value?.activeTeam?.teamType === 'SELLER'
})
const isLoggedIn = computed(() => loggedIn.value || !!userData.value?.id)
const userName = computed(() => {
return userData.value?.firstName || 'User'
})
const userInitials = computed(() => {
const first = userData.value?.firstName?.charAt(0) || ''
const last = userData.value?.lastName?.charAt(0) || ''
if (first || last) return (first + last).toUpperCase()
return '?'
})
// SubNavigation items - use page-provided items or default to catalog section
const defaultSubNavItems = [
{ label: t('cabinetNav.offers'), path: '/catalog/offers' },
{ label: t('cabinetNav.suppliers'), path: '/catalog/suppliers' },
{ label: t('cabinetNav.hubs'), path: '/catalog/hubs' },
]
const subNavItems = computed(() => {
return catalogData?.subNavItems || defaultSubNavItems
})
const isSubNavActive = (path: string) => {
return route.path === localePath(path) || route.path.startsWith(localePath(path) + '/')
}
// Provide collapsed state to children
provide('headerCollapsed', isCollapsed)
// Avatar generation
const generateUserAvatar = async (seed: string) => {
if (!seed) return
try {
const response = await fetch(`https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(seed)}&backgroundColor=b6e3f4,c0aede,d1d4f9`)
if (response.ok) {
userAvatarSvg.value = await response.text()
lastAvatarSeed.value = seed
}
} catch (error) {
console.error('Error generating avatar:', error)
}
}
const { setActiveTeam } = useActiveTeam()
const { mutate } = useGraphQL()
const locationStore = useLocationStore()
const syncUserUi = async () => {
if (!userData.value) {
locationStore.clear()
return
}
if (userData.value.activeTeamId && userData.value.activeTeam?.logtoOrgId) {
setActiveTeam(userData.value.activeTeamId, userData.value.activeTeam.logtoOrgId)
}
const seed = userData.value.avatarId || userData.value.id || userData.value.firstName || 'default'
if (!userAvatarSvg.value || lastAvatarSeed.value !== seed) {
userAvatarSvg.value = ''
await generateUserAvatar(seed)
}
locationStore.setFromUserData(userData.value.activeTeam?.selectedLocation)
}
watch(userData, () => {
void syncUserUi()
}, { immediate: true })
// Check session
await fetchSession().catch(() => {})
sessionChecked.value = true
const switchToTeam = async (team: { id?: string; logtoOrgId?: string; name?: string }) => {
if (!team?.id) return
try {
const { SwitchTeamDocument } = await import('~/composables/graphql/user/teams-generated')
const result = await mutate(SwitchTeamDocument, { teamId: team.id }, 'user', 'teams')
if (result.switchTeam?.user && userData.value) {
userData.value.activeTeam = team as typeof userData.value.activeTeam
userData.value.activeTeamId = team.id
if (team.logtoOrgId) {
setActiveTeam(team.id, team.logtoOrgId)
}
}
} catch (err) {
console.error('Failed to switch team:', err)
}
}
const onClickSignOut = () => {
signOut(siteUrl)
}
const applyTheme = (value: 'default' | 'night') => {
if (import.meta.client) {
if (value === 'default') {
document.documentElement.removeAttribute('data-theme')
} else {
document.documentElement.setAttribute('data-theme', value)
}
localStorage.setItem('theme', value)
}
}
onMounted(() => {
const stored = import.meta.client ? localStorage.getItem('theme') : null
if (stored === 'night' || stored === 'default') {
theme.value = stored
}
applyTheme(theme.value)
})
watch(theme, (value) => applyTheme(value))
const toggleTheme = () => {
theme.value = theme.value === 'night' ? 'default' : 'night'
}
</script>