Browse Source

Merge branch 'develop' into qr-prototyping-cleanedup

pull/4142/head
Daniel Spaude 2 years ago
parent
commit
2cb6ad8eb4
No known key found for this signature in database
GPG Key ID: 654A3D1FA4F35FFE
  1. 27
      packages/nc-gui/app.vue
  2. 10
      packages/nc-gui/assets/style.scss
  3. 6
      packages/nc-gui/components.d.ts
  4. 142
      packages/nc-gui/components/cell/MultiSelect.vue
  5. 7
      packages/nc-gui/components/cell/Percent.vue
  6. 111
      packages/nc-gui/components/cell/SingleSelect.vue
  7. 4
      packages/nc-gui/components/cell/Text.vue
  8. 8
      packages/nc-gui/components/dlg/TableCreate.vue
  9. 1
      packages/nc-gui/components/dlg/TableRename.vue
  10. 2
      packages/nc-gui/components/dlg/ViewCreate.vue
  11. 6
      packages/nc-gui/components/shared-view/AskPassword.vue
  12. 3
      packages/nc-gui/components/smartsheet/Cell.vue
  13. 23
      packages/nc-gui/components/smartsheet/Grid.vue
  14. 7
      packages/nc-gui/components/smartsheet/column/EditOrAdd.vue
  15. 4
      packages/nc-gui/components/smartsheet/column/SelectOptions.vue
  16. 42
      packages/nc-gui/components/smartsheet/expanded-form/Header.vue
  17. 10
      packages/nc-gui/components/smartsheet/expanded-form/index.vue
  18. 2
      packages/nc-gui/components/smartsheet/header/CellIcon.ts
  19. 7
      packages/nc-gui/components/smartsheet/toolbar/ColumnFilterMenu.vue
  20. 7
      packages/nc-gui/components/smartsheet/toolbar/FieldsMenu.vue
  21. 16
      packages/nc-gui/components/smartsheet/toolbar/KanbanStackEditOrAdd.vue
  22. 108
      packages/nc-gui/components/smartsheet/toolbar/ShareView.vue
  23. 7
      packages/nc-gui/components/smartsheet/toolbar/SortListMenu.vue
  24. 11
      packages/nc-gui/components/smartsheet/toolbar/StackedBy.vue
  25. 9
      packages/nc-gui/components/smartsheet/toolbar/ViewActions.vue
  26. 6
      packages/nc-gui/components/tabs/auth/user-management/UsersModal.vue
  27. 2
      packages/nc-gui/components/virtual-cell/Lookup.vue
  28. 14
      packages/nc-gui/composables/useColumnCreateStore.ts
  29. 3
      packages/nc-gui/composables/useExpandedFormStore.ts
  30. 28
      packages/nc-gui/composables/useMenuCloseOnEsc/index.ts
  31. 5
      packages/nc-gui/composables/useMultiSelect/index.ts
  32. 11
      packages/nc-gui/composables/useViewData.ts
  33. 2
      packages/nc-gui/lang/en.json
  34. 1
      packages/nc-gui/nuxt.config.ts
  35. 69
      packages/nc-gui/package-lock.json
  36. 4
      packages/nc-gui/pages/[projectType]/form/[viewId]/index/survey.vue
  37. 8
      packages/nc-gui/pages/index/index/create-external.vue
  38. 6
      packages/nc-gui/pages/index/index/index.vue
  39. 3
      packages/nc-gui/utils/cell.ts
  40. 11
      packages/nc-gui/utils/parsers/CSVTemplateAdapter.ts
  41. 2
      packages/noco-docs/content/en/getting-started/installation.md
  42. 1
      packages/nocodb-sdk/src/lib/Api.ts
  43. 47
      packages/nocodb/package-lock.json
  44. 1
      packages/nocodb/src/lib/Noco.ts
  45. 23
      packages/nocodb/src/lib/db/sql-data-mapper/lib/sql/BaseModelSqlv2.ts
  46. 29
      packages/nocodb/src/lib/meta/api/swagger/redocHtml.ts
  47. 1
      packages/nocodb/src/lib/meta/api/testApis.ts
  48. 2
      packages/nocodb/src/lib/models/Model.ts
  49. 22
      packages/nocodb/src/lib/services/test/TestResetService/index.ts
  50. 3
      scripts/sdk/swagger.json
  51. 28
      tests/playwright/pages/Dashboard/ExpandedForm/index.ts
  52. 44
      tests/playwright/pages/Dashboard/common/Cell/SelectOptionCell.ts
  53. 2
      tests/playwright/pages/Dashboard/common/Toolbar/AddEditKanbanStack.ts
  54. 9
      tests/playwright/setup/db.ts
  55. 18
      tests/playwright/setup/index.ts
  56. 24
      tests/playwright/tests/columnMultiSelect.spec.ts
  57. 12
      tests/playwright/tests/columnSingleSelect.spec.ts
  58. 10
      tests/playwright/tests/expandedFormUrl.spec.ts
  59. 2
      tests/playwright/tests/metaSync.spec.ts
  60. 14
      tests/playwright/tests/tableColumnOperation.spec.ts

27
packages/nc-gui/app.vue

@ -6,12 +6,37 @@ const route = useRoute()
const disableBaseLayout = computed(() => route.path.startsWith('/nc/view') || route.path.startsWith('/nc/form')) const disableBaseLayout = computed(() => route.path.startsWith('/nc/view') || route.path.startsWith('/nc/form'))
useTheme() useTheme()
// TODO: Remove when https://github.com/vuejs/core/issues/5513 fixed
const key = ref(0)
const messages = [
`Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`, // chromium based
`NotFoundError: The object can not be found here.`, // safari
"Cannot read properties of null (reading 'parentNode')",
]
if (typeof window !== 'undefined') {
// @ts-expect-error using arbitrary window key
if (!window.__ncvue) {
window.addEventListener('error', (event) => {
if (messages.includes(event.message)) {
event.preventDefault()
console.warn('Re-rendering layout because of https://github.com/vuejs/core/issues/5513')
key.value++
}
})
}
// @ts-expect-error using arbitrary window key
window.__ncvue = true
}
</script> </script>
<template> <template>
<a-config-provider> <a-config-provider>
<NuxtLayout :name="disableBaseLayout ? false : 'base'"> <NuxtLayout :name="disableBaseLayout ? false : 'base'">
<NuxtPage /> <NuxtPage :key="key" />
</NuxtLayout> </NuxtLayout>
</a-config-provider> </a-config-provider>
</template> </template>

10
packages/nc-gui/assets/style.scss

@ -214,17 +214,13 @@ a {
@apply z-1 relative color-transition rounded-md px-4 py-2 text-white; @apply z-1 relative color-transition rounded-md px-4 py-2 text-white;
&::after { &::after {
@apply ring-opacity-100 ring-[2px] ring-slate-300 rounded absolute top-0 left-0 right-0 bottom-0 transition-all duration-150 ease-in-out bg-primary bg-opacity-100; @apply rounded absolute top-0 left-0 right-0 bottom-0 transition-all duration-150 ease-in-out bg-primary bg-opacity-100;
content: ''; content: '';
z-index: -1; z-index: -1;
} }
&:hover::after { &:hover::after {
@apply transform scale-110 ring ring-accent; @apply transform scale-110;
}
&:active::after {
@apply ring ring-accent;
} }
} }
@ -261,7 +257,7 @@ a {
} }
.ant-dropdown-menu-item, .ant-menu-item { .ant-dropdown-menu-item, .ant-menu-item {
@apply !py-0 active:(ring ring-accent ring-opacity-100); @apply py-0;
} }
.ant-dropdown-menu-title-content, .ant-dropdown-menu-title-content,

6
packages/nc-gui/components.d.ts vendored

