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'))
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>
<template>
<a-config-provider>
<NuxtLayout :name="disableBaseLayout ? false : 'base'">
<NuxtPage />
<NuxtPage :key="key" />
</NuxtLayout>
</a-config-provider>
</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;
&::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: '';
z-index: -1;
}
&:hover::after {
@apply transform scale-110 ring ring-accent;
}
&:active::after {
@apply ring ring-accent;
@apply transform scale-110;
}
}
@ -261,7 +257,7 @@ a {
}
.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,

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']
ADrawer: typeof import('ant-design-vue/es')['Drawer']
ADropdown: typeof import('ant-design-vue/es')['Dropdown']
ADropdownButton: typeof import('ant-design-vue/es')['DropdownButton']
AEmpty: typeof import('ant-design-vue/es')['Empty']
AForm: typeof import('ant-design-vue/es')['Form']
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']
MaterialSymbolsFileCopyOutline: typeof import('~icons/material-symbols/file-copy-outline')['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']
MaterialSymbolsRocketLaunchOutline: typeof import('~icons/material-symbols/rocket-launch-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']
MdiCalculator: typeof import('~icons/mdi/calculator')['default']
MdiCalendarMonth: typeof import('~icons/mdi/calendar-month')['default']
MdiCancel: typeof import('~icons/mdi/cancel')['default']
MdiCardsHeart: typeof import('~icons/mdi/cards-heart')['default']
MdiCellphoneMessage: typeof import('~icons/mdi/cellphone-message')['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']
MdiContentCopy: typeof import('~icons/mdi/content-copy')['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']
MdiDatabaseOutline: typeof import('~icons/mdi/database-outline')['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']
MdiPlusCircleOutline: typeof import('~icons/mdi/plus-circle-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']
MdiRefresh: typeof import('~icons/mdi/refresh')['default']
MdiReload: typeof import('~icons/mdi/reload')['default']

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

