Browse Source

Merge pull request #4406 from nocodb/feat/select-option-creation-from-cell

Feat: Grid - Single/Multi select add option directly from cell if missing
pull/4456/head
Raju Udava 2 years ago committed by GitHub
parent
commit
ef8aebadbb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      packages/nc-gui/components.d.ts
  2. 142
      packages/nc-gui/components/cell/MultiSelect.vue
  3. 111
      packages/nc-gui/components/cell/SingleSelect.vue
  4. 4
      packages/nc-gui/composables/useMultiSelect/index.ts
  5. 1
      packages/nc-gui/nuxt.config.ts
  6. 2
      packages/noco-docs/content/en/getting-started/installation.md
  7. 1
      packages/nocodb/src/lib/Noco.ts
  8. 1
      packages/nocodb/src/lib/meta/api/testApis.ts
  9. 22
      packages/nocodb/src/lib/services/test/TestResetService/index.ts
  10. 44
      tests/playwright/pages/Dashboard/common/Cell/SelectOptionCell.ts
  11. 9
      tests/playwright/setup/db.ts
  12. 18
      tests/playwright/setup/index.ts
  13. 24
      tests/playwright/tests/columnMultiSelect.spec.ts
  14. 12
      tests/playwright/tests/columnSingleSelect.spec.ts
  15. 2
      tests/playwright/tests/metaSync.spec.ts

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

@ -96,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']

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>
<!--
-->

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/composables/useMultiSelect/index.ts

@ -133,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 (
@ -268,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 */

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: {

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/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(

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());

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) {

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++;
}
}
} }

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' });
});
}); });

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;
} }
}); });

Loading…
Cancel
Save