@ -24,6 +24,7 @@ declare module '@vue/runtime-core' {
ADivider: typeof import('ant-design-vue/es')['Divider'] ADivider: typeof import('ant-design-vue/es')['Divider']
ADrawer: typeof import('ant-design-vue/es')['Drawer'] ADrawer: typeof import('ant-design-vue/es')['Drawer']
ADropdown: typeof import('ant-design-vue/es')['Dropdown'] ADropdown: typeof import('ant-design-vue/es')['Dropdown']
ADropdownButton: typeof import('ant-design-vue/es')['DropdownButton']
AEmpty: typeof import('ant-design-vue/es')['Empty'] AEmpty: typeof import('ant-design-vue/es')['Empty']
AForm: typeof import('ant-design-vue/es')['Form'] AForm: typeof import('ant-design-vue/es')['Form']
AFormItem: typeof import('ant-design-vue/es')['FormItem'] AFormItem: typeof import('ant-design-vue/es')['FormItem']
@ -95,8 +96,6 @@ declare module '@vue/runtime-core' {
MaterialSymbolsDarkModeOutline: typeof import('~icons/material-symbols/dark-mode-outline')['default'] MaterialSymbolsDarkModeOutline: typeof import('~icons/material-symbols/dark-mode-outline')['default']
MaterialSymbolsFileCopyOutline: typeof import('~icons/material-symbols/file-copy-outline')['default'] MaterialSymbolsFileCopyOutline: typeof import('~icons/material-symbols/file-copy-outline')['default']
MaterialSymbolsKeyboardReturn: typeof import('~icons/material-symbols/keyboard-return')['default'] MaterialSymbolsKeyboardReturn: typeof import('~icons/material-symbols/keyboard-return')['default']
MaterialSymbolsKeyboardShift: typeof import('~icons/material-symbols/keyboard-shift')['default']
MaterialSymbolsLightMode: typeof import('~icons/material-symbols/light-mode')['default']
MaterialSymbolsLightModeOutline: typeof import('~icons/material-symbols/light-mode-outline')['default'] MaterialSymbolsLightModeOutline: typeof import('~icons/material-symbols/light-mode-outline')['default']
MaterialSymbolsRocketLaunchOutline: typeof import('~icons/material-symbols/rocket-launch-outline')['default'] MaterialSymbolsRocketLaunchOutline: typeof import('~icons/material-symbols/rocket-launch-outline')['default']
MaterialSymbolsSendOutline: typeof import('~icons/material-symbols/send-outline')['default'] MaterialSymbolsSendOutline: typeof import('~icons/material-symbols/send-outline')['default']
@ -126,6 +125,7 @@ declare module '@vue/runtime-core' {
MdiBugOutline: typeof import('~icons/mdi/bug-outline')['default'] MdiBugOutline: typeof import('~icons/mdi/bug-outline')['default']
MdiCalculator: typeof import('~icons/mdi/calculator')['default'] MdiCalculator: typeof import('~icons/mdi/calculator')['default']
MdiCalendarMonth: typeof import('~icons/mdi/calendar-month')['default'] MdiCalendarMonth: typeof import('~icons/mdi/calendar-month')['default']
MdiCancel: typeof import('~icons/mdi/cancel')['default']
MdiCardsHeart: typeof import('~icons/mdi/cards-heart')['default'] MdiCardsHeart: typeof import('~icons/mdi/cards-heart')['default']
MdiCellphoneMessage: typeof import('~icons/mdi/cellphone-message')['default'] MdiCellphoneMessage: typeof import('~icons/mdi/cellphone-message')['default']
MdiChat: typeof import('~icons/mdi/chat')['default'] MdiChat: typeof import('~icons/mdi/chat')['default']
@ -143,6 +143,7 @@ declare module '@vue/runtime-core' {
MdiCommentTextOutline: typeof import('~icons/mdi/comment-text-outline')['default'] MdiCommentTextOutline: typeof import('~icons/mdi/comment-text-outline')['default']
MdiContentCopy: typeof import('~icons/mdi/content-copy')['default'] MdiContentCopy: typeof import('~icons/mdi/content-copy')['default']
MdiContentSave: typeof import('~icons/mdi/content-save')['default'] MdiContentSave: typeof import('~icons/mdi/content-save')['default']
MdiContentSaveEdit: typeof import('~icons/mdi/content-save-edit')['default']
MdiCurrencyUsd: typeof import('~icons/mdi/currency-usd')['default'] MdiCurrencyUsd: typeof import('~icons/mdi/currency-usd')['default']
MdiDatabaseOutline: typeof import('~icons/mdi/database-outline')['default'] MdiDatabaseOutline: typeof import('~icons/mdi/database-outline')['default']
MdiDatabaseSync: typeof import('~icons/mdi/database-sync')['default'] MdiDatabaseSync: typeof import('~icons/mdi/database-sync')['default']
@ -200,6 +201,7 @@ declare module '@vue/runtime-core' {
MdiPlus: typeof import('~icons/mdi/plus')['default'] MdiPlus: typeof import('~icons/mdi/plus')['default']
MdiPlusCircleOutline: typeof import('~icons/mdi/plus-circle-outline')['default'] MdiPlusCircleOutline: typeof import('~icons/mdi/plus-circle-outline')['default']
MdiPlusOutline: typeof import('~icons/mdi/plus-outline')['default'] MdiPlusOutline: typeof import('~icons/mdi/plus-outline')['default']
MdiPlusThick: typeof import('~icons/mdi/plus-thick')['default']
MdiReddit: typeof import('~icons/mdi/reddit')['default'] MdiReddit: typeof import('~icons/mdi/reddit')['default']
MdiRefresh: typeof import('~icons/mdi/refresh')['default'] MdiRefresh: typeof import('~icons/mdi/refresh')['default']
MdiReload: typeof import('~icons/mdi/reload')['default'] MdiReload: typeof import('~icons/mdi/reload')['default']

142
packages/nc-gui/components/cell/MultiSelect.vue

@ -1,19 +1,23 @@
<script lang="ts" setup> <script lang="ts" setup>
import { message } from 'ant-design-vue'
import tinycolor from 'tinycolor2' import tinycolor from 'tinycolor2'
import type { Select as AntSelect } from 'ant-design-vue' import type { Select as AntSelect } from 'ant-design-vue'
import type { SelectOptionType, SelectOptionsType } from 'nocodb-sdk' import type { SelectOptionType, SelectOptionsType } from 'nocodb-sdk'
import { import {
ActiveCellInj, ActiveCellInj,
ColumnInj, ColumnInj,
EditModeInj,
IsKanbanInj, IsKanbanInj,
ReadonlyInj, ReadonlyInj,
computed, computed,
enumColor,
extractSdkResponseErrorMsg,
h, h,
inject, inject,
onMounted, onMounted,
reactive,
ref, ref,
useEventListener, useEventListener,
useMetas,
useProject, useProject,
useSelectedCellKeyupListener, useSelectedCellKeyupListener,
watch, watch,
@ -39,6 +43,8 @@ const active = inject(ActiveCellInj, ref(false))
const editable = inject(EditModeInj, ref(false)) const editable = inject(EditModeInj, ref(false))
const isPublic = inject(IsPublicInj, ref(false))
const selectedIds = ref<string[]>([]) const selectedIds = ref<string[]>([])
const aselect = ref<typeof AntSelect>() const aselect = ref<typeof AntSelect>()
@ -47,7 +53,17 @@ const isOpen = ref(false)
const isKanban = inject(IsKanbanInj, ref(false)) const isKanban = inject(IsKanbanInj, ref(false))
const options = computed<SelectOptionType[]>(() => { const searchVal = ref<string | null>()
const { $api } = useNuxtApp()
const { getMeta } = useMetas()
// a variable to keep newly created options value
// temporary until it's add the option to column meta
const tempSelectedOptsState = reactive<string[]>([])
const options = computed<(SelectOptionType & { value?: string })[]>(() => {
if (column?.value.colOptions) { if (column?.value.colOptions) {
const opts = column.value.colOptions const opts = column.value.colOptions
? (column.value.colOptions as SelectOptionsType).options.filter((el: SelectOptionType) => el.title !== '') || [] ? (column.value.colOptions as SelectOptionsType).options.filter((el: SelectOptionType) => el.title !== '') || []
@ -55,21 +71,35 @@ const options = computed<SelectOptionType[]>(() => {
for (const op of opts.filter((el: SelectOptionType) => el.order === null)) { for (const op of opts.filter((el: SelectOptionType) => el.order === null)) {
op.title = op.title?.replace(/^'/, '').replace(/'$/, '') op.title = op.title?.replace(/^'/, '').replace(/'$/, '')
} }
return opts return opts.map((o: SelectOptionType) => ({ ...o, value: o.title }))
} }
return [] return []
}) })
const isOptionMissing = computed(() => {
return (options.value ?? []).every((op) => op.title !== searchVal.value)
})
const vModel = computed({ const vModel = computed({
get: () => get: () => {
selectedIds.value.reduce((acc, id) => { const selected = selectedIds.value.reduce((acc, id) => {
const title = options.value.find((op) => op.id === id)?.title const title = (options.value.find((op) => op.id === id) || options.value.find((op) => op.title === id))?.title
if (title) acc.push(title) if (title) acc.push(title)
return acc return acc
}, [] as string[]), }, [] as string[])
set: (val) => emit('update:modelValue', val.length === 0 ? null : val.join(',')),
if (tempSelectedOptsState.length) selected.push(...tempSelectedOptsState)
return selected
},
set: (val) => {
if (isOptionMissing.value && val.length && val[val.length - 1] === searchVal.value) {
return addIfMissingAndSave()
}
emit('update:modelValue', val.length === 0 ? null : val.join(','))
},
}) })
const selectedTitles = computed(() => const selectedTitles = computed(() =>
@ -97,9 +127,10 @@ const handleClose = (e: MouseEvent) => {
onMounted(() => { onMounted(() => {
selectedIds.value = selectedTitles.value.flatMap((el) => { selectedIds.value = selectedTitles.value.flatMap((el) => {
const item = options.value.find((op) => op.title === el)?.id const item = options.value.find((op) => op.title === el)
if (item) { const itemIdOrTitle = item?.id || item?.title
return [item] if (itemIdOrTitle) {
return [itemIdOrTitle]
} }
return [] return []
@ -111,10 +142,10 @@ useEventListener(document, 'click', handleClose)
watch( watch(
() => modelValue, () => modelValue,
() => { () => {
selectedIds.value = selectedIds.value = selectedTitles.value.flatMap((el) => { selectedIds.value = selectedTitles.value.flatMap((el) => {
const item = options.value.find((op) => op.title === el)?.id const item = options.value.find((op) => op.title === el)
if (item) { if (item && (item.id || item.title)) {
return [item] return [(item.id || item.title)!]
} }
return [] return []
@ -140,8 +171,65 @@ useSelectedCellKeyupListener(active, (e) => {
isOpen.value = true isOpen.value = true
} }
break break
default:
isOpen.value = true
break
} }
}) })
const activeOptCreateInProgress = ref(0)
async function addIfMissingAndSave() {
if (!searchVal.value || isPublic.value) return false
try {
tempSelectedOptsState.push(searchVal.value)
const newOptValue = searchVal?.value
searchVal.value = ''
activeOptCreateInProgress.value++
if (newOptValue && !options.value.some((o) => o.title === newOptValue)) {
const newOptions = [...options.value]
newOptions.push({
title: newOptValue,
value: newOptValue,
color: enumColor.light[(options.value.length + 1) % enumColor.light.length],
})
column.value.colOptions = { options: newOptions.map(({ value: _, ...rest }) => rest) }
await $api.dbTableColumn.update((column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), {
...column.value,
})
activeOptCreateInProgress.value--
if (!activeOptCreateInProgress.value) {
await getMeta(column.value.fk_model_id!, true)
vModel.value = [...vModel.value]
tempSelectedOptsState.splice(0, tempSelectedOptsState.length)
}
} else {
activeOptCreateInProgress.value--
}
} catch (e) {
// todo: handle error
console.log(e)
activeOptCreateInProgress.value--
message.error(await extractSdkResponseErrorMsg(e))
}
}
const search = () => {
searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value
}
const onTagClick = (e: Event, onClose: Function) => {
// check clicked element is remove icon
if (
(e.target as HTMLElement)?.classList.contains('ant-tag-close-icon') ||
(e.target as HTMLElement)?.closest('.ant-tag-close-icon')
) {
e.stopPropagation()
onClose()
}
}
</script> </script>
<template> <template>
@ -152,17 +240,20 @@ useSelectedCellKeyupListener(active, (e) => {
mode="multiple" mode="multiple"
class="w-full" class="w-full"
:bordered="false" :bordered="false"
clear-icon
:show-arrow="!readOnly" :show-arrow="!readOnly"
:show-search="false" :show-search="active || editable"
:open="isOpen && (active || editable)"
:disabled="readOnly" :disabled="readOnly"
:class="{ '!ml-[-8px]': readOnly }" :class="{ '!ml-[-8px]': readOnly }"
:dropdown-class-name="`nc-dropdown-multi-select-cell ${isOpen ? 'active' : ''}`" :dropdown-class-name="`nc-dropdown-multi-select-cell ${isOpen ? 'active' : ''}`"
@keydown.enter.stop @search="search"
@keydown.stop
@click="isOpen = (active || editable) && !isOpen" @click="isOpen = (active || editable) && !isOpen"
> >
<a-select-option <a-select-option
v-for="op of options" v-for="op of options"
:key="op.id" :key="op.id || op.title"
:value="op.title" :value="op.title"
:data-testid="`select-option-${column.title}-${rowIndex}`" :data-testid="`select-option-${column.title}-${rowIndex}`"
@click.stop @click.stop
@ -182,14 +273,24 @@ useSelectedCellKeyupListener(active, (e) => {
</a-tag> </a-tag>
</a-select-option> </a-select-option>
<a-select-option v-if="searchVal && isOptionMissing && !isPublic" :key="searchVal" :value="searchVal">
<div class="flex gap-2 text-gray-500 items-center h-full">
<MdiPlusThick class="min-w-4" />
<div class="text-xs whitespace-normal">
Create new option named <strong>{{ searchVal }}</strong>
</div>
</div>
</a-select-option>
<template #tagRender="{ value: val, onClose }"> <template #tagRender="{ value: val, onClose }">
<a-tag <a-tag
v-if="options.find((el) => el.title === val)" v-if="options.find((el) => el.title === val)"
class="rounded-tag" class="rounded-tag nc-selected-option"
:style="{ display: 'flex', alignItems: 'center' }" :style="{ display: 'flex', alignItems: 'center' }"
:color="options.find((el) => el.title === val)?.color" :color="options.find((el) => el.title === val)?.color"
:closable="(active || editable) && (vModel.length > 1 || !column?.rqd)" :closable="(active || editable) && (vModel.length > 1 || !column?.rqd)"
:close-icon="h(MdiCloseCircle, { class: ['ms-close-icon'] })" :close-icon="h(MdiCloseCircle, { class: ['ms-close-icon'] })"
@click="onTagClick($event, onClose)"
@close="onClose" @close="onClose"
> >
<span <span
@ -255,6 +356,3 @@ useSelectedCellKeyupListener(active, (e) => {
@apply "flex overflow-hidden"; @apply "flex overflow-hidden";
} }
</style> </style>
<!--
-->

7
packages/nc-gui/components/cell/Percent.vue

@ -1,4 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import type { VNodeRef } from '@vue/runtime-core'
import { EditModeInj, inject, useVModel } from '#imports' import { EditModeInj, inject, useVModel } from '#imports'
interface Props { interface Props {
@ -12,15 +13,21 @@ const emits = defineEmits(['update:modelValue'])
const editEnabled = inject(EditModeInj) const editEnabled = inject(EditModeInj)
const vModel = useVModel(props, 'modelValue', emits) const vModel = useVModel(props, 'modelValue', emits)
const focus: VNodeRef = (el) => {
;(el as HTMLInputElement)?.focus()
}
</script> </script>
<template> <template>
<input <input
v-if="editEnabled" v-if="editEnabled"
:ref="focus"
v-model="vModel" v-model="vModel"
class="w-full !border-none text-base" class="w-full !border-none text-base"
:class="{ '!px-2': editEnabled }" :class="{ '!px-2': editEnabled }"
type="number" type="number"
@blur="editEnabled = false"
@keydown.down.stop @keydown.down.stop
@keydown.left.stop @keydown.left.stop
@keydown.right.stop @keydown.right.stop

111
packages/nc-gui/components/cell/SingleSelect.vue

@ -1,4 +1,5 @@
<script lang="ts" setup> <script lang="ts" setup>
import { message } from 'ant-design-vue'
import tinycolor from 'tinycolor2' import tinycolor from 'tinycolor2'
import type { Select as AntSelect } from 'ant-design-vue' import type { Select as AntSelect } from 'ant-design-vue'
import type { SelectOptionType } from 'nocodb-sdk' import type { SelectOptionType } from 'nocodb-sdk'
@ -9,12 +10,13 @@ import {
IsKanbanInj, IsKanbanInj,
ReadonlyInj, ReadonlyInj,
computed, computed,
enumColor,
extractSdkResponseErrorMsg,
inject, inject,
ref, ref,
useEventListener, useSelectedCellKeyupListener,
watch, watch,
} from '#imports' } from '#imports'
import { useSelectedCellKeyupListener } from '~/composables/useSelectedCellKeyupListener'
interface Props { interface Props {
modelValue?: string | undefined modelValue?: string | undefined
@ -39,12 +41,19 @@ const isOpen = ref(false)
const isKanban = inject(IsKanbanInj, ref(false)) const isKanban = inject(IsKanbanInj, ref(false))
const vModel = computed({ const isPublic = inject(IsPublicInj, ref(false))
get: () => modelValue,
set: (val) => emit('update:modelValue', val || null), const { $api } = useNuxtApp()
})
const searchVal = ref()
const { getMeta } = useMetas()
// a variable to keep newly created option value
// temporary until it's add the option to column meta
const tempSelectedOptState = ref<string>()
const options = computed<SelectOptionType[]>(() => { const options = computed<(SelectOptionType & { value: string })[]>(() => {
if (column?.value.colOptions) { if (column?.value.colOptions) {
const opts = column.value.colOptions const opts = column.value.colOptions
? // todo: fix colOptions type, options does not exist as a property ? // todo: fix colOptions type, options does not exist as a property
@ -53,19 +62,27 @@ const options = computed<SelectOptionType[]>(() => {
for (const op of opts.filter((el: any) => el.order === null)) { for (const op of opts.filter((el: any) => el.order === null)) {
op.title = op.title.replace(/^'/, '').replace(/'$/, '') op.title = op.title.replace(/^'/, '').replace(/'$/, '')
} }
return opts return opts.map((o: any) => ({ ...o, value: o.title }))
} }
return [] return []
}) })
const handleClose = (e: MouseEvent) => { const isOptionMissing = computed(() => {
if (aselect.value && !aselect.value.$el.contains(e.target)) { return (options.value ?? []).every((op) => op.title !== searchVal.value)
isOpen.value = false })
aselect.value.blur()
}
}
useEventListener(document, 'click', handleClose) const vModel = computed({
get: () => tempSelectedOptState.value ?? modelValue,
set: (val) => {
if (isOptionMissing.value && val === searchVal.value) {
tempSelectedOptState.value = val
return addIfMissingAndSave().finally(() => {
tempSelectedOptState.value = undefined
})
}
emit('update:modelValue', val || null)
},
})
watch(isOpen, (n, _o) => { watch(isOpen, (n, _o) => {
if (!n) { if (!n) {
@ -87,6 +104,50 @@ useSelectedCellKeyupListener(active, (e) => {
break break
} }
}) })
async function addIfMissingAndSave() {
if (!searchVal.value || isPublic.value) return false
const newOptValue = searchVal.value
searchVal.value = ''
if (newOptValue && !options.value.some((o) => o.title === newOptValue)) {
try {
options.value.push({
title: newOptValue,
value: newOptValue,
color: enumColor.light[(options.value.length + 1) % enumColor.light.length],
})
column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) }
await $api.dbTableColumn.update((column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), {
...column.value,
})
vModel.value = newOptValue
await getMeta(column.value.fk_model_id!, true)
} catch (e) {
console.log(e)
message.error(await extractSdkResponseErrorMsg(e))
}
}
}
const search = () => {
searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value
}
const toggleMenu = (e: Event) => {
// todo: refactor
// check clicked element is clear icon
if (
(e.target as HTMLElement)?.classList.contains('ant-select-clear') ||
(e.target as HTMLElement)?.closest('.ant-select-clear')
) {
vModel.value = ''
return
}
isOpen.value = (active.value || editable.value) && !isOpen.value
}
</script> </script>
<template> <template>
@ -96,13 +157,15 @@ useSelectedCellKeyupListener(active, (e) => {
class="w-full" class="w-full"
:allow-clear="!column.rqd && active" :allow-clear="!column.rqd && active"
:bordered="false" :bordered="false"
:open="isOpen" :open="isOpen && (active || editable)"
:disabled="readOnly" :disabled="readOnly"
:show-arrow="!readOnly && (active || editable || vModel === null)" :show-arrow="!readOnly && (active || editable || vModel === null)"
:dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen ? 'active' : ''}`" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen ? 'active' : ''}`"
:show-search="active || editable"
@select="isOpen = false" @select="isOpen = false"
@keydown.enter.stop @keydown.stop
@click="isOpen = (active || editable) && !isOpen" @search="search"
@click="toggleMenu"
> >
<a-select-option <a-select-option
v-for="op of options" v-for="op of options"
@ -125,6 +188,15 @@ useSelectedCellKeyupListener(active, (e) => {
</span> </span>
</a-tag> </a-tag>
</a-select-option> </a-select-option>
<a-select-option v-if="searchVal && isOptionMissing && !isPublic" :key="searchVal" :value="searchVal">
<div class="flex gap-2 text-gray-500 items-center h-full">
<MdiPlusThick class="min-w-4" />
<div class="text-xs whitespace-normal">
Create new option named <strong>{{ searchVal }}</strong>
</div>
</div>
</a-select-option>
</a-select> </a-select>
</template> </template>
@ -141,6 +213,3 @@ useSelectedCellKeyupListener(active, (e) => {
opacity: 1; opacity: 1;
} }
</style> </style>
<!--
-->

4
packages/nc-gui/components/cell/Text.vue

@ -16,7 +16,9 @@ const readonly = inject(ReadonlyInj, ref(false))
const vModel = useVModel(props, 'modelValue', emits) const vModel = useVModel(props, 'modelValue', emits)
const focus: VNodeRef = (el) => (el as HTMLInputElement)?.focus() const focus: VNodeRef = (el) => {
;(el as HTMLInputElement)?.focus()
}
</script> </script>
<template> <template>

8
packages/nc-gui/components/dlg/TableCreate.vue

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { Form, computed, onMounted, ref, useProject, useTable, useTabs, useVModel, validateTableName } from '#imports' import { Form, computed, nextTick, onMounted, ref, useProject, useTable, useTabs, useVModel, validateTableName } from '#imports'
import { TabType } from '~/lib' import { TabType } from '~/lib'
const props = defineProps<{ const props = defineProps<{
@ -89,8 +89,10 @@ const _createTable = async () => {
onMounted(() => { onMounted(() => {
generateUniqueTitle() generateUniqueTitle()
nextTick(() => {
inputEl.value?.focus() inputEl.value?.focus()
inputEl.value?.select()
})
}) })
</script> </script>

1
packages/nc-gui/components/dlg/TableRename.vue

@ -119,6 +119,7 @@ const renameTable = async () => {
await $api.dbTable.update(tableMeta.id as string, { await $api.dbTable.update(tableMeta.id as string, {
project_id: tableMeta.project_id, project_id: tableMeta.project_id,
table_name: formState.title, table_name: formState.title,
title: formState.title,
}) })
dialogShow.value = false dialogShow.value = false

2
packages/nc-gui/components/dlg/ViewCreate.vue

@ -184,7 +184,7 @@ async function onSubmit() {
<template> <template>
<a-modal v-model:visible="vModel" class="!top-[35%]" :confirm-loading="loading" wrap-class-name="nc-modal-view-create"> <a-modal v-model:visible="vModel" class="!top-[35%]" :confirm-loading="loading" wrap-class-name="nc-modal-view-create">
<template #title> <template #title>
{{ $t(`general.${selectedViewId ? 'duplicate' : 'create'}`) }} <span class="text-capitalize">{{ typeAlias }}</span> {{ $t(`general.${selectedViewId ? 'duplicate' : 'create'}`) }} <span class="capitalize">{{ typeAlias }}</span>
{{ $t('objects.view') }} {{ $t('objects.view') }}
</template> </template>

6
packages/nc-gui/components/shared-view/AskPassword.vue

@ -1,4 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import type { VNodeRef } from '@vue/runtime-core'
import type { InputPassword } from 'ant-design-vue'
import { extractSdkResponseErrorMsg, message, ref, useRoute, useSharedView, useVModel } from '#imports' import { extractSdkResponseErrorMsg, message, ref, useRoute, useSharedView, useVModel } from '#imports'
const props = defineProps<{ const props = defineProps<{
@ -24,6 +26,8 @@ const onFinish = async () => {
message.error(await extractSdkResponseErrorMsg(e)) message.error(await extractSdkResponseErrorMsg(e))
} }
} }
const focus: VNodeRef = (el: typeof InputPassword) => el?.$el?.querySelector('input').focus()
</script> </script>
<template> <template>
@ -42,7 +46,7 @@ const onFinish = async () => {
<a-form ref="formRef" :model="formState" class="mt-2" @finish="onFinish"> <a-form ref="formRef" :model="formState" class="mt-2" @finish="onFinish">
<a-form-item name="password" :rules="[{ required: true, message: 'Password is required' }]"> <a-form-item name="password" :rules="[{ required: true, message: 'Password is required' }]">
<a-input-password v-model:value="formState.password" placeholder="Enter password" /> <a-input-password :ref="focus" v-model:value="formState.password" placeholder="Enter password" />
</a-form-item> </a-form-item>
<a-button type="primary" html-type="submit">Unlock</a-button> <a-button type="primary" html-type="submit">Unlock</a-button>

3
packages/nc-gui/components/smartsheet/Cell.vue

@ -111,7 +111,6 @@ const vModel = computed({
}) })
const syncAndNavigate = (dir: NavigateDir, e: KeyboardEvent) => { const syncAndNavigate = (dir: NavigateDir, e: KeyboardEvent) => {
console.log('syncAndNavigate', e.target)
if (isJSON(column.value)) return if (isJSON(column.value)) return
if (currentRow.value.rowMeta.changed || currentRow.value.rowMeta.new) { if (currentRow.value.rowMeta.changed || currentRow.value.rowMeta.new) {
@ -136,7 +135,7 @@ const syncAndNavigate = (dir: NavigateDir, e: KeyboardEvent) => {
> >
<template v-if="column"> <template v-if="column">
<LazyCellTextArea v-if="isTextArea(column)" v-model="vModel" /> <LazyCellTextArea v-if="isTextArea(column)" v-model="vModel" />
<LazyCellCheckbox v-else-if="isBoolean(column)" v-model="vModel" /> <LazyCellCheckbox v-else-if="isBoolean(column, abstractType)" v-model="vModel" />
<LazyCellAttachment v-else-if="isAttachment(column)" v-model="vModel" :row-index="props.rowIndex" /> <LazyCellAttachment v-else-if="isAttachment(column)" v-model="vModel" :row-index="props.rowIndex" />
<LazyCellSingleSelect v-else-if="isSingleSelect(column)" v-model="vModel" :row-index="props.rowIndex" /> <LazyCellSingleSelect v-else-if="isSingleSelect(column)" v-model="vModel" :row-index="props.rowIndex" />
<LazyCellMultiSelect v-else-if="isMultiSelect(column)" v-model="vModel" :row-index="props.rowIndex" /> <LazyCellMultiSelect v-else-if="isMultiSelect(column)" v-model="vModel" :row-index="props.rowIndex" />

23
packages/nc-gui/components/smartsheet/Grid.vue

@ -423,6 +423,7 @@ onClickOutside(smartTable, (e) => {
const onNavigate = (dir: NavigateDir) => { const onNavigate = (dir: NavigateDir) => {
if (selected.row === null || selected.col === null) return if (selected.row === null || selected.col === null) return
editEnabled = false
switch (dir) { switch (dir) {
case NavigateDir.NEXT: case NavigateDir.NEXT:
if (selected.row < data.value.length - 1) { if (selected.row < data.value.length - 1) {
@ -435,8 +436,6 @@ const onNavigate = (dir: NavigateDir) => {
case NavigateDir.PREV: case NavigateDir.PREV:
if (selected.row > 0) { if (selected.row > 0) {
selected.row-- selected.row--
} else {
editEnabled = false
} }
break break
} }
@ -521,11 +520,14 @@ provide(ReloadRowDataHookInj, reloadViewDataHook)
// trigger initial data load in grid // trigger initial data load in grid
// reloadViewDataHook.trigger() // reloadViewDataHook.trigger()
const switchingTab = ref(false)
watch( watch(
view, view,
async (next, old) => { async (next, old) => {
try { try {
if (next && next.id !== old?.id) { if (next && next.id !== old?.id) {
switchingTab.value = true
// whenever tab changes or view changes save any unsaved data // whenever tab changes or view changes save any unsaved data
if (old?.id) { if (old?.id) {
const oldMeta = await getMeta(old.fk_model_id!) const oldMeta = await getMeta(old.fk_model_id!)
@ -541,6 +543,8 @@ watch(
} }
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} finally {
switchingTab.value = false
} }
}, },
{ immediate: true }, { immediate: true },
@ -707,7 +711,7 @@ watch(
@mouseover="selectBlock(rowIndex, colIndex)" @mouseover="selectBlock(rowIndex, colIndex)"
@contextmenu="showContextMenu($event, { row: rowIndex, col: colIndex })" @contextmenu="showContextMenu($event, { row: rowIndex, col: colIndex })"
> >
<div class="w-full h-full"> <div v-if="!switchingTab" class="w-full h-full">
<LazySmartsheetVirtualCell <LazySmartsheetVirtualCell
v-if="isVirtualCol(columnObj)" v-if="isVirtualCol(columnObj)"
v-model="row.row[columnObj.title]" v-model="row.row[columnObj.title]"
@ -850,8 +854,7 @@ watch(
text-overflow: ellipsis; text-overflow: ellipsis;
} }
td.active::after, td.active::after {
td.active::before {
content: ''; content: '';
position: absolute; position: absolute;
z-index: 3; z-index: 3;
@ -864,12 +867,14 @@ watch(
// todo: replace with css variable // todo: replace with css variable
td.active::after { td.active::after {
@apply border-2 border-solid border-primary; @apply border-2 border-solid text-primary border-current bg-primary bg-opacity-5;
} }
td.active::before { //td.active::before {
@apply bg-primary bg-opacity-5; // content: '';
} // z-index:4;
// @apply absolute !w-[10px] !h-[10px] !right-[-5px] !bottom-[-5px] bg-primary;
//}
} }
:deep { :deep {

7
packages/nc-gui/components/smartsheet/column/EditOrAdd.vue

@ -1,4 +1,5 @@
<script lang="ts" setup> <script lang="ts" setup>
import { useEventListener } from '@vueuse/core'
import { UITypes, isVirtualCol } from 'nocodb-sdk' import { UITypes, isVirtualCol } from 'nocodb-sdk'
import { import {
IsFormInj, IsFormInj,
@ -116,6 +117,12 @@ onMounted(() => {
formState.value.column_name = formState.value?.title formState.value.column_name = formState.value?.title
} }
}) })
useEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape') {
emit('cancel')
}
})
</script> </script>
<template> <template>

4
packages/nc-gui/components/smartsheet/column/SelectOptions.vue

@ -163,12 +163,12 @@ watch(inputs, () => {
v-model:value="element.title" v-model:value="element.title"
class="caption" class="caption"
:data-testid="`select-column-option-input-${index}`" :data-testid="`select-column-option-input-${index}`"
@keydown.enter.prevent="element.title?.trim() && addNewOption()"
@change="optionChanged(element.id)" @change="optionChanged(element.id)"
/> />
<MdiClose <MdiClose
class="ml-2 hover:!text-black" class="ml-2 hover:!text-black-500 text-gray-500 cursor-pointer"
:style="{ color: 'red' }"
:data-testid="`select-column-option-remove-${index}`" :data-testid="`select-column-option-remove-${index}`"
@click="removeOption(index)" @click="removeOption(index)"
/> />

42
packages/nc-gui/components/smartsheet/expanded-form/Header.vue

@ -25,6 +25,8 @@ const { isUIAllowed } = useUIPermission()
const reloadTrigger = inject(ReloadRowDataHookInj, createEventHook()) const reloadTrigger = inject(ReloadRowDataHookInj, createEventHook())
const saveRowAndStay = ref(0)
const save = async () => { const save = async () => {
if (isNew.value) { if (isNew.value) {
const data = await _save(state.value) const data = await _save(state.value)
@ -34,6 +36,9 @@ const save = async () => {
await _save() await _save()
reloadTrigger?.trigger() reloadTrigger?.trigger()
} }
if (!saveRowAndStay.value) {
emit('cancel')
}
} }
// todo: accept as a prop / inject // todo: accept as a prop / inject
@ -101,14 +106,39 @@ const copyRecordUrl = () => {
</a-tooltip> </a-tooltip>
<a-button class="!text mx-1 nc-expand-form-close-btn" @click="emit('cancel')"> <a-button class="!text mx-1 nc-expand-form-close-btn" @click="emit('cancel')">
<!-- Cancel --> <div class="flex items-center">
{{ $t('general.cancel') }} <MdiCloseCircleOutline class="mr-1" />
<!-- Close -->
{{ $t('general.close') }}
</div>
</a-button> </a-button>
<a-button :disabled="!isUIAllowed('tableRowUpdate')" type="primary" class="mx-1" @click="save"> <a-dropdown-button class="nc-expand-form-save-btn" type="primary" :disabled="!isUIAllowed('tableRowUpdate')" @click="save">
<!-- Save Row --> <template #overlay>
{{ $t('activity.saveRow') }} <a-menu class="nc-expand-form-save-dropdown-menu">
</a-button> <a-menu-item key="0" class="!py-2 flex gap-2" @click="saveRowAndStay = 0">
<div class="flex items-center">
<MdiContentSave class="mr-1" />
{{ $t('activity.saveAndExit') }}
</div>
</a-menu-item>
<a-menu-item key="1" class="!py-2 flex gap-2 items-center" @click="saveRowAndStay = 1">
<div class="flex items-center">
<MdiContentSaveEdit class="mr-1" />
{{ $t('activity.saveAndStay') }}
</div>
</a-menu-item>
</a-menu>
</template>
<div v-if="saveRowAndStay === 0" class="flex items-center">
<MdiContentSave class="mr-1" />
{{ $t('activity.saveAndExit') }}
</div>
<div v-if="saveRowAndStay === 1" class="flex items-center">
<MdiContentSaveEdit class="mr-1" />
{{ $t('activity.saveAndStay') }}
</div>
</a-dropdown-button>
</div> </div>
</template> </template>

10
packages/nc-gui/components/smartsheet/expanded-form/index.vue

@ -121,6 +121,12 @@ if (isKanban.value) {
} }
} }
} }
const cellWrapperEl = (wrapperEl: HTMLElement) => {
nextTick(() => {
;(wrapperEl?.querySelector('input,select,textarea') as HTMLInputElement)?.focus()
})
}
</script> </script>
<script lang="ts"> <script lang="ts">
@ -146,7 +152,7 @@ export default {
<div class="flex-1 overflow-auto scrollbar-thin-dull nc-form-fields-container"> <div class="flex-1 overflow-auto scrollbar-thin-dull nc-form-fields-container">
<div class="w-[500px] mx-auto"> <div class="w-[500px] mx-auto">
<div <div
v-for="col of fields" v-for="(col, i) of fields"
v-show="!isVirtualCol(col) || !isNew || col.uidt === UITypes.LinkToAnotherRecord" v-show="!isVirtualCol(col) || !isNew || col.uidt === UITypes.LinkToAnotherRecord"
:key="col.title" :key="col.title"
class="mt-2 py-2" class="mt-2 py-2"
@ -157,7 +163,7 @@ export default {
<LazySmartsheetHeaderCell v-else :column="col" /> <LazySmartsheetHeaderCell v-else :column="col" />
<div class="!bg-white rounded px-1 min-h-[35px] flex items-center mt-2"> <div :ref="i ? null : cellWrapperEl" class="!bg-white rounded px-1 min-h-[35px] flex items-center mt-2">
<LazySmartsheetVirtualCell v-if="isVirtualCol(col)" v-model="row.row[col.title]" :row="row" :column="col" /> <LazySmartsheetVirtualCell v-if="isVirtualCol(col)" v-model="row.row[col.title]" :row="row" :column="col" />
<LazySmartsheetCell <LazySmartsheetCell

2
packages/nc-gui/components/smartsheet/header/CellIcon.ts

@ -68,7 +68,7 @@ const renderIcon = (column: ColumnType, abstractType: any) => {
return MultiSelectIcon return MultiSelectIcon
} else if (isSingleSelect(column)) { } else if (isSingleSelect(column)) {
return SingleSelectIcon return SingleSelectIcon
} else if (isBoolean(column)) { } else if (isBoolean(column, abstractType)) {
return BooleanIcon return BooleanIcon
} else if (isTextArea(column)) { } else if (isTextArea(column)) {
return TextAreaIcon return TextAreaIcon

7
packages/nc-gui/components/smartsheet/toolbar/ColumnFilterMenu.vue

@ -8,6 +8,7 @@ import {
inject, inject,
ref, ref,
useGlobal, useGlobal,
useMenuCloseOnEsc,
useNuxtApp, useNuxtApp,
useSmartsheetStoreOrThrow, useSmartsheetStoreOrThrow,
useViewFilters, useViewFilters,
@ -62,10 +63,14 @@ const filterAutoSaveLoc = computed({
filterAutoSave.value = val filterAutoSave.value = val
}, },
}) })
const open = ref(false)
useMenuCloseOnEsc(open)
</script> </script>
<template> <template>
<a-dropdown :trigger="['click']" overlay-class-name="nc-dropdown-filter-menu"> <a-dropdown v-model:visible="open" :trigger="['click']" overlay-class-name="nc-dropdown-filter-menu">
<div :class="{ 'nc-badge nc-active-btn': filtersLength }"> <div :class="{ 'nc-badge nc-active-btn': filtersLength }">
<a-button v-e="['c:filter']" class="nc-filter-menu-btn nc-toolbar-btn txt-sm" :disabled="isLocked"> <a-button v-e="['c:filter']" class="nc-filter-menu-btn nc-toolbar-btn txt-sm" :disabled="isLocked">
<div class="flex items-center gap-1"> <div class="flex items-center gap-1">

7
packages/nc-gui/components/smartsheet/toolbar/FieldsMenu.vue

@ -14,6 +14,7 @@ import {
inject, inject,
ref, ref,
resolveComponent, resolveComponent,
useMenuCloseOnEsc,
useNuxtApp, useNuxtApp,
useViewColumns, useViewColumns,
watch, watch,
@ -119,10 +120,14 @@ const getIcon = (c: ColumnType) =>
h(isVirtualCol(c) ? resolveComponent('SmartsheetHeaderVirtualCellIcon') : resolveComponent('SmartsheetHeaderCellIcon'), { h(isVirtualCol(c) ? resolveComponent('SmartsheetHeaderVirtualCellIcon') : resolveComponent('SmartsheetHeaderCellIcon'), {
columnMeta: c, columnMeta: c,
}) })
const open = ref(false)
useMenuCloseOnEsc(open)
</script> </script>
<template> <template>
<a-dropdown :trigger="['click']" overlay-class-name="nc-dropdown-fields-menu"> <a-dropdown v-model:visible="open" :trigger="['click']" overlay-class-name="nc-dropdown-fields-menu">
<div :class="{ 'nc-badge nc-active-btn': isAnyFieldHidden }"> <div :class="{ 'nc-badge nc-active-btn': isAnyFieldHidden }">
<a-button v-e="['c:fields']" class="nc-fields-menu-btn nc-toolbar-btn" :disabled="isLocked"> <a-button v-e="['c:fields']" class="nc-fields-menu-btn nc-toolbar-btn" :disabled="isLocked">
<div class="flex items-center gap-1"> <div class="flex items-center gap-1">

16
packages/nc-gui/components/smartsheet/toolbar/KanbanStackEditOrAdd.vue

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { IsLockedInj, IsPublicInj, useKanbanViewStoreOrThrow } from '#imports' import { IsLockedInj, IsPublicInj, useKanbanViewStoreOrThrow, useMenuCloseOnEsc } from '#imports'
const { isUIAllowed } = useUIPermission() const { isUIAllowed } = useUIPermission()
@ -7,12 +7,14 @@ const { groupingFieldColumn } = useKanbanViewStoreOrThrow()
const isLocked = inject(IsLockedInj, ref(false)) const isLocked = inject(IsLockedInj, ref(false))
const addOrEditStackDropdown = ref(false)
const IsPublic = inject(IsPublicInj, ref(false)) const IsPublic = inject(IsPublicInj, ref(false))
const open = ref(false)
useMenuCloseOnEsc(open)
const handleSubmit = async () => { const handleSubmit = async () => {
addOrEditStackDropdown.value = false open.value = false
} }
provide(IsKanbanInj, ref(true)) provide(IsKanbanInj, ref(true))
@ -21,7 +23,7 @@ provide(IsKanbanInj, ref(true))
<template> <template>
<a-dropdown <a-dropdown
v-if="!IsPublic && isUIAllowed('edit-column')" v-if="!IsPublic && isUIAllowed('edit-column')"
v-model:visible="addOrEditStackDropdown" v-model:visible="open"
:trigger="['click']" :trigger="['click']"
overlay-class-name="nc-dropdown-kanban-add-edit-stack-menu" overlay-class-name="nc-dropdown-kanban-add-edit-stack-menu"
> >
@ -42,10 +44,10 @@ provide(IsKanbanInj, ref(true))
</div> </div>
<template #overlay> <template #overlay>
<LazySmartsheetColumnEditOrAddProvider <LazySmartsheetColumnEditOrAddProvider
v-if="addOrEditStackDropdown" v-if="open"
:column="groupingFieldColumn" :column="groupingFieldColumn"
@submit="handleSubmit" @submit="handleSubmit"
@cancel="addOrEditStackDropdown = false" @cancel="open = false"
@click.stop @click.stop
@keydown.stop @keydown.stop
/> />

108
packages/nc-gui/components/smartsheet/toolbar/ShareView.vue

@ -5,12 +5,12 @@ import tinycolor from 'tinycolor2'
import { import {
computed, computed,
extractSdkResponseErrorMsg, extractSdkResponseErrorMsg,
isRtlLang,
message, message,
projectThemeColors, projectThemeColors,
ref, ref,
useCopy, useCopy,
useDashboard, useDashboard,
useDebounceFn,
useI18n, useI18n,
useNuxtApp, useNuxtApp,
useProject, useProject,
@ -48,12 +48,12 @@ const withRTL = computed({
}, },
}) })
const transitionDuration = computed({ // const transitionDuration = computed({
get: () => shared.value.meta.transitionDuration || 250, // get: () => shared.value.meta.transitionDuration || 50,
set: (duration) => { // set: (duration) => {
shared.value.meta = { ...shared.value.meta, transitionDuration: duration > 5000 ? 5000 : duration } // shared.value.meta = { ...shared.value.meta, transitionDuration: duration > 5000 ? 5000 : duration }
}, // },
}) // })
const allowCSVDownload = computed({ const allowCSVDownload = computed({
get: () => !!shared.value.meta.allowCSVDownload, get: () => !!shared.value.meta.allowCSVDownload,
@ -131,7 +131,7 @@ async function saveTheme() {
$e(`a:view:share:${viewTheme.value ? 'enable' : 'disable'}-theme`) $e(`a:view:share:${viewTheme.value ? 'enable' : 'disable'}-theme`)
} }
const saveTransitionDuration = useDebounceFn(updateSharedViewMeta, 1000, { maxWait: 2000 }) // const saveTransitionDuration = useDebounceFn(updateSharedViewMeta, 1000, { maxWait: 2000 })
async function updateSharedViewMeta() { async function updateSharedViewMeta() {
try { try {
@ -192,6 +192,10 @@ watch(passwordProtected, (value) => {
saveShareLinkPassword() saveShareLinkPassword()
} }
}) })
const { locale } = useI18n()
const isRtl = computed(() => isRtlLang(locale.value as any))
</script> </script>
<template> <template>
@ -248,7 +252,7 @@ watch(passwordProtected, (value) => {
Use Survey Mode Use Survey Mode
</a-checkbox> </a-checkbox>
<Transition name="layout" mode="out-in"> <!-- <Transition name="layout" mode="out-in">
<div v-if="surveyMode" class="flex flex-col justify-center pl-6"> <div v-if="surveyMode" class="flex flex-col justify-center pl-6">
<a-form-item class="!my-1" :has-feedback="false" name="transitionDuration"> <a-form-item class="!my-1" :has-feedback="false" name="transitionDuration">
<template #label> <template #label>
@ -264,46 +268,7 @@ watch(passwordProtected, (value) => {
/> />
</a-form-item> </a-form-item>
</div> </div>
</Transition> </Transition> -->
</div>
<div>
<!-- todo: i18n -->
<a-checkbox
v-if="shared.type === ViewTypes.FORM"
v-model:checked="viewTheme"
data-testid="nc-modal-share-view__with-theme"
class="!text-sm"
>
Use Theme
</a-checkbox>
<Transition name="layout" mode="out-in">
<div v-if="viewTheme" class="flex pl-6">
<LazyGeneralColorPicker
data-testid="nc-modal-share-view__theme-picker"
class="!p-0"
:model-value="shared.meta.theme?.primaryColor"
:colors="projectThemeColors"
:row-size="9"
:advanced="false"
@input="onChangeTheme"
/>
</div>
</Transition>
</div>
<div>
<!-- use RTL orientation in form - todo: i18n -->
<a-checkbox
v-if="shared.type === ViewTypes.FORM"
v-model:checked="withRTL"
data-testid="nc-modal-share-view__locale"
class="!text-sm"
>
<!-- todo i18n -->
RTL Orientation
</a-checkbox>
</div> </div>
<div> <div>
@ -339,20 +304,45 @@ watch(passwordProtected, (value) => {
</Transition> </Transition>
</div> </div>
<div> <div
v-if="
shared && (shared.type === ViewTypes.GRID || shared.type === ViewTypes.KANBAN || shared.type === ViewTypes.GALLERY)
"
>
<!-- Allow Download --> <!-- Allow Download -->
<a-checkbox <a-checkbox v-model:checked="allowCSVDownload" data-testid="nc-modal-share-view__with-csv-download" class="!text-sm">
v-if="
shared &&
(shared.type === ViewTypes.GRID || shared.type === ViewTypes.KANBAN || shared.type === ViewTypes.GALLERY)
"
v-model:checked="allowCSVDownload"
data-testid="nc-modal-share-view__with-csv-download"
class="!text-sm"
>
{{ $t('labels.downloadAllowed') }} {{ $t('labels.downloadAllowed') }}
</a-checkbox> </a-checkbox>
</div> </div>
<div v-if="shared.type === ViewTypes.FORM">
<!-- todo: i18n -->
<a-checkbox v-model:checked="viewTheme" data-testid="nc-modal-share-view__with-theme" class="!text-sm">
Use Theme
</a-checkbox>
<Transition name="layout" mode="out-in">
<div v-if="viewTheme" class="flex pl-6">
<LazyGeneralColorPicker
data-testid="nc-modal-share-view__theme-picker"
class="!p-0"
:model-value="shared.meta.theme?.primaryColor"
:colors="projectThemeColors"
:row-size="9"
:advanced="false"
@input="onChangeTheme"
/>
</div>
</Transition>
</div>
<div v-if="shared.type === ViewTypes.FORM && isRtl">
<!-- use RTL orientation in form - todo: i18n -->
<a-checkbox v-model:checked="withRTL" data-testid="nc-modal-share-view__locale" class="!text-sm">
<!-- todo i18n -->
RTL Orientation
</a-checkbox>
</div>
</div> </div>
</div> </div>
</a-modal> </a-modal>

7
packages/nc-gui/components/smartsheet/toolbar/SortListMenu.vue

@ -9,6 +9,7 @@ import {
getSortDirectionOptions, getSortDirectionOptions,
inject, inject,
ref, ref,
useMenuCloseOnEsc,
useViewSorts, useViewSorts,
watch, watch,
} from '#imports' } from '#imports'
@ -37,10 +38,14 @@ watch(
}, },
{ immediate: true }, { immediate: true },
) )
const open = ref(false)
useMenuCloseOnEsc(open)
</script> </script>
<template> <template>
<a-dropdown offset-y class="" :trigger="['click']" overlay-class-name="nc-dropdown-sort-menu"> <a-dropdown v-model:visible="open" offset-y class="" :trigger="['click']" overlay-class-name="nc-dropdown-sort-menu">
<div :class="{ 'nc-badge nc-active-btn': sorts?.length }"> <div :class="{ 'nc-badge nc-active-btn': sorts?.length }">
<a-button v-e="['c:sort']" class="nc-sort-menu-btn nc-toolbar-btn" :disabled="isLocked"> <a-button v-e="['c:sort']" class="nc-sort-menu-btn nc-toolbar-btn" :disabled="isLocked">
<div class="flex items-center gap-1"> <div class="flex items-center gap-1">

11
packages/nc-gui/components/smartsheet/toolbar/StackedBy.vue

@ -12,6 +12,7 @@ import {
inject, inject,
ref, ref,
useKanbanViewStoreOrThrow, useKanbanViewStoreOrThrow,
useMenuCloseOnEsc,
useViewColumns, useViewColumns,
watch, watch,
} from '#imports' } from '#imports'
@ -30,7 +31,9 @@ const { fields, loadViewColumns, metaColumnById } = useViewColumns(activeView, m
const { kanbanMetaData, loadKanbanMeta, loadKanbanData, updateKanbanMeta, groupingField } = useKanbanViewStoreOrThrow() const { kanbanMetaData, loadKanbanMeta, loadKanbanData, updateKanbanMeta, groupingField } = useKanbanViewStoreOrThrow()
const stackedByDropdown = ref(false) const open = ref(false)
useMenuCloseOnEsc(open)
watch( watch(
() => activeView.value?.id, () => activeView.value?.id,
@ -68,14 +71,14 @@ const singleSelectFieldOptions = computed<SelectProps['options']>(() => {
}) })
const handleChange = () => { const handleChange = () => {
stackedByDropdown.value = false open.value = false
} }
</script> </script>
<template> <template>
<a-dropdown <a-dropdown
v-if="!IsPublic" v-if="!IsPublic"
v-model:visible="stackedByDropdown" v-model:visible="open"
:trigger="['click']" :trigger="['click']"
overlay-class-name="nc-dropdown-kanban-stacked-by-menu" overlay-class-name="nc-dropdown-kanban-stacked-by-menu"
> >
@ -97,7 +100,7 @@ const handleChange = () => {
</div> </div>
<template #overlay> <template #overlay>
<div <div
v-if="stackedByDropdown" v-if="open"
class="p-3 min-w-[280px] bg-gray-50 shadow-lg nc-table-toolbar-menu max-h-[max(80vh,500px)] overflow-auto !border" class="p-3 min-w-[280px] bg-gray-50 shadow-lg nc-table-toolbar-menu max-h-[max(80vh,500px)] overflow-auto !border"
@click.stop @click.stop
> >

9
packages/nc-gui/components/smartsheet/toolbar/ViewActions.vue

@ -8,6 +8,7 @@ import {
message, message,
ref, ref,
useI18n, useI18n,
useMenuCloseOnEsc,
useNuxtApp, useNuxtApp,
useProject, useProject,
useSmartsheetStoreOrThrow, useSmartsheetStoreOrThrow,
@ -79,11 +80,15 @@ async function changeLockType(type: LockType) {
} }
const { isSqlView } = useSmartsheetStoreOrThrow() const { isSqlView } = useSmartsheetStoreOrThrow()
const open = ref(false)
useMenuCloseOnEsc(open)
</script> </script>
<template> <template>
<div> <div>
<a-dropdown :trigger="['click']" overlay-class-name="nc-dropdown-actions-menu"> <a-dropdown v-model:visible="open" :trigger="['click']" overlay-class-name="nc-dropdown-actions-menu">
<a-button v-e="['c:actions']" class="nc-actions-menu-btn nc-toolbar-btn"> <a-button v-e="['c:actions']" class="nc-actions-menu-btn nc-toolbar-btn">
<div class="flex gap-2 items-center"> <div class="flex gap-2 items-center">
<component <component
@ -103,7 +108,7 @@ const { isSqlView } = useSmartsheetStoreOrThrow()
</a-button> </a-button>
<template #overlay> <template #overlay>
<a-menu class="ml-6 !text-sm !px-0 !py-2 !rounded" data-testid="toolbar-actions"> <a-menu class="ml-6 !text-sm !px-0 !py-2 !rounded" data-testid="toolbar-actions" @click="open = false">
<a-menu-item-group> <a-menu-item-group>
<a-sub-menu <a-sub-menu
v-if="isUIAllowed('view-type')" v-if="isUIAllowed('view-type')"

6
packages/nc-gui/components/tabs/auth/user-management/UsersModal.vue

@ -1,4 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import type { Input } from 'ant-design-vue'
import { import {
Form, Form,
computed, computed,
@ -133,6 +134,10 @@ const clickInviteMore = () => {
usersData.role = ProjectRole.Viewer usersData.role = ProjectRole.Viewer
usersData.emails = undefined usersData.emails = undefined
} }
const emailField = (inputEl: typeof Input) => {
inputEl?.$el?.focus()
}
</script> </script>
<template> <template>
@ -222,6 +227,7 @@ const clickInviteMore = () => {
<div class="ml-1 mb-1 text-xs text-gray-500">{{ $t('datatype.Email') }}:</div> <div class="ml-1 mb-1 text-xs text-gray-500">{{ $t('datatype.Email') }}:</div>
<a-input <a-input
:ref="emailField"
v-model:value="usersData.emails" v-model:value="usersData.emails"
validate-trigger="onBlur" validate-trigger="onBlur"
:placeholder="$t('labels.email')" :placeholder="$t('labels.email')"

2
packages/nc-gui/components/virtual-cell/Lookup.vue

@ -11,8 +11,8 @@ import {
inject, inject,
isAttachment, isAttachment,
provide, provide,
refAutoReset,
ref, ref,
refAutoReset,
useMetas, useMetas,
watch, watch,
} from '#imports' } from '#imports'

14
packages/nc-gui/composables/useColumnCreateStore.ts

@ -97,7 +97,19 @@ const [useProvideColumnCreateStore, useColumnCreateStore] = createInjectionState
const onUidtOrIdTypeChange = () => { const onUidtOrIdTypeChange = () => {
const colProp = sqlUi.value.getDataTypeForUiType(formState.value as { uidt: UITypes }, idType ?? undefined) const colProp = sqlUi.value.getDataTypeForUiType(formState.value as { uidt: UITypes }, idType ?? undefined)
formState.value = { formState.value = {
...formState.value, ...(!isEdit.value && {
// only take title, column_name and uidt when creating a column
// to avoid the extra props from being taken (e.g. SingleLineText -> LTAR -> SingleLineText)
// to mess up the column creation
title: formState.value.title,
column_name: formState.value.column_name,
uidt: formState.value.uidt,
}),
...(isEdit.value && {
// take the existing formState.value when editing a column
// LTAR is not available in this case
...formState.value,
}),
meta: {}, meta: {},
rqd: false, rqd: false,
pk: false, pk: false,

3
packages/nc-gui/composables/useExpandedFormStore.ts

@ -46,8 +46,6 @@ const [useProvideExpandedFormStore, useExpandedFormStore] = useInjectionState((m
const activeView = inject(ActiveViewInj, ref()) const activeView = inject(ActiveViewInj, ref())
const { addOrEditStackRow } = useKanbanViewStoreOrThrow()
const { sharedView } = useSharedView() const { sharedView } = useSharedView()
// getters // getters
@ -197,6 +195,7 @@ const [useProvideExpandedFormStore, useExpandedFormStore] = useInjectionState((m
} }
if (activeView.value?.type === ViewTypes.KANBAN) { if (activeView.value?.type === ViewTypes.KANBAN) {
const { addOrEditStackRow } = useKanbanViewStoreOrThrow()
addOrEditStackRow(row.value, isNewRow) addOrEditStackRow(row.value, isNewRow)
} }

28
packages/nc-gui/composables/useMenuCloseOnEsc/index.ts

@ -0,0 +1,28 @@
import { isClient } from '@vueuse/core'
import type { Ref } from 'vue'
export function useMenuCloseOnEsc(open: Ref<boolean>) {
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
open.value = false
}
}
if (isClient) {
watch(open, (nextVal, _, cleanup) => {
// bind listener when `open` is truthy
if (nextVal) {
document.addEventListener('keydown', handler, true)
// if `open` is falsy then remove the event handler
} else {
document.removeEventListener('keydown', handler, true)
}
// cleanup is called whenever the watcher is re-evaluated or stopped
cleanup(() => {
document.removeEventListener('keydown', handler, true)
})
})
}
}

5
packages/nc-gui/composables/useMultiSelect/index.ts

@ -41,6 +41,7 @@ export function useMultiSelect(
function selectCell(row: number, col: number) { function selectCell(row: number, col: number) {
clearRangeRows() clearRangeRows()
if (selected.row === row && selected.col === col) return
editEnabled.value = false editEnabled.value = false
selected.row = row selected.row = row
selected.col = col selected.col = col
@ -132,7 +133,7 @@ export function useMultiSelect(
const onKeyDown = async (e: KeyboardEvent) => { const onKeyDown = async (e: KeyboardEvent) => {
// invoke the keyEventHandler if provided and return if it returns true // invoke the keyEventHandler if provided and return if it returns true
if (await keyEventHandler?.(e)) { if (await keyEventHandler?.(e)) {
return return true
} }
if ( if (
@ -267,7 +268,7 @@ export function useMultiSelect(
} }
if (unref(editEnabled) || e.ctrlKey || e.altKey || e.metaKey) { if (unref(editEnabled) || e.ctrlKey || e.altKey || e.metaKey) {
return return true
} }
/** on letter key press make cell editable and empty */ /** on letter key press make cell editable and empty */

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

@ -189,14 +189,21 @@ export function useViewData(
: await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: nestedFilters.value }) : await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: nestedFilters.value })
formattedData.value = formatData(response.list) formattedData.value = formatData(response.list)
paginationData.value = response.pageInfo paginationData.value = response.pageInfo
// to cater the case like when querying with a non-zero offset
// the result page may point to the target page where the actual returned data don't display on
const expectedPage = Math.max(1, Math.ceil(paginationData.value.totalRows! / paginationData.value.pageSize!))
if (expectedPage < paginationData.value.page!) {
await changePage(expectedPage)
}
if (viewMeta.value?.type === ViewTypes.GRID) { if (viewMeta.value?.type === ViewTypes.GRID) {
await loadAggCommentsCount() await loadAggCommentsCount()
} }
} }
async function loadGalleryData() { async function loadGalleryData() {
if (!viewMeta?.value?.id) return if (!viewMeta?.value?.id || isPublic.value) return
galleryData.value = await $api.dbView.galleryRead(viewMeta.value.id) galleryData.value = await $api.dbView.galleryRead(viewMeta.value.id)
} }

2
packages/nc-gui/lang/en.json

@ -369,6 +369,8 @@
"setPrimary": "Set as Primary value", "setPrimary": "Set as Primary value",
"addRow": "Add new row", "addRow": "Add new row",
"saveRow": "Save row", "saveRow": "Save row",
"saveAndExit": "Save & Exit",
"saveAndStay": "Save & Stay",
"insertRow": "Insert New Row", "insertRow": "Insert New Row",
"deleteRow": "Delete Row", "deleteRow": "Delete Row",
"deleteSelectedRow": "Delete Selected Rows", "deleteSelectedRow": "Delete Selected Rows",

1
packages/nc-gui/nuxt.config.ts

@ -141,7 +141,6 @@ export default defineNuxtConfig({
'process.env.DEBUG': 'false', 'process.env.DEBUG': 'false',
'process.nextTick': () => {}, 'process.nextTick': () => {},
'process.env.ANT_MESSAGE_DURATION': process.env.ANT_MESSAGE_DURATION, 'process.env.ANT_MESSAGE_DURATION': process.env.ANT_MESSAGE_DURATION,
'process.env.NC_BACKEND_URL': process.env.NC_BACKEND_URL,
}, },
server: { server: {
watch: { watch: {

69
packages/nc-gui/package-lock.json generated

@ -85,28 +85,6 @@
"windicss": "^3.5.6" "windicss": "^3.5.6"
} }
}, },
"../nocodb-sdk": {
"version": "0.98.4",
"license": "AGPL-3.0-or-later",
"dependencies": {
"axios": "^0.21.1",
"jsep": "^1.3.6"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"cspell": "^4.1.0",
"eslint": "^7.8.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-functional": "^3.0.2",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-prettier": "^4.0.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.1.1",
"typescript": "^4.0.2"
}
},
"node_modules/@ampproject/remapping": { "node_modules/@ampproject/remapping": {
"version": "2.2.0", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz", "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz",
@ -8405,7 +8383,6 @@
"version": "1.15.1", "version": "1.15.1",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz",
"integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==", "integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==",
"devOptional": true,
"funding": [ "funding": [
{ {
"type": "individual", "type": "individual",
@ -11761,8 +11738,21 @@
} }
}, },
"node_modules/nocodb-sdk": { "node_modules/nocodb-sdk": {
"resolved": "../nocodb-sdk", "version": "0.98.4",
"link": true "resolved": "file:../nocodb-sdk",
"license": "AGPL-3.0-or-later",
"dependencies": {
"axios": "^0.21.1",
"jsep": "^1.3.6"
}
},
"node_modules/nocodb-sdk/node_modules/axios": {
"version": "0.21.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
"dependencies": {
"follow-redirects": "^1.14.0"
}
}, },
"node_modules/node-abi": { "node_modules/node-abi": {
"version": "3.23.0", "version": "3.23.0",
@ -23571,8 +23561,7 @@
"follow-redirects": { "follow-redirects": {
"version": "1.15.1", "version": "1.15.1",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz",
"integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==", "integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA=="
"devOptional": true
}, },
"form-data": { "form-data": {
"version": "4.0.0", "version": "4.0.0",
@ -26040,22 +26029,20 @@
} }
}, },
"nocodb-sdk": { "nocodb-sdk": {
"version": "file:../nocodb-sdk", "version": "0.98.4",
"requires": { "requires": {
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"axios": "^0.21.1", "axios": "^0.21.1",
"cspell": "^4.1.0", "jsep": "^1.3.6"
"eslint": "^7.8.0", },
"eslint-config-prettier": "^6.11.0", "dependencies": {
"eslint-plugin-eslint-comments": "^3.2.0", "axios": {
"eslint-plugin-functional": "^3.0.2", "version": "0.21.4",
"eslint-plugin-import": "^2.22.0", "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
"eslint-plugin-prettier": "^4.0.0", "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
"jsep": "^1.3.6", "requires": {
"npm-run-all": "^4.1.5", "follow-redirects": "^1.14.0"
"prettier": "^2.1.1", }
"typescript": "^4.0.2" }
} }
}, },
"node-abi": { "node-abi": {

4
packages/nc-gui/pages/[projectType]/form/[viewId]/index/survey.vue

@ -44,7 +44,7 @@ const el = ref<HTMLDivElement>()
provide(DropZoneRef, el) provide(DropZoneRef, el)
const transitionDuration = computed(() => sharedViewMeta.value.transitionDuration || 250) const transitionDuration = computed(() => sharedViewMeta.value.transitionDuration || 50)
const steps = computed(() => { const steps = computed(() => {
if (!formColumns.value) return [] if (!formColumns.value) return []
@ -305,7 +305,7 @@ onMounted(() => {
</button> </button>
</div> </div>
<div v-else-if="!submitted" class="flex items-center gap-3"> <div v-else-if="!submitted" class="flex items-center gap-3 flex-col">
<a-tooltip <a-tooltip
:title="v$.localState[field.title]?.$error ? v$.localState[field.title].$errors[0].$message : 'Go to next'" :title="v$.localState[field.title]?.$error ? v$.localState[field.title].$errors[0].$message : 'Go to next'"
:mouse-enter-delay="0.25" :mouse-enter-delay="0.25"

8
packages/nc-gui/pages/index/index/create-external.vue

@ -46,8 +46,8 @@ let formState = $ref<ProjectCreateForm>({
title: '', title: '',
dataSource: { ...getDefaultConnectionConfig(ClientType.MYSQL) }, dataSource: { ...getDefaultConnectionConfig(ClientType.MYSQL) },
inflection: { inflection: {
inflectionColumn: 'camelize', inflectionColumn: 'none',
inflectionTable: 'camelize', inflectionTable: 'none',
}, },
sslUse: SSLUsage.No, sslUse: SSLUsage.No,
extraParameters: [], extraParameters: [],
@ -57,8 +57,8 @@ const customFormState = ref<ProjectCreateForm>({
title: '', title: '',
dataSource: { ...getDefaultConnectionConfig(ClientType.MYSQL) }, dataSource: { ...getDefaultConnectionConfig(ClientType.MYSQL) },
inflection: { inflection: {
inflectionColumn: 'camelize', inflectionColumn: 'none',
inflectionTable: 'camelize', inflectionTable: 'none',
}, },
sslUse: SSLUsage.No, sslUse: SSLUsage.No,
extraParameters: [], extraParameters: [],

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

@ -316,11 +316,7 @@ const copyProjectMeta = async () => {
} }
&:hover::after { &:hover::after {
@apply transform scale-110 ring ring-accent; @apply transform scale-110;
}
&:active::after {
@apply ring ring-accent;
} }
} }

3
packages/nc-gui/utils/cell.ts

@ -2,7 +2,8 @@ import type { ColumnType } from 'nocodb-sdk'
import { UITypes } from 'nocodb-sdk' import { UITypes } from 'nocodb-sdk'
export const dataTypeLow = (column: ColumnType) => column.dt?.toLowerCase() export const dataTypeLow = (column: ColumnType) => column.dt?.toLowerCase()
export const isBoolean = (abstractType: any) => abstractType === 'boolean' export const isBoolean = (column: ColumnType, abstractType?: any) =>
column.uidt === UITypes.Checkbox || abstractType === 'boolean'
export const isString = (column: ColumnType, abstractType: any) => export const isString = (column: ColumnType, abstractType: any) =>
column.uidt === UITypes.SingleLineText || abstractType === 'string' column.uidt === UITypes.SingleLineText || abstractType === 'string'
export const isTextArea = (column: ColumnType) => column.uidt === UITypes.LongText export const isTextArea = (column: ColumnType) => column.uidt === UITypes.LongText

11
packages/nc-gui/utils/parsers/CSVTemplateAdapter.ts

@ -145,9 +145,6 @@ export default class CSVTemplateAdapter {
} }
// handle numeric case // handle numeric case
if (len === 2 && UITypes.Number in detectedColTypes && UITypes.Decimal in detectedColTypes) { if (len === 2 && UITypes.Number in detectedColTypes && UITypes.Decimal in detectedColTypes) {
if (detectedColTypes[UITypes.Number] > detectedColTypes[UITypes.Decimal]) {
return UITypes.Number
}
return UITypes.Decimal return UITypes.Decimal
} }
// if there are multiple detected column types // if there are multiple detected column types
@ -179,8 +176,10 @@ export default class CSVTemplateAdapter {
) { ) {
this.tables[tableIdx].columns[columnIdx].uidt = UITypes.Date this.tables[tableIdx].columns[columnIdx].uidt = UITypes.Date
// take the date format with the max occurrence // take the date format with the max occurrence
this.tables[tableIdx].columns[columnIdx].meta.date_format = const objKeys = Object.keys(dateFormat)
Object.keys(dateFormat).reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y)) || 'YYYY/MM/DD' this.tables[tableIdx].columns[columnIdx].meta.date_format = objKeys.length
? objKeys.reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y))
: 'YYYY/MM/DD'
} else { } else {
// Datetime // Datetime
this.tables[tableIdx].columns[columnIdx].uidt = uidt this.tables[tableIdx].columns[columnIdx].uidt = uidt
@ -238,6 +237,8 @@ export default class CSVTemplateAdapter {
reject(e) reject(e)
}, },
}) })
} else {
resolve(true)
} }
}) })
} }

2
packages/noco-docs/content/en/getting-started/installation.md

@ -478,7 +478,7 @@ It is mandatory to configure `NC_DB` environment variables for production usecas
| NC_JWT_EXPIRES_IN | No | JWT token expiry time | `10h` | | | NC_JWT_EXPIRES_IN | No | JWT token expiry time | `10h` | |
| NC_CONNECT_TO_EXTERNAL_DB_DISABLED | No | Disable Project creation with external database | | | | NC_CONNECT_TO_EXTERNAL_DB_DISABLED | No | Disable Project creation with external database | | |
| NC_INVITE_ONLY_SIGNUP | No | Allow users to signup only via invite url, value should be any non-empty string. | | | | NC_INVITE_ONLY_SIGNUP | No | Allow users to signup only via invite url, value should be any non-empty string. | | |
| NC_BACKEND_URL | No | Custom Backend URL | ``http://localhost:8080`` will be used | | | NUXT_PUBLIC_NC_BACKEND_URL | No | Custom Backend URL | ``http://localhost:8080`` will be used | |
| NC_REQUEST_BODY_SIZE | No | Request body size [limit](https://expressjs.com/en/resources/middleware/body-parser.html#limit) | `1048576` | | | NC_REQUEST_BODY_SIZE | No | Request body size [limit](https://expressjs.com/en/resources/middleware/body-parser.html#limit) | `1048576` | |
| NC_EXPORT_MAX_TIMEOUT | No | After NC_EXPORT_MAX_TIMEOUT csv gets downloaded in batches | Default value 5000(in millisecond) will be used | | | NC_EXPORT_MAX_TIMEOUT | No | After NC_EXPORT_MAX_TIMEOUT csv gets downloaded in batches | Default value 5000(in millisecond) will be used | |
| NC_DISABLE_TELE | No | Disable telemetry | | | | NC_DISABLE_TELE | No | Disable telemetry | | |

1
packages/nocodb-sdk/src/lib/Api.ts

@ -1950,6 +1950,7 @@ export class Api<
tableId: string, tableId: string,
data: { data: {
table_name?: string; table_name?: string;
title?: string;
project_id?: string; project_id?: string;
}, },
params: RequestParams = {} params: RequestParams = {}

47
packages/nocodb/package-lock.json generated

@ -151,28 +151,6 @@
"vuedraggable": "^2.24.3" "vuedraggable": "^2.24.3"
} }
}, },
"../nocodb-sdk": {
"version": "0.98.4",
"license": "AGPL-3.0-or-later",
"dependencies": {
"axios": "^0.21.1",
"jsep": "^1.3.6"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"cspell": "^4.1.0",
"eslint": "^7.8.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-functional": "^3.0.2",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-prettier": "^4.0.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.1.1",
"typescript": "^4.0.2"
}
},
"node_modules/@azure/abort-controller": { "node_modules/@azure/abort-controller": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-1.1.0.tgz", "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-1.1.0.tgz",
@ -10685,8 +10663,13 @@
"dev": true "dev": true
}, },
"node_modules/nocodb-sdk": { "node_modules/nocodb-sdk": {
"resolved": "../nocodb-sdk", "version": "0.98.4",
"link": true "resolved": "file:../nocodb-sdk",
"license": "AGPL-3.0-or-later",
"dependencies": {
"axios": "^0.21.1",
"jsep": "^1.3.6"
}
}, },
"node_modules/node-abort-controller": { "node_modules/node-abort-controller": {
"version": "3.0.1", "version": "3.0.1",
@ -26108,22 +26091,10 @@
"dev": true "dev": true
}, },
"nocodb-sdk": { "nocodb-sdk": {
"version": "file:../nocodb-sdk", "version": "0.98.4",
"requires": { "requires": {
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"axios": "^0.21.1", "axios": "^0.21.1",
"cspell": "^4.1.0", "jsep": "^1.3.6"
"eslint": "^7.8.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-functional": "^3.0.2",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-prettier": "^4.0.0",
"jsep": "^1.3.6",
"npm-run-all": "^4.1.5",
"prettier": "^2.1.1",
"typescript": "^4.0.2"
} }
}, },
"node-abort-controller": { "node-abort-controller": {

1
packages/nocodb/src/lib/Noco.ts

@ -213,7 +213,6 @@ export default class Noco {
}); });
// to get ip addresses // to get ip addresses
this.router.use(requestIp.mw()); this.router.use(requestIp.mw());
this.router.use(cookieParser()); this.router.use(cookieParser());
this.router.use( this.router.use(

23
packages/nocodb/src/lib/db/sql-data-mapper/lib/sql/BaseModelSqlv2.ts

@ -176,7 +176,7 @@ class BaseModelSqlv2 {
sortArr?: Sort[]; sortArr?: Sort[];
sort?: string | string[]; sort?: string | string[];
} = {}, } = {},
ignoreFilterSort = false ignoreViewFilterAndSort = false
): Promise<any> { ): Promise<any> {
const { where, ...rest } = this._getListArgs(args as any); const { where, ...rest } = this._getListArgs(args as any);
@ -190,7 +190,7 @@ class BaseModelSqlv2 {
let sorts = extractSortsObject(rest?.sort, aliasColObjMap); let sorts = extractSortsObject(rest?.sort, aliasColObjMap);
const filterObj = extractFilterFromXwhere(where, aliasColObjMap); const filterObj = extractFilterFromXwhere(where, aliasColObjMap);
// todo: replace with view id // todo: replace with view id
if (!ignoreFilterSort && this.viewId) { if (!ignoreViewFilterAndSort && this.viewId) {
await conditionV2( await conditionV2(
[ [
new Filter({ new Filter({
@ -250,7 +250,7 @@ class BaseModelSqlv2 {
qb.orderBy('created_at'); qb.orderBy('created_at');
} }
if (!ignoreFilterSort) applyPaginate(qb, rest); if (!ignoreViewFilterAndSort) applyPaginate(qb, rest);
const proto = await this.getProto(); const proto = await this.getProto();
const data = await this.extractRawQueryAndExec(qb); const data = await this.extractRawQueryAndExec(qb);
@ -262,7 +262,7 @@ class BaseModelSqlv2 {
public async count( public async count(
args: { where?: string; limit?; filterArr?: Filter[] } = {}, args: { where?: string; limit?; filterArr?: Filter[] } = {},
ignoreFilterSort = false ignoreViewFilterAndSort = false
): Promise<any> { ): Promise<any> {
await this.model.getColumns(); await this.model.getColumns();
const { where } = this._getListArgs(args); const { where } = this._getListArgs(args);
@ -273,7 +273,7 @@ class BaseModelSqlv2 {
const aliasColObjMap = await this.model.getAliasColObjMap(); const aliasColObjMap = await this.model.getAliasColObjMap();
const filterObj = extractFilterFromXwhere(where, aliasColObjMap); const filterObj = extractFilterFromXwhere(where, aliasColObjMap);
if (!ignoreFilterSort && this.viewId) { if (!ignoreViewFilterAndSort && this.viewId) {
await conditionV2( await conditionV2(
[ [
new Filter({ new Filter({
@ -2278,7 +2278,7 @@ class BaseModelSqlv2 {
for (let i = 0; i < this.model.columns.length; ++i) { for (let i = 0; i < this.model.columns.length; ++i) {
const column = this.model.columns[i]; const column = this.model.columns[i];
// skip validation if `validate` is undefined or false // skip validation if `validate` is undefined or false
if (!column?.meta?.validate && !column?.validate) continue; if (!column?.meta?.validate || !column?.validate) continue;
const validate = column.getValidators(); const validate = column.getValidators();
const cn = column.column_name; const cn = column.column_name;
@ -2512,7 +2512,7 @@ class BaseModelSqlv2 {
public async groupedList( public async groupedList(
args: { args: {
groupColumnId: string; groupColumnId: string;
ignoreFilterSort?: boolean; ignoreViewFilterAndSort?: boolean;
options?: (string | number | null | boolean)[]; options?: (string | number | null | boolean)[];
} & Partial<XcFilter> } & Partial<XcFilter>
): Promise< ): Promise<
@ -2565,7 +2565,7 @@ class BaseModelSqlv2 {
let sorts = extractSortsObject(args?.sort, aliasColObjMap); let sorts = extractSortsObject(args?.sort, aliasColObjMap);
const filterObj = extractFilterFromXwhere(where, aliasColObjMap); const filterObj = extractFilterFromXwhere(where, aliasColObjMap);
// todo: replace with view id // todo: replace with view id
if (!args.ignoreFilterSort && this.viewId) { if (!args.ignoreViewFilterAndSort && this.viewId) {
await conditionV2( await conditionV2(
[ [
new Filter({ new Filter({
@ -2678,7 +2678,10 @@ class BaseModelSqlv2 {
} }
public async groupedListCount( public async groupedListCount(
args: { groupColumnId: string; ignoreFilterSort?: boolean } & XcFilter args: {
groupColumnId: string;
ignoreViewFilterAndSort?: boolean;
} & XcFilter
) { ) {
const column = await this.model const column = await this.model
.getColumns() .getColumns()
@ -2697,7 +2700,7 @@ class BaseModelSqlv2 {
const filterObj = extractFilterFromXwhere(args.where, aliasColObjMap); const filterObj = extractFilterFromXwhere(args.where, aliasColObjMap);
// todo: replace with view id // todo: replace with view id
if (!args.ignoreFilterSort && this.viewId) { if (!args.ignoreViewFilterAndSort && this.viewId) {
await conditionV2( await conditionV2(
[ [
new Filter({ new Filter({

29
packages/nocodb/src/lib/meta/api/swagger/redocHtml.ts

@ -17,8 +17,33 @@ export default `<!DOCTYPE html>
</style> </style>
</head> </head>
<body> <body>
<redoc spec-url='./swagger.json'></redoc> <div id="redoc"></div>
<script src="https://cdn.jsdelivr.net/npm/redoc@latest/bundles/redoc.standalone.js"> </script> <script src="https://cdn.jsdelivr.net/npm/redoc@latest/bundles/redoc.standalone.js"></script>
<script>
let initialLocalStorage = {}
try {
initialLocalStorage = JSON.parse(localStorage.getItem('nocodb-gui-v2') || '{}');
} catch (e) {
console.error('Failed to parse local storage', e);
}
const xhttp = new XMLHttpRequest();
xhttp.open("GET", "./swagger.json");
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.setRequestHeader("xc-auth", initialLocalStorage && initialLocalStorage.token);
xhttp.onload = function () {
const swaggerJson = this.responseText;
const swagger = JSON.parse(swaggerJson);
Redoc.init(swagger, {
scrollYOffset: 50
}, document.getElementById('redoc'))
};
xhttp.send();
</script>
<script> <script>
console.log('%c🚀 We are Hiring!!! 🚀%c\\n%cJoin the forces http://careers.nocodb.com', 'color:#1348ba;font-size:3rem;padding:20px;', 'display:none', 'font-size:1.5rem;padding:20px') console.log('%c🚀 We are Hiring!!! 🚀%c\\n%cJoin the forces http://careers.nocodb.com', 'color:#1348ba;font-size:3rem;padding:20px;', 'display:none', 'font-size:1.5rem;padding:20px')
const linkEl = document.createElement('a') const linkEl = document.createElement('a')

1
packages/nocodb/src/lib/meta/api/testApis.ts

@ -6,6 +6,7 @@ export async function reset(req: Request<any, any>, res) {
parallelId: req.body.parallelId, parallelId: req.body.parallelId,
dbType: req.body.dbType, dbType: req.body.dbType,
isEmptyProject: req.body.isEmptyProject, isEmptyProject: req.body.isEmptyProject,
workerId: req.body.workerId
}); });
res.json(await service.process()); res.json(await service.process());

2
packages/nocodb/src/lib/models/Model.ts

@ -248,7 +248,6 @@ export default class Model implements TableType {
)); ));
if (!modelData) { if (!modelData) {
modelData = await ncMeta.metaGet2(null, null, MetaTable.MODELS, k); modelData = await ncMeta.metaGet2(null, null, MetaTable.MODELS, k);
await NocoCache.set(`${CacheScope.MODEL}:${modelData.id}`, modelData);
// if ( // if (
// this.baseModels?.[modelData.base_id]?.[modelData.db_alias]?.[ // this.baseModels?.[modelData.base_id]?.[modelData.db_alias]?.[
// modelData.title // modelData.title
@ -269,6 +268,7 @@ export default class Model implements TableType {
// } // }
} }
if (modelData) { if (modelData) {
await NocoCache.set(`${CacheScope.MODEL}:${modelData.id}`, modelData);
return new Model(modelData); return new Model(modelData);
} }
return null; return null;

22
packages/nocodb/src/lib/services/test/TestResetService/index.ts

@ -23,11 +23,13 @@ const loginRootUser = async () => {
const projectTitleByType = { const projectTitleByType = {
sqlite: 'sampleREST', sqlite: 'sampleREST',
mysql: 'externalREST', mysql: 'externalREST',
pg: 'pgExtREST', pg: 'pgExtREST'
}; };
export class TestResetService { export class TestResetService {
private readonly parallelId; private readonly parallelId;
// todo: Hack to resolve issue with pg resetting
private readonly workerId;
private readonly dbType; private readonly dbType;
private readonly isEmptyProject: boolean; private readonly isEmptyProject: boolean;
@ -35,14 +37,17 @@ export class TestResetService {
parallelId, parallelId,
dbType, dbType,
isEmptyProject, isEmptyProject,
workerId
}: { }: {
parallelId: string; parallelId: string;
dbType: string; dbType: string;
isEmptyProject: boolean; isEmptyProject: boolean;
workerId: string;
}) { }) {
this.parallelId = parallelId; this.parallelId = parallelId;
this.dbType = dbType; this.dbType = dbType;
this.isEmptyProject = isEmptyProject; this.isEmptyProject = isEmptyProject;
this.workerId = workerId;
} }
async process() { async process() {
@ -68,6 +73,7 @@ export class TestResetService {
token, token,
dbType: this.dbType, dbType: this.dbType,
parallelId: this.parallelId, parallelId: this.parallelId,
workerId: this.workerId
}); });
try { try {
@ -90,10 +96,12 @@ export class TestResetService {
token, token,
dbType, dbType,
parallelId, parallelId,
workerId
}: { }: {
token: string; token: string;
dbType: string; dbType: string;
parallelId: string; parallelId: string;
workerId: string;
}) { }) {
const title = `${projectTitleByType[dbType]}${parallelId}`; const title = `${projectTitleByType[dbType]}${parallelId}`;
const project: Project | undefined = await Project.getByTitle(title); const project: Project | undefined = await Project.getByTitle(title);
@ -115,7 +123,7 @@ export class TestResetService {
token, token,
title, title,
parallelId, parallelId,
isEmptyProject: this.isEmptyProject, isEmptyProject: this.isEmptyProject
}); });
} else if (dbType == 'mysql') { } else if (dbType == 'mysql') {
await resetMysqlSakilaProject({ await resetMysqlSakilaProject({
@ -123,20 +131,20 @@ export class TestResetService {
title, title,
parallelId, parallelId,
oldProject: project, oldProject: project,
isEmptyProject: this.isEmptyProject, isEmptyProject: this.isEmptyProject
}); });
} else if (dbType == 'pg') { } else if (dbType == 'pg') {
await resetPgSakilaProject({ await resetPgSakilaProject({
token, token,
title, title,
parallelId, parallelId: workerId,
oldProject: project, oldProject: project,
isEmptyProject: this.isEmptyProject, isEmptyProject: this.isEmptyProject
}); });
} }
return { return {
project: await Project.getByTitle(title), project: await Project.getByTitle(title)
}; };
} }
} }
@ -169,7 +177,7 @@ const removeProjectUsersFromCache = async (project: Project) => {
const projectUsers: ProjectUser[] = await ProjectUser.getUsersList({ const projectUsers: ProjectUser[] = await ProjectUser.getUsersList({
project_id: project.id, project_id: project.id,
limit: 1000, limit: 1000,
offset: 0, offset: 0
}); });
for (const projectUser of projectUsers) { for (const projectUser of projectUsers) {

3
scripts/sdk/swagger.json

@ -1703,6 +1703,9 @@
"table_name": { "table_name": {
"type": "string" "type": "string"
}, },
"title": {
"type": "string"
},
"project_id": { "project_id": {
"type": "string" "type": "string"
} }

28
tests/playwright/pages/Dashboard/ExpandedForm/index.ts

@ -54,10 +54,21 @@ export class ExpandedFormPage extends BasePage {
async save({ async save({
waitForRowsData = true, waitForRowsData = true,
saveAndExitMode = true,
}: { }: {
waitForRowsData?: boolean; waitForRowsData?: boolean;
saveAndExitMode?: boolean;
} = {}) { } = {}) {
const saveRowAction = this.get().locator('button:has-text("Save Row")').click(); if (!saveAndExitMode) {
await this.get().locator('.nc-expand-form-save-btn .ant-dropdown-trigger').click();
const dropdownList = this.rootPage.locator('.nc-expand-form-save-dropdown-menu');
await dropdownList.locator('.ant-dropdown-menu-item:has-text("Save & Stay")').click();
}
const saveRowAction = saveAndExitMode
? this.get().locator('button:has-text("Save & Exit")').click()
: this.get().locator('button:has-text("Save & Stay")').click();
if (waitForRowsData) { if (waitForRowsData) {
await this.waitForResponse({ await this.waitForResponse({
uiAction: saveRowAction, uiAction: saveRowAction,
@ -73,7 +84,10 @@ export class ExpandedFormPage extends BasePage {
}); });
} }
await this.get().press('Escape'); if (!saveAndExitMode) {
await this.get().press('Escape');
}
await this.get().waitFor({ state: 'hidden' }); await this.get().waitFor({ state: 'hidden' });
await this.verifyToast({ message: `updated successfully.` }); await this.verifyToast({ message: `updated successfully.` });
await this.rootPage.locator('[data-testid="grid-load-spinner"]').waitFor({ state: 'hidden' }); await this.rootPage.locator('[data-testid="grid-load-spinner"]').waitFor({ state: 'hidden' });
@ -84,13 +98,13 @@ export class ExpandedFormPage extends BasePage {
await expect.poll(() => this.rootPage.url()).toContain(url); await expect.poll(() => this.rootPage.url()).toContain(url);
} }
async close() { async escape() {
await this.rootPage.keyboard.press('Escape'); await this.rootPage.keyboard.press('Escape');
await this.get().waitFor({ state: 'hidden' }); await this.get().waitFor({ state: 'hidden' });
} }
async cancel() { async close() {
await this.get().locator('button:has-text("Cancel")').last().click(); await this.get().locator('button:has-text("Close")').last().click();
} }
async openChildCard(param: { column: string; title: string }) { async openChildCard(param: { column: string; title: string }) {
@ -104,9 +118,9 @@ export class ExpandedFormPage extends BasePage {
async validateRoleAccess(param: { role: string }) { async validateRoleAccess(param: { role: string }) {
if (param.role === 'commenter' || param.role === 'viewer') { if (param.role === 'commenter' || param.role === 'viewer') {
await expect(await this.get().locator('button:has-text("Save Row")')).toBeDisabled(); await expect(await this.get().locator('button:has-text("Save & Exit")')).toBeDisabled();
} else { } else {
await expect(await this.get().locator('button:has-text("Save Row")')).toBeEnabled(); await expect(await this.get().locator('button:has-text("Save & Exit")')).toBeEnabled();
} }
if (param.role === 'viewer') { if (param.role === 'viewer') {
await expect(await this.toggleCommentsButton).toHaveCount(0); await expect(await this.toggleCommentsButton).toHaveCount(0);

44
tests/playwright/pages/Dashboard/common/Cell/SelectOptionCell.ts

@ -112,4 +112,48 @@ export class SelectOptionCellPageObject extends BasePage {
await this.get({ index, columnHeader }).click(); await this.get({ index, columnHeader }).click();
await this.rootPage.locator(`.nc-dropdown-single-select-cell`).nth(index).waitFor({ state: 'hidden' }); await this.rootPage.locator(`.nc-dropdown-single-select-cell`).nth(index).waitFor({ state: 'hidden' });
} }
async addNewOption({
index,
columnHeader,
option,
multiSelect,
}: {
index: number;
columnHeader: string;
option: string;
multiSelect?: boolean;
}) {
const selectCell = this.get({ index, columnHeader });
// check if cell active
if (!(await selectCell.getAttribute('class')).includes('active')) {
await selectCell.click();
}
await selectCell.locator('.ant-select-selection-search-input').type(option);
await selectCell.locator('.ant-select-selection-search-input').press('Enter');
if (multiSelect) await selectCell.locator('.ant-select-selection-search-input').press('Escape');
// todo: wait for update api call
}
async verifySelectedOptions({
index,
options,
columnHeader,
}: {
columnHeader: string;
options: string[];
index: number;
}) {
const selectCell = this.get({ index, columnHeader });
let counter = 0;
for (const option of options) {
await expect(selectCell.locator(`.nc-selected-option`).nth(counter)).toHaveText(option);
counter++;
}
}
} }

2
tests/playwright/pages/Dashboard/common/Toolbar/AddEditKanbanStack.ts

@ -16,7 +16,7 @@ export class ToolbarAddEditStackPage extends BasePage {
async addOption({ title }: { title: string }) { async addOption({ title }: { title: string }) {
await this.get().locator(`.ant-btn-dashed`).click(); await this.get().locator(`.ant-btn-dashed`).click();
await this.get().locator(`.nc-select-option >> input`).last().fill(title); await this.get().locator(`.nc-select-option >> input`).last().fill(title);
await this.get().locator(`.nc-select-option >> input`).last().press('Enter'); await this.get().locator(`[type="submit"]`).click();
await this.verifyToast({ message: 'Column updated' }); await this.verifyToast({ message: 'Column updated' });
} }
} }

9
tests/playwright/setup/db.ts

@ -11,17 +11,18 @@ const isSqlite = (context: NcContext) => context.dbType === 'sqlite';
const isPg = (context: NcContext) => context.dbType === 'pg'; const isPg = (context: NcContext) => context.dbType === 'pg';
const pg_credentials = () => ({ const pg_credentials = (context: NcContext) => ({
user: 'postgres', user: 'postgres',
host: 'localhost', host: 'localhost',
database: `sakila_${process.env.TEST_PARALLEL_INDEX}`, // todo: Hack to resolve issue with pg resetting
database: `sakila_${context.workerId}`,
password: 'password', password: 'password',
port: 5432, port: 5432,
}); });
const pgExec = async (query: string) => { const pgExec = async (query: string, context: NcContext) => {
// open pg client connection // open pg client connection
const client = new Client(pg_credentials()); const client = new Client(pg_credentials(context));
await client.connect(); await client.connect();
await client.query(query); await client.query(query);

18
tests/playwright/setup/index.ts

@ -1,10 +1,14 @@
import { Page, selectors } from '@playwright/test'; import { Page, selectors } from '@playwright/test';
import axios from 'axios'; import axios from 'axios';
const workerCount = {};
export interface NcContext { export interface NcContext {
project: any; project: any;
token: string; token: string;
dbType?: string; dbType?: string;
// todo: Hack to resolve issue with pg resetting
workerId?: string;
} }
selectors.setTestIdAttribute('data-testid'); selectors.setTestIdAttribute('data-testid');
@ -13,11 +17,23 @@ const setup = async ({ page, isEmptyProject }: { page: Page; isEmptyProject?: bo
let dbType = process.env.CI ? process.env.E2E_DB_TYPE : process.env.E2E_DEV_DB_TYPE; let dbType = process.env.CI ? process.env.E2E_DB_TYPE : process.env.E2E_DEV_DB_TYPE;
dbType = dbType || 'sqlite'; dbType = dbType || 'sqlite';
let workerId;
// todo: Hack to resolve issue with pg resetting
if (dbType === 'pg') {
const workerIndex = process.env.TEST_PARALLEL_INDEX;
if (!workerCount[workerIndex]) {
workerCount[workerIndex] = 0;
}
workerCount[workerIndex]++;
workerId = String(Number(workerIndex) + Number(workerCount[workerIndex]) * 4);
}
// if (!process.env.CI) console.time(`setup ${process.env.TEST_PARALLEL_INDEX}`); // if (!process.env.CI) console.time(`setup ${process.env.TEST_PARALLEL_INDEX}`);
let response; let response;
try { try {
response = await axios.post(`http://localhost:8080/api/v1/meta/test/reset`, { response = await axios.post(`http://localhost:8080/api/v1/meta/test/reset`, {
parallelId: process.env.TEST_PARALLEL_INDEX, parallelId: process.env.TEST_PARALLEL_INDEX,
workerId: workerId,
dbType, dbType,
isEmptyProject, isEmptyProject,
}); });
@ -59,7 +75,7 @@ const setup = async ({ page, isEmptyProject }: { page: Page; isEmptyProject?: bo
await page.goto(`/#/nc/${project.id}/auth`, { waitUntil: 'networkidle' }); await page.goto(`/#/nc/${project.id}/auth`, { waitUntil: 'networkidle' });
return { project, token, dbType } as NcContext; return { project, token, dbType, workerId } as NcContext;
}; };
export default setup; export default setup;

24
tests/playwright/tests/columnMultiSelect.spec.ts

@ -128,4 +128,28 @@ test.describe('Multi select', () => {
await grid.column.delete({ title: 'MultiSelect' }); await grid.column.delete({ title: 'MultiSelect' });
}); });
test('Add new option directly from cell', async () => {
await grid.cell.selectOption.addNewOption({
index: 0,
columnHeader: 'MultiSelect',
option: 'Option added from cell 1',
multiSelect: true,
});
await grid.cell.selectOption.addNewOption({
index: 0,
columnHeader: 'MultiSelect',
option: 'Option added from cell 2',
multiSelect: true,
});
await grid.cell.selectOption.verifySelectedOptions({
index: 0,
columnHeader: 'MultiSelect',
options: ['Option added from cell 1', 'Option added from cell 2'],
});
await grid.column.delete({ title: 'MultiSelect' });
});
}); });

12
tests/playwright/tests/columnSingleSelect.spec.ts

@ -69,4 +69,16 @@ test.describe('Single select', () => {
await grid.column.delete({ title: 'SingleSelect' }); await grid.column.delete({ title: 'SingleSelect' });
}); });
test('Add new option directly from cell', async () => {
await grid.cell.selectOption.addNewOption({
index: 0,
columnHeader: 'SingleSelect',
option: 'Option added from cell',
});
await grid.cell.selectOption.verify({ index: 0, columnHeader: 'SingleSelect', option: 'Option added from cell' });
await grid.column.delete({ title: 'SingleSelect' });
});
}); });

10
tests/playwright/tests/expandedFormUrl.spec.ts

@ -37,7 +37,7 @@ test.describe('Expanded form URL', () => {
// expand row & verify URL // expand row & verify URL
await viewObj.openExpandedRow({ index: 0 }); await viewObj.openExpandedRow({ index: 0 });
const url = await dashboard.expandedForm.getShareRowUrl(); const url = await dashboard.expandedForm.getShareRowUrl();
await dashboard.expandedForm.close(); await dashboard.expandedForm.escape();
await dashboard.rootPage.goto(url); await dashboard.rootPage.goto(url);
await dashboard.expandedForm.verify({ await dashboard.expandedForm.verify({
@ -81,13 +81,13 @@ test.describe('Expanded form URL', () => {
// expect(expandedFormUrl).toContain("rowId=1"); // expect(expandedFormUrl).toContain("rowId=1");
// access a new rowID using URL // access a new rowID using URL
await dashboard.expandedForm.close(); await dashboard.expandedForm.escape();
await dashboard.expandedForm.gotoUsingUrlAndRowId({ rowId: '2' }); await dashboard.expandedForm.gotoUsingUrlAndRowId({ rowId: '2' });
await dashboard.expandedForm.verify({ await dashboard.expandedForm.verify({
header: 'Algeria', header: 'Algeria',
url: 'rowId=2', url: 'rowId=2',
}); });
await dashboard.expandedForm.close(); await dashboard.expandedForm.escape();
// visit invalid rowID // visit invalid rowID
await dashboard.expandedForm.gotoUsingUrlAndRowId({ rowId: '999' }); await dashboard.expandedForm.gotoUsingUrlAndRowId({ rowId: '999' });
@ -114,12 +114,12 @@ test.describe('Expanded form URL', () => {
await dashboard.expandedForm.verifyCount({ count: 2 }); await dashboard.expandedForm.verifyCount({ count: 2 });
// close child card // close child card
await dashboard.expandedForm.cancel(); await dashboard.expandedForm.close();
await dashboard.expandedForm.verify({ await dashboard.expandedForm.verify({
header: 'Afghanistan', header: 'Afghanistan',
url: 'rowId=1', url: 'rowId=1',
}); });
await dashboard.expandedForm.cancel(); await dashboard.expandedForm.close();
} }
test('Grid', async () => { test('Grid', async () => {

2
tests/playwright/tests/metaSync.spec.ts

@ -24,7 +24,7 @@ test.describe('Meta sync', () => {
dbExec = mysqlExec; dbExec = mysqlExec;
break; break;
case 'pg': case 'pg':
dbExec = pgExec; dbExec = query => pgExec(query, context);
break; break;
} }
}); });

14
tests/playwright/tests/tableColumnOperation.spec.ts

@ -36,13 +36,25 @@ test.describe('Table Column Operations', () => {
columnTitle: 'Title', columnTitle: 'Title',
value: 'value_a', value: 'value_a',
}); });
await dashboard.expandedForm.save(); await dashboard.expandedForm.save({ saveAndExitMode: true });
await grid.cell.verify({ await grid.cell.verify({
index: 0, index: 0,
columnHeader: 'Title', columnHeader: 'Title',
value: 'value_a', value: 'value_a',
}); });
await grid.openExpandedRow({ index: 0 });
await dashboard.expandedForm.fillField({
columnTitle: 'Title',
value: 'value_a_a',
});
await dashboard.expandedForm.save({ saveAndExitMode: false });
await grid.cell.verify({
index: 0,
columnHeader: 'Title',
value: 'value_a_a',
});
await grid.deleteRow(0); await grid.deleteRow(0);
await grid.verifyRowDoesNotExist({ index: 0 }); await grid.verifyRowDoesNotExist({ index: 0 });

Loading…
Cancel
Save