@ -1,19 +1,23 @@
<script lang="ts" setup>
import { message } from 'ant-design-vue'
import tinycolor from 'tinycolor2'
import type { Select as AntSelect } from 'ant-design-vue'
import type { SelectOptionType, SelectOptionsType } from 'nocodb-sdk'
import {
ActiveCellInj,
ColumnInj,
EditModeInj,
IsKanbanInj,
ReadonlyInj,
computed,
enumColor,
extractSdkResponseErrorMsg,
h,
inject,
onMounted,
reactive,
ref,
useEventListener,
useMetas,
useProject,
useSelectedCellKeyupListener,
watch,
@ -39,6 +43,8 @@ const active = inject(ActiveCellInj, ref(false))
const editable = inject(EditModeInj, ref(false))
const isPublic = inject(IsPublicInj, ref(false))
const selectedIds = ref<string[]>([])
const aselect = ref<typeof AntSelect>()
@ -47,7 +53,17 @@ const isOpen = 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) {
const opts = column.value.colOptions
? (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)) {
op.title = op.title?.replace(/^'/, '').replace(/'$/, '')
}
return opts
return opts.map((o: SelectOptionType) => ({ ...o, value: o.title }))
}
return []
})
const isOptionMissing = computed(() => {
return (options.value ?? []).every((op) => op.title !== searchVal.value)
})
const vModel = computed({
get: () =>
selectedIds.value.reduce((acc, id) => {
const title = options.value.find((op) => op.id === id)?.title
get: () => {
const selected = selectedIds.value.reduce((acc, id) => {
const title = (options.value.find((op) => op.id === id) || options.value.find((op) => op.title === id))?.title
if (title) acc.push(title)
return acc
}, [] as string[]),
set: (val) => emit('update:modelValue', val.length === 0 ? null : val.join(',')),
}, [] as string[])
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(() =>
@ -97,9 +127,10 @@ const handleClose = (e: MouseEvent) => {
onMounted(() => {
selectedIds.value = selectedTitles.value.flatMap((el) => {
const item = options.value.find((op) => op.title === el)?.id
if (item) {
return [item]
const item = options.value.find((op) => op.title === el)
const itemIdOrTitle = item?.id || item?.title
if (itemIdOrTitle) {
return [itemIdOrTitle]
}
return []
@ -111,10 +142,10 @@ useEventListener(document, 'click', handleClose)
watch(
() => modelValue,
() => {
selectedIds.value = selectedIds.value = selectedTitles.value.flatMap((el) => {
const item = options.value.find((op) => op.title === el)?.id
if (item) {
return [item]
selectedIds.value = selectedTitles.value.flatMap((el) => {
const item = options.value.find((op) => op.title === el)
if (item && (item.id || item.title)) {
return [(item.id || item.title)!]
}
return []
@ -140,8 +171,65 @@ useSelectedCellKeyupListener(active, (e) => {
isOpen.value = true
}
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>
<template>
@ -152,17 +240,20 @@ useSelectedCellKeyupListener(active, (e) => {
mode="multiple"
class="w-full"
:bordered="false"
clear-icon
:show-arrow="!readOnly"
:show-search="false"
:show-search="active || editable"
:open="isOpen && (active || editable)"
:disabled="readOnly"
:class="{ '!ml-[-8px]': readOnly }"
:dropdown-class-name="`nc-dropdown-multi-select-cell ${isOpen ? 'active' : ''}`"
@keydown.enter.stop
@search="search"
@keydown.stop
@click="isOpen = (active || editable) && !isOpen"
>
<a-select-option
v-for="op of options"
:key="op.id"
:key="op.id || op.title"
:value="op.title"
:data-testid="`select-option-${column.title}-${rowIndex}`"
@click.stop
@ -182,14 +273,24 @@ useSelectedCellKeyupListener(active, (e) => {
</a-tag>
</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 }">
<a-tag
v-if="options.find((el) => el.title === val)"
class="rounded-tag"
class="rounded-tag nc-selected-option"
:style="{ display: 'flex', alignItems: 'center' }"
:color="options.find((el) => el.title === val)?.color"
:closable="(active || editable) && (vModel.length > 1 || !column?.rqd)"
:close-icon="h(MdiCloseCircle, { class: ['ms-close-icon'] })"
@click="onTagClick($event, onClose)"
@close="onClose"
>
<span
@ -255,6 +356,3 @@ useSelectedCellKeyupListener(active, (e) => {
@apply "flex overflow-hidden";
}
</style>
<!--
-->

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

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

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

@ -1,4 +1,5 @@
<script lang="ts" setup>
import { message } from 'ant-design-vue'
import tinycolor from 'tinycolor2'
import type { Select as AntSelect } from 'ant-design-vue'
import type { SelectOptionType } from 'nocodb-sdk'
@ -9,12 +10,13 @@ import {
IsKanbanInj,
ReadonlyInj,
computed,
enumColor,
extractSdkResponseErrorMsg,
inject,
ref,
useEventListener,
useSelectedCellKeyupListener,
watch,
} from '#imports'
import { useSelectedCellKeyupListener } from '~/composables/useSelectedCellKeyupListener'
interface Props {
modelValue?: string | undefined
@ -39,12 +41,19 @@ const isOpen = ref(false)
const isKanban = inject(IsKanbanInj, ref(false))
const vModel = computed({
get: () => modelValue,
set: (val) => emit('update:modelValue', val || null),
})
const isPublic = inject(IsPublicInj, ref(false))
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) {
const opts = column.value.colOptions
? // 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)) {
op.title = op.title.replace(/^'/, '').replace(/'$/, '')
}
return opts
return opts.map((o: any) => ({ ...o, value: o.title }))
}
return []
})
const handleClose = (e: MouseEvent) => {
if (aselect.value && !aselect.value.$el.contains(e.target)) {
isOpen.value = false
aselect.value.blur()
}
}
const isOptionMissing = computed(() => {
return (options.value ?? []).every((op) => op.title !== searchVal.value)
})
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) => {
if (!n) {
@ -87,6 +104,50 @@ useSelectedCellKeyupListener(active, (e) => {
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>
<template>
@ -96,13 +157,15 @@ useSelectedCellKeyupListener(active, (e) => {
class="w-full"
:allow-clear="!column.rqd && active"
:bordered="false"
:open="isOpen"
:open="isOpen && (active || editable)"
:disabled="readOnly"
:show-arrow="!readOnly && (active || editable || vModel === null)"
:dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen ? 'active' : ''}`"
:show-search="active || editable"
@select="isOpen = false"
@keydown.enter.stop
@click="isOpen = (active || editable) && !isOpen"
@keydown.stop
@search="search"
@click="toggleMenu"
>
<a-select-option
v-for="op of options"
@ -125,6 +188,15 @@ useSelectedCellKeyupListener(active, (e) => {
</span>
</a-tag>
</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>
</template>
@ -141,6 +213,3 @@ useSelectedCellKeyupListener(active, (e) => {
opacity: 1;
}
</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 focus: VNodeRef = (el) => (el as HTMLInputElement)?.focus()
const focus: VNodeRef = (el) => {
;(el as HTMLInputElement)?.focus()
}
</script>
<template>

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

@ -1,5 +1,5 @@
<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'
const props = defineProps<{
@ -89,8 +89,10 @@ const _createTable = async () => {
onMounted(() => {
generateUniqueTitle()
inputEl.value?.focus()
nextTick(() => {
inputEl.value?.focus()
inputEl.value?.select()
})
})
</script>

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

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

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

@ -184,7 +184,7 @@ async function onSubmit() {
<template>
<a-modal v-model:visible="vModel" class="!top-[35%]" :confirm-loading="loading" wrap-class-name="nc-modal-view-create">
<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') }}
</template>

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

@ -1,4 +1,6 @@
<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'
const props = defineProps<{
@ -24,6 +26,8 @@ const onFinish = async () => {
message.error(await extractSdkResponseErrorMsg(e))
}
}
const focus: VNodeRef = (el: typeof InputPassword) => el?.$el?.querySelector('input').focus()
</script>
<template>
@ -42,7 +46,7 @@ const onFinish = async () => {
<a-form ref="formRef" :model="formState" class="mt-2" @finish="onFinish">
<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-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) => {
console.log('syncAndNavigate', e.target)
if (isJSON(column.value)) return
if (currentRow.value.rowMeta.changed || currentRow.value.rowMeta.new) {
@ -136,7 +135,7 @@ const syncAndNavigate = (dir: NavigateDir, e: KeyboardEvent) => {
>
<template v-if="column">
<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" />
<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" />

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

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

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

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

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

@ -163,12 +163,12 @@ watch(inputs, () => {
v-model:value="element.title"
class="caption"
:data-testid="`select-column-option-input-${index}`"
@keydown.enter.prevent="element.title?.trim() && addNewOption()"
@change="optionChanged(element.id)"
/>
<MdiClose
class="ml-2 hover:!text-black"
:style="{ color: 'red' }"
class="ml-2 hover:!text-black-500 text-gray-500 cursor-pointer"
:data-testid="`select-column-option-remove-${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 saveRowAndStay = ref(0)
const save = async () => {
if (isNew.value) {
const data = await _save(state.value)
@ -34,6 +36,9 @@ const save = async () => {
await _save()
reloadTrigger?.trigger()
}
if (!saveRowAndStay.value) {
emit('cancel')
}
}
// todo: accept as a prop / inject
@ -101,14 +106,39 @@ const copyRecordUrl = () => {
</a-tooltip>
<a-button class="!text mx-1 nc-expand-form-close-btn" @click="emit('cancel')">
<!-- Cancel -->
{{ $t('general.cancel') }}
<div class="flex items-center">
<MdiCloseCircleOutline class="mr-1" />
<!-- Close -->
{{ $t('general.close') }}
</div>
</a-button>
<a-button :disabled="!isUIAllowed('tableRowUpdate')" type="primary" class="mx-1" @click="save">
<!-- Save Row -->
{{ $t('activity.saveRow') }}
</a-button>
<a-dropdown-button class="nc-expand-form-save-btn" type="primary" :disabled="!isUIAllowed('tableRowUpdate')" @click="save">
<template #overlay>
<a-menu class="nc-expand-form-save-dropdown-menu">
<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>
</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 lang="ts">
@ -146,7 +152,7 @@ export default {
<div class="flex-1 overflow-auto scrollbar-thin-dull nc-form-fields-container">
<div class="w-[500px] mx-auto">
<div
v-for="col of fields"
v-for="(col, i) of fields"
v-show="!isVirtualCol(col) || !isNew || col.uidt === UITypes.LinkToAnotherRecord"
:key="col.title"
class="mt-2 py-2"
@ -157,7 +163,7 @@ export default {
<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" />
<LazySmartsheetCell

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

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

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

@ -8,6 +8,7 @@ import {
inject,
ref,
useGlobal,
useMenuCloseOnEsc,
useNuxtApp,
useSmartsheetStoreOrThrow,
useViewFilters,
@ -62,10 +63,14 @@ const filterAutoSaveLoc = computed({
filterAutoSave.value = val
},
})
const open = ref(false)
useMenuCloseOnEsc(open)
</script>
<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 }">
<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">

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

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

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

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

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

@ -5,12 +5,12 @@ import tinycolor from 'tinycolor2'
import {
computed,
extractSdkResponseErrorMsg,
isRtlLang,
message,
projectThemeColors,
ref,
useCopy,
useDashboard,
useDebounceFn,
useI18n,
useNuxtApp,
useProject,
@ -48,12 +48,12 @@ const withRTL = computed({
},
})
const transitionDuration = computed({
get: () => shared.value.meta.transitionDuration || 250,
set: (duration) => {
shared.value.meta = { ...shared.value.meta, transitionDuration: duration > 5000 ? 5000 : duration }
},
})
// const transitionDuration = computed({
// get: () => shared.value.meta.transitionDuration || 50,
// set: (duration) => {
// shared.value.meta = { ...shared.value.meta, transitionDuration: duration > 5000 ? 5000 : duration }
// },
// })
const allowCSVDownload = computed({
get: () => !!shared.value.meta.allowCSVDownload,
@ -131,7 +131,7 @@ async function saveTheme() {
$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() {
try {
@ -192,6 +192,10 @@ watch(passwordProtected, (value) => {
saveShareLinkPassword()
}
})
const { locale } = useI18n()
const isRtl = computed(() => isRtlLang(locale.value as any))
</script>
<template>
@ -248,7 +252,7 @@ watch(passwordProtected, (value) => {
Use Survey Mode
</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">
<a-form-item class="!my-1" :has-feedback="false" name="transitionDuration">
<template #label>
@ -264,46 +268,7 @@ watch(passwordProtected, (value) => {
/>
</a-form-item>
</div>
</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>
</Transition> -->
</div>
<div>
@ -339,20 +304,45 @@ watch(passwordProtected, (value) => {
</Transition>
</div>
<div>
<div
v-if="
shared && (shared.type === ViewTypes.GRID || shared.type === ViewTypes.KANBAN || shared.type === ViewTypes.GALLERY)
"
>
<!-- Allow Download -->
<a-checkbox
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"
>
<a-checkbox v-model:checked="allowCSVDownload" data-testid="nc-modal-share-view__with-csv-download" class="!text-sm">
{{ $t('labels.downloadAllowed') }}
</a-checkbox>
</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>
</a-modal>

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

@ -9,6 +9,7 @@ import {
getSortDirectionOptions,
inject,
ref,
useMenuCloseOnEsc,
useViewSorts,
watch,
} from '#imports'
@ -37,10 +38,14 @@ watch(
},
{ immediate: true },
)
const open = ref(false)
useMenuCloseOnEsc(open)
</script>
<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 }">
<a-button v-e="['c:sort']" class="nc-sort-menu-btn nc-toolbar-btn" :disabled="isLocked">
<div class="flex items-center gap-1">

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

@ -12,6 +12,7 @@ import {
inject,
ref,
useKanbanViewStoreOrThrow,
useMenuCloseOnEsc,
useViewColumns,
watch,
} from '#imports'
@ -30,7 +31,9 @@ const { fields, loadViewColumns, metaColumnById } = useViewColumns(activeView, m
const { kanbanMetaData, loadKanbanMeta, loadKanbanData, updateKanbanMeta, groupingField } = useKanbanViewStoreOrThrow()
const stackedByDropdown = ref(false)
const open = ref(false)
useMenuCloseOnEsc(open)
watch(
() => activeView.value?.id,
@ -68,14 +71,14 @@ const singleSelectFieldOptions = computed<SelectProps['options']>(() => {
})
const handleChange = () => {
stackedByDropdown.value = false
open.value = false
}
</script>
<template>
<a-dropdown
v-if="!IsPublic"
v-model:visible="stackedByDropdown"
v-model:visible="open"
:trigger="['click']"
overlay-class-name="nc-dropdown-kanban-stacked-by-menu"
>
@ -97,7 +100,7 @@ const handleChange = () => {
</div>
<template #overlay>
<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"
@click.stop
>

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

@ -8,6 +8,7 @@ import {
message,
ref,
useI18n,
useMenuCloseOnEsc,
useNuxtApp,
useProject,
useSmartsheetStoreOrThrow,
@ -79,11 +80,15 @@ async function changeLockType(type: LockType) {
}
const { isSqlView } = useSmartsheetStoreOrThrow()
const open = ref(false)
useMenuCloseOnEsc(open)
</script>
<template>
<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">
<div class="flex gap-2 items-center">
<component
@ -103,7 +108,7 @@ const { isSqlView } = useSmartsheetStoreOrThrow()
</a-button>
<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-sub-menu
v-if="isUIAllowed('view-type')"

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

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

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

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

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

@ -97,7 +97,19 @@ const [useProvideColumnCreateStore, useColumnCreateStore] = createInjectionState
const onUidtOrIdTypeChange = () => {
const colProp = sqlUi.value.getDataTypeForUiType(formState.value as { uidt: UITypes }, idType ?? undefined)
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: {},
rqd: 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 { addOrEditStackRow } = useKanbanViewStoreOrThrow()
const { sharedView } = useSharedView()
// getters
@ -197,6 +195,7 @@ const [useProvideExpandedFormStore, useExpandedFormStore] = useInjectionState((m
}
if (activeView.value?.type === ViewTypes.KANBAN) {
const { addOrEditStackRow } = useKanbanViewStoreOrThrow()
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) {
clearRangeRows()
if (selected.row === row && selected.col === col) return
editEnabled.value = false
selected.row = row
selected.col = col
@ -132,7 +133,7 @@ export function useMultiSelect(
const onKeyDown = async (e: KeyboardEvent) => {
// invoke the keyEventHandler if provided and return if it returns true
if (await keyEventHandler?.(e)) {
return
return true
}
if (
@ -267,7 +268,7 @@ export function useMultiSelect(
}
if (unref(editEnabled) || e.ctrlKey || e.altKey || e.metaKey) {
return
return true
}
/** 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 })
formattedData.value = formatData(response.list)
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) {
await loadAggCommentsCount()
}
}
async function loadGalleryData() {
if (!viewMeta?.value?.id) return
if (!viewMeta?.value?.id || isPublic.value) return
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",
"addRow": "Add new row",
"saveRow": "Save row",
"saveAndExit": "Save & Exit",
"saveAndStay": "Save & Stay",
"insertRow": "Insert New Row",
"deleteRow": "Delete Row",
"deleteSelectedRow": "Delete Selected Rows",

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

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

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

@ -85,28 +85,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": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz",
@ -8405,7 +8383,6 @@
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz",
"integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==",
"devOptional": true,
"funding": [
{
"type": "individual",
@ -11761,8 +11738,21 @@
}
},
"node_modules/nocodb-sdk": {
"resolved": "../nocodb-sdk",
"link": true
"version": "0.98.4",
"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": {
"version": "3.23.0",
@ -23571,8 +23561,7 @@
"follow-redirects": {
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz",
"integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==",
"devOptional": true
"integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA=="
},
"form-data": {
"version": "4.0.0",
@ -26040,22 +26029,20 @@
}
},
"nocodb-sdk": {
"version": "file:../nocodb-sdk",
"version": "0.98.4",
"requires": {
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"axios": "^0.21.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",
"jsep": "^1.3.6",
"npm-run-all": "^4.1.5",
"prettier": "^2.1.1",
"typescript": "^4.0.2"
"jsep": "^1.3.6"
},
"dependencies": {
"axios": {
"version": "0.21.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
"requires": {
"follow-redirects": "^1.14.0"
}
}
}
},
"node-abi": {

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

@ -44,7 +44,7 @@ const el = ref<HTMLDivElement>()
provide(DropZoneRef, el)
const transitionDuration = computed(() => sharedViewMeta.value.transitionDuration || 250)
const transitionDuration = computed(() => sharedViewMeta.value.transitionDuration || 50)
const steps = computed(() => {
if (!formColumns.value) return []
@ -305,7 +305,7 @@ onMounted(() => {
</button>
</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
:title="v$.localState[field.title]?.$error ? v$.localState[field.title].$errors[0].$message : 'Go to next'"
:mouse-enter-delay="0.25"

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

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

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

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

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

@ -2,7 +2,8 @@ import type { ColumnType } from 'nocodb-sdk'
import { UITypes } from 'nocodb-sdk'
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) =>
column.uidt === UITypes.SingleLineText || abstractType === 'string'
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
if (len === 2 && UITypes.Number in detectedColTypes && UITypes.Decimal in detectedColTypes) {
if (detectedColTypes[UITypes.Number] > detectedColTypes[UITypes.Decimal]) {
return UITypes.Number
}
return UITypes.Decimal
}
// if there are multiple detected column types
@ -179,8 +176,10 @@ export default class CSVTemplateAdapter {
) {
this.tables[tableIdx].columns[columnIdx].uidt = UITypes.Date
// take the date format with the max occurrence
this.tables[tableIdx].columns[columnIdx].meta.date_format =
Object.keys(dateFormat).reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y)) || 'YYYY/MM/DD'
const objKeys = Object.keys(dateFormat)
this.tables[tableIdx].columns[columnIdx].meta.date_format = objKeys.length
? objKeys.reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y))
: 'YYYY/MM/DD'
} else {
// Datetime
this.tables[tableIdx].columns[columnIdx].uidt = uidt
@ -238,6 +237,8 @@ export default class CSVTemplateAdapter {
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_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_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_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 | | |

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

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

47
packages/nocodb/package-lock.json generated

@ -151,28 +151,6 @@
"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": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-1.1.0.tgz",
@ -10685,8 +10663,13 @@
"dev": true
},
"node_modules/nocodb-sdk": {
"resolved": "../nocodb-sdk",
"link": true
"version": "0.98.4",
"resolved": "file:../nocodb-sdk",
"license": "AGPL-3.0-or-later",
"dependencies": {
"axios": "^0.21.1",
"jsep": "^1.3.6"
}
},
"node_modules/node-abort-controller": {
"version": "3.0.1",
@ -26108,22 +26091,10 @@
"dev": true
},
"nocodb-sdk": {
"version": "file:../nocodb-sdk",
"version": "0.98.4",
"requires": {
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"axios": "^0.21.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",
"jsep": "^1.3.6",
"npm-run-all": "^4.1.5",
"prettier": "^2.1.1",
"typescript": "^4.0.2"
"jsep": "^1.3.6"
}
},
"node-abort-controller": {

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

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

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

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

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

@ -17,8 +17,33 @@ export default `<!DOCTYPE html>
</style>
</head>
<body>
<redoc spec-url='./swagger.json'></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@latest/bundles/redoc.standalone.js"> </script>
<div id="redoc"></div>
<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>
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')

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,
dbType: req.body.dbType,
isEmptyProject: req.body.isEmptyProject,
workerId: req.body.workerId
});
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) {
modelData = await ncMeta.metaGet2(null, null, MetaTable.MODELS, k);
await NocoCache.set(`${CacheScope.MODEL}:${modelData.id}`, modelData);
// if (
// this.baseModels?.[modelData.base_id]?.[modelData.db_alias]?.[
// modelData.title
@ -269,6 +268,7 @@ export default class Model implements TableType {
// }
}
if (modelData) {
await NocoCache.set(`${CacheScope.MODEL}:${modelData.id}`, modelData);
return new Model(modelData);
}
return null;

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

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

3
scripts/sdk/swagger.json

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

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

@ -54,10 +54,21 @@ export class ExpandedFormPage extends BasePage {
async save({
waitForRowsData = true,
saveAndExitMode = true,
}: {
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) {
await this.waitForResponse({
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.verifyToast({ message: `updated successfully.` });
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);
}
async close() {
async escape() {
await this.rootPage.keyboard.press('Escape');
await this.get().waitFor({ state: 'hidden' });
}
async cancel() {
await this.get().locator('button:has-text("Cancel")').last().click();
async close() {
await this.get().locator('button:has-text("Close")').last().click();
}
async openChildCard(param: { column: string; title: string }) {
@ -104,9 +118,9 @@ export class ExpandedFormPage extends BasePage {
async validateRoleAccess(param: { role: string }) {
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 {
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') {
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.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 }) {
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().press('Enter');
await this.get().locator(`[type="submit"]`).click();
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 pg_credentials = () => ({
const pg_credentials = (context: NcContext) => ({
user: 'postgres',
host: 'localhost',
database: `sakila_${process.env.TEST_PARALLEL_INDEX}`,
// todo: Hack to resolve issue with pg resetting
database: `sakila_${context.workerId}`,
password: 'password',
port: 5432,
});
const pgExec = async (query: string) => {
const pgExec = async (query: string, context: NcContext) => {
// open pg client connection
const client = new Client(pg_credentials());
const client = new Client(pg_credentials(context));
await client.connect();
await client.query(query);

18
tests/playwright/setup/index.ts

@ -1,10 +1,14 @@
import { Page, selectors } from '@playwright/test';
import axios from 'axios';
const workerCount = {};
export interface NcContext {
project: any;
token: string;
dbType?: string;
// todo: Hack to resolve issue with pg resetting
workerId?: string;
}
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;
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}`);
let response;
try {
response = await axios.post(`http://localhost:8080/api/v1/meta/test/reset`, {
parallelId: process.env.TEST_PARALLEL_INDEX,
workerId: workerId,
dbType,
isEmptyProject,
});
@ -59,7 +75,7 @@ const setup = async ({ page, isEmptyProject }: { page: Page; isEmptyProject?: bo
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;

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

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

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

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

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

@ -36,13 +36,25 @@ test.describe('Table Column Operations', () => {
columnTitle: 'Title',
value: 'value_a',
});
await dashboard.expandedForm.save();
await dashboard.expandedForm.save({ saveAndExitMode: true });
await grid.cell.verify({
index: 0,
columnHeader: 'Title',
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.verifyRowDoesNotExist({ index: 0 });

Loading…
Cancel
Save