Browse Source

Merge pull request #3637 from nocodb/fix/reset-project-state

fix(nc-gui): project state not properly reset
pull/3664/head
Pranav C 2 years ago committed by GitHub
parent
commit
f897a521b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 87
      packages/nc-gui/composables/useProject.ts
  2. 4
      packages/nc-gui/composables/useViewData.ts
  3. 2
      packages/nc-gui/lib/types.ts
  4. 12
      packages/nc-gui/nuxt-shim.d.ts
  5. 23
      packages/nc-gui/pages/[projectType]/[projectId]/index.vue
  6. 41
      packages/nc-gui/pages/[projectType]/[projectId]/index/index.vue
  7. 15
      packages/nc-gui/pages/[projectType]/[projectId]/index/index/[type]/[title]/[[viewTitle]].vue
  8. 36
      packages/nc-gui/pages/index/index/index.vue

87
packages/nc-gui/composables/useProject.ts

@ -1,31 +1,53 @@
import type { MaybeRef } from '@vueuse/core'
import { SqlUiFactory } from 'nocodb-sdk'
import type { OracleUi, ProjectType, TableType } from 'nocodb-sdk'
import { useNuxtApp, useRoute } from '#app'
import type { ProjectMetaInfo } from '~/lib'
import { SqlUiFactory } from 'nocodb-sdk'
import { isString } from '@vueuse/core'
import {
USER_PROJECT_ROLES,
computed,
createEventHook,
ref,
useApi,
useGlobal,
useInjectionState,
useNuxtApp,
useRoute,
useState,
useTheme,
watch,
} from '#imports'
import type { ProjectMetaInfo, Roles } from '~/lib'
import type { ThemeConfig } from '@/composables/useTheme'
import { createEventHook, useInjectionState } from '#imports'
const [setup, use] = useInjectionState((_projectId?: MaybeRef<string>) => {
const { $api, $e } = useNuxtApp()
const { $e } = useNuxtApp()
const { api, isLoading } = useApi()
const route = useRoute()
const { includeM2M } = useGlobal()
const { setTheme, theme } = useTheme()
const projectLoadedHook = createEventHook<ProjectType>()
const projectId = computed(() => (_projectId ? unref(_projectId) : (route.params.projectId as string)))
const project = ref<ProjectType>({})
const tables = ref<TableType[]>([])
const projectRoles = useState<Record<string, boolean>>(USER_PROJECT_ROLES, () => ({}))
const projectRoles = useState<Roles>(USER_PROJECT_ROLES, () => ({}))
const projectMetaInfo = ref<ProjectMetaInfo | undefined>()
const projectId = computed(() => (_projectId ? unref(_projectId) : (route.params.projectId as string)))
// todo: refactor path param name and variable name
const projectType = $computed(() => route.params.projectType as string)
const projectMeta = computed(() => {
const projectMeta = computed<Record<string, any>>(() => {
try {
return typeof project.value.meta === 'string' ? JSON.parse(project.value.meta) : project.value.meta
return isString(project.value.meta) ? JSON.parse(project.value.meta) : project.value.meta
} catch (e) {
return {}
}
@ -44,15 +66,15 @@ const [setup, use] = useInjectionState((_projectId?: MaybeRef<string>) => {
async function loadProjectMetaInfo(force?: boolean) {
if (!projectMetaInfo.value || force) {
const data = await $api.project.metaGet(project.value.id!, {}, {})
projectMetaInfo.value = data
projectMetaInfo.value = await api.project.metaGet(project.value.id!, {}, {})
}
}
async function loadProjectRoles() {
projectRoles.value = {}
if (isSharedBase.value) {
const user = await $api.auth.me(
const user = await api.auth.me(
{},
{
headers: {
@ -60,33 +82,40 @@ const [setup, use] = useInjectionState((_projectId?: MaybeRef<string>) => {
},
},
)
projectRoles.value = user.roles
} else if (project.value.id) {
const user = await $api.auth.me({ project_id: project.value.id })
const user = await api.auth.me({ project_id: project.value.id })
projectRoles.value = user.roles
}
}
async function loadTables() {
if (project.value.id) {
const tablesResponse = await $api.dbTable.list(project.value.id, {
const tablesResponse = await api.dbTable.list(project.value.id, {
includeM2M: includeM2M.value,
})
if (tablesResponse.list) tables.value = tablesResponse.list
}
}
async function loadProject() {
if (projectType === 'base') {
const baseData = await $api.public.sharedBaseGet(route.params.projectId as string)
project.value = await $api.project.read(baseData.project_id!)
async function loadProject(id?: string) {
if (id) {
project.value = await api.project.read(projectId.value)
} else if (projectType === 'base') {
const baseData = await api.public.sharedBaseGet(route.params.projectId as string)
project.value = await api.project.read(baseData.project_id!)
} else if (projectId.value) {
project.value = await $api.project.read(projectId.value)
project.value = await api.project.read(projectId.value)
} else {
return
}
await loadProjectRoles()
await loadTables()
setTheme(projectMeta.value?.theme)
projectLoadedHook.trigger(project.value)
@ -97,15 +126,13 @@ const [setup, use] = useInjectionState((_projectId?: MaybeRef<string>) => {
return
}
if (data.meta && typeof data.meta === 'string') {
await $api.project.update(projectId.value, data)
await api.project.update(projectId.value, data)
} else {
await $api.project.update(projectId.value, { ...data, meta: JSON.stringify(data.meta) })
await api.project.update(projectId.value, { ...data, meta: JSON.stringify(data.meta) })
}
}
async function saveTheme(_theme: Partial<ThemeConfig>) {
$e('c:themes:change')
const fullTheme = {
primaryColor: theme.value.primaryColor,
accentColor: theme.value.accentColor,
@ -119,25 +146,27 @@ const [setup, use] = useInjectionState((_projectId?: MaybeRef<string>) => {
theme: fullTheme,
},
})
setTheme(fullTheme)
$e('c:themes:change')
}
watch(
() => route.params,
(v) => {
if (!v?.projectId) {
(next) => {
if (!next.projectId) {
setTheme()
}
},
)
// TODO useProject should only called inside a project for now this doesn't work
onScopeDispose(() => {
const reset = () => {
project.value = {}
tables.value = []
projectMetaInfo.value = undefined
projectRoles.value = {}
})
}
return {
project,
@ -156,6 +185,8 @@ const [setup, use] = useInjectionState((_projectId?: MaybeRef<string>) => {
projectMeta,
saveTheme,
projectLoadedHook: projectLoadedHook.on,
reset,
isLoading,
}
}, 'useProject')

4
packages/nc-gui/composables/useViewData.ts

@ -1,8 +1,6 @@
import type { Api, ColumnType, FormType, GalleryType, PaginatedType, TableType, ViewType } from 'nocodb-sdk'
import type { ComputedRef, Ref } from 'vue'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import { useNuxtApp } from '#app'
import {
IsPublicInj,
NOCO,
@ -10,6 +8,8 @@ import {
extractSdkResponseErrorMsg,
getHTMLEncodedText,
useApi,
useI18n,
useNuxtApp,
useProject,
useUIPermission,
} from '#imports'

2
packages/nc-gui/lib/types.ts

@ -31,7 +31,7 @@ export interface Field {
system?: boolean
}
export type Roles = Record<Role, boolean> | string
export type Roles = Record<Role | string, boolean> | string
export type Filter = FilterType & { status?: 'update' | 'delete' | 'create'; parentId?: string; readOnly?: boolean }

12
packages/nc-gui/nuxt-shim.d.ts vendored

@ -1,6 +1,7 @@
import type { Api as BaseAPI } from 'nocodb-sdk'
import type { UseGlobalReturn } from './composables/useGlobal/types'
import type { NocoI18n } from './lib'
import type { TabType } from './composables'
declare module '#app/nuxt' {
interface NuxtApp {
@ -28,4 +29,15 @@ declare module 'vue-router' {
hideHeader?: boolean
title?: string
}
interface RouteParams {
projectId: string
projectType: 'base' | 'nc' | string
type: TabType
title: string
viewId: string
viewTitle: string
baseId: string
token: string
}
}

23
packages/nc-gui/pages/[projectType]/[projectId]/index.vue

@ -5,6 +5,8 @@ import {
computed,
definePageMeta,
navigateTo,
onBeforeMount,
onBeforeUnmount,
onKeyStroke,
openLink,
projectThemeColors,
@ -16,6 +18,7 @@ import {
useI18n,
useProject,
useRoute,
useRouter,
useTabs,
useUIPermission,
} from '#imports'
@ -29,9 +32,11 @@ const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const { appInfo, token, signOut, signedIn, user } = useGlobal()
const { projectLoadedHook, project, isSharedBase, loadProjectMetaInfo, projectMetaInfo, saveTheme } = useProject()
const { project, isSharedBase, loadProjectMetaInfo, projectMetaInfo, saveTheme, loadProject, reset } = useProject()
const { clearTabs, addTab } = useTabs()
@ -114,7 +119,7 @@ const copyProjectInfo = async () => {
// Copied to clipboard
message.info(t('msg.info.copiedToClipboard'))
} catch (e: any) {
console.log(e)
console.error(e)
message.error(e.message)
}
}
@ -125,7 +130,7 @@ const copyAuthToken = async () => {
// Copied to clipboard
message.info(t('msg.info.copiedToClipboard'))
} catch (e: any) {
console.log(e)
console.error(e)
message.error(e.message)
}
}
@ -140,11 +145,21 @@ onKeyStroke(
clearTabs()
projectLoadedHook(() => {
onBeforeMount(async () => {
await loadProject()
if (!route.params.type && isUIAllowed('teamAndAuth')) {
addTab({ type: TabType.AUTH, title: t('title.teamAndAuth') })
}
/** If v1 url found navigate to corresponding new url */
const { type, name, view } = route.query
if (type && name) {
await router.replace(`/nc/${route.params.projectId}/${type}/${name}${view ? `/${view}` : ''}`)
}
})
onBeforeUnmount(reset)
</script>
<template>

41
packages/nc-gui/pages/[projectType]/[projectId]/index/index.vue

@ -1,48 +1,17 @@
<script setup lang="ts">
import type { TabItem } from '~/composables'
import { TabType } from '~/composables'
import {
TabMetaInj,
onBeforeMount,
provide,
ref,
useGlobal,
useProject,
useRoute,
useRouter,
useSidebar,
useTabs,
} from '#imports'
import { TabMetaInj, provide, useGlobal, useProject, useSidebar, useTabs } from '#imports'
import MdiAirTableIcon from '~icons/mdi/table-large'
import MdiView from '~icons/mdi/eye-circle-outline'
import MdiAccountGroup from '~icons/mdi/account-group'
const { project, loadProject, loadTables } = useProject()
const { isLoading: isLoadingProject } = useProject()
const { tabs, activeTabIndex, activeTab, closeTab } = useTabs()
const { isLoading } = useGlobal()
const route = useRoute()
const router = useRouter()
const isReady = ref(false)
onBeforeMount(async () => {
if (!Object.keys(project.value).length) await loadProject()
/** If v1 url found navigate to corresponding new url */
const { type, name, view } = route.query
if (type && name) {
await router.replace(`/nc/${route.params.projectId}/${type}/${name}${view ? `/${view}` : ''}`)
}
await loadTables()
isReady.value = true
})
provide(TabMetaInj, activeTab)
const icon = (tab: TabItem) => {
@ -110,9 +79,11 @@ function onEdit(targetKey: number, action: 'add' | 'remove' | string) {
</div>
<div class="w-full min-h-[300px] flex-auto">
<NuxtPage v-if="isReady" />
<div v-show="!isLoadingProject" class="w-full h-full">
<NuxtPage />
</div>
<div v-else class="w-full h-full flex justify-center items-center">
<div v-show="isLoadingProject" class="w-full h-full flex justify-center items-center">
<a-spin size="large" />
</div>
</div>

15
packages/nc-gui/pages/[projectType]/[projectId]/index/index/[type]/[title]/[[viewTitle]].vue

@ -3,7 +3,11 @@ import type { TabItem } from '~/composables'
import { TabMetaInj } from '#imports'
const { getMeta } = useMetas()
const { project, projectLoadedHook } = useProject()
const route = useRoute()
const loading = ref(true)
const activeTab = inject(
@ -11,9 +15,14 @@ const activeTab = inject(
computed(() => ({} as TabItem)),
)
getMeta(route.params.title as string, true).finally(() => {
loading.value = false
})
if (!project.value.id) {
projectLoadedHook(async () => {
await getMeta(route.params.title as string, true)
loading.value = false
})
} else {
getMeta(route.params.title as string, true).finally(() => (loading.value = false))
}
</script>
<template>

36
packages/nc-gui/pages/index/index/index.vue

@ -9,8 +9,10 @@ import {
navigateTo,
projectThemeColors,
ref,
themeV2Colors,
useApi,
useNuxtApp,
useProject,
useSidebar,
useUIPermission,
} from '#imports'
@ -27,6 +29,8 @@ const { isUIAllowed } = useUIPermission()
useSidebar({ hasSidebar: true, isOpen: true })
const { loadProject } = useProject()
const filterQuery = ref('')
const projects = ref<ProjectType[]>()
@ -70,10 +74,14 @@ await loadProjects()
const handleProjectColor = async (projectId: string, color: string) => {
const tcolor = tinycolor(color)
if (tcolor.isValid()) {
const complement = tcolor.complement()
const project: ProjectType = await $api.project.read(projectId)
const meta = project?.meta && typeof project.meta === 'string' ? JSON.parse(project.meta) : project.meta || {}
await $api.project.update(projectId, {
color,
meta: JSON.stringify({
@ -84,8 +92,10 @@ const handleProjectColor = async (projectId: string, color: string) => {
},
}),
})
// Update local project
const localProject = projects.value?.find((p) => p.id === projectId)
if (localProject) {
localProject.color = color
localProject.meta = JSON.stringify({
@ -100,9 +110,21 @@ const handleProjectColor = async (projectId: string, color: string) => {
}
const getProjectPrimary = (project: ProjectType) => {
const meta = project?.meta && typeof project.meta === 'string' ? JSON.parse(project.meta) : project.meta || {}
return meta?.theme?.primaryColor || themeV2Colors['royal-blue'].DEFAULT
if (!project) return
const meta = project.meta && typeof project.meta === 'string' ? JSON.parse(project.meta) : project.meta || {}
return meta.theme?.primaryColor || themeV2Colors['royal-blue'].DEFAULT
}
const customRow = (record: ProjectType) => ({
onClick: async () => {
await navigateTo(`/nc/${record.id}`)
$e('a:project:open')
},
class: ['group'],
})
</script>
<template>
@ -183,15 +205,7 @@ const getProjectPrimary = (project: ProjectType) => {
<a-table
v-else
key="table"
:custom-row="
(record) => ({
onClick: () => {
navigateTo(`/nc/${record.id}`)
$e('a:project:open')
},
class: ['group'],
})
"
:custom-row="customRow"
:data-source="filteredProjects"
:pagination="{ position: ['bottomCenter'] }"
>

Loading…
Cancel
Save