Browse Source

Merge pull request #3300 from nocodb/fix/attachments-shared-view

fix(gui-v2): attachments not loading in shared view
pull/3330/head
Raju Udava 2 years ago committed by GitHub
parent
commit
b2daff16c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      packages/nc-gui-v2/components.d.ts
  2. 5
      packages/nc-gui-v2/components/cell/Text.vue
  3. 34
      packages/nc-gui-v2/components/cell/attachment/index.vue
  4. 61
      packages/nc-gui-v2/components/cell/attachment/utils.ts
  5. 1
      packages/nc-gui-v2/components/general/HelpAndSupport.vue
  6. 168
      packages/nc-gui-v2/components/shared-view/Form.vue
  7. 39
      packages/nc-gui-v2/components/smartsheet-toolbar/SortListMenu.vue
  8. 12
      packages/nc-gui-v2/components/smartsheet/Form.vue
  9. 5
      packages/nc-gui-v2/components/smartsheet/Grid.vue
  10. 62
      packages/nc-gui-v2/composables/useSharedFormViewStore.ts
  11. 28
      packages/nc-gui-v2/composables/useSmartsheetRowStore.ts
  12. 1
      packages/nc-gui-v2/composables/useViewColumns.ts
  13. 12
      packages/nc-gui-v2/layouts/default.vue
  14. 1
      packages/nc-gui-v2/nuxt-shim.d.ts
  15. 30
      packages/nc-gui-v2/pages/[projectType]/form/[viewId].vue
  16. 174
      packages/nc-gui-v2/pages/[projectType]/form/[viewId]/index.vue
  17. 5
      packages/nc-gui-v2/utils/urlUtils.ts
  18. 4
      packages/nc-gui-v2/windi.config.ts

1
packages/nc-gui-v2/components.d.ts vendored

@ -202,6 +202,7 @@ declare module '@vue/runtime-core' {
MdiSearch: typeof import('~icons/mdi/search')['default']
MdiShieldLockOutline: typeof import('~icons/mdi/shield-lock-outline')['default']
MdiSlack: typeof import('~icons/mdi/slack')['default']
MdiSort: typeof import('~icons/mdi/sort')['default']
MdiStar: typeof import('~icons/mdi/star')['default']
MdiStarOutline: typeof import('~icons/mdi/star-outline')['default']
MdiStore: typeof import('~icons/mdi/store')['default']

5
packages/nc-gui-v2/components/cell/Text.vue

@ -1,10 +1,9 @@
<script setup lang="ts">
import type { VNodeRef } from '@vue/runtime-core'
import { inject } from '#imports'
import { EditModeInj } from '~/context'
import { EditModeInj, inject, useVModel } from '#imports'
interface Props {
modelValue: string | null | undefined
modelValue?: string | null
}
const props = defineProps<Props>()

34
packages/nc-gui-v2/components/cell/attachment/index.vue

@ -5,7 +5,9 @@ import { useSortable } from './sort'
import Modal from './Modal.vue'
import Carousel from './Carousel.vue'
import {
IsFormInj,
computed,
inject,
isImage,
openLink,
ref,
@ -16,7 +18,7 @@ import {
} from '#imports'
interface Props {
modelValue: string | Record<string, any>[] | null
modelValue?: string | Record<string, any>[] | null
rowIndex?: number
}
@ -28,6 +30,10 @@ const { modelValue, rowIndex } = defineProps<Props>()
const emits = defineEmits<Emits>()
const isForm = inject(IsFormInj, ref(false))
const attachmentCellRef = ref<HTMLDivElement>()
const sortableRef = ref<HTMLDivElement>()
const { cellRefs } = useSmartsheetStoreOrThrow()!
@ -44,9 +50,17 @@ const {
selectedImage,
isReadonly,
storedFiles,
} = useProvideAttachmentCell(updateModelValue)
} = useProvideAttachmentCell((val) => {
console.log(val)
const currentCellRef = computed(() => cellRefs.value.find((cell) => cell.dataset.key === `${rowIndex}${column.value.id}`))
updateModelValue(val)
})
const currentCellRef = computed(() =>
!rowIndex && isForm.value
? attachmentCellRef.value
: cellRefs.value.find((cell) => cell.dataset.key === `${rowIndex}${column.value.id}`),
)
const { dragging } = useSortable(sortableRef, visibleItems, updateModelValue, isReadonly)
@ -61,7 +75,8 @@ watch(
if (nextModel) {
try {
attachments.value = ((typeof nextModel === 'string' ? JSON.parse(nextModel) : nextModel) || []).filter(Boolean)
} catch {
} catch (e) {
console.error(e)
attachments.value = []
}
}
@ -92,7 +107,10 @@ const { isSharedForm } = useSmartsheetStoreOrThrow()
</script>
<template>
<div class="nc-attachment-cell relative flex-1 color-transition flex items-center justify-between gap-1">
<div
ref="attachmentCellRef"
class="nc-attachment-cell relative flex-1 color-transition flex items-center justify-between gap-1"
>
<Carousel />
<template v-if="isSharedForm || (!isReadonly && !dragging && !!currentCellRef)">
@ -124,6 +142,7 @@ const { isSharedForm } = useSmartsheetStoreOrThrow()
</div>
</a-tooltip>
</div>
<div v-else class="flex" />
<template v-if="visibleItems.length">
<div
@ -133,9 +152,8 @@ const { isSharedForm } = useSmartsheetStoreOrThrow()
>
<div
v-for="(item, i) of visibleItems"
:id="item.url"
:key="item.url || item.title"
:class="isImage(item.title, item.mimetype) ? '' : 'border-1 rounded'"
:class="isImage(item.title, item.mimetype ?? item.type) ? '' : 'border-1 rounded'"
class="nc-attachment flex items-center justify-center min-h-[50px]"
>
<a-tooltip placement="bottom">
@ -144,7 +162,7 @@ const { isSharedForm } = useSmartsheetStoreOrThrow()
</template>
<nuxt-img
v-if="isImage(item.title, item.mimetype)"
v-if="isImage(item.title, item.mimetype ?? item.type) && (item.url || item.data)"
quality="75"
placeholder
:alt="item.title || `#${i}`"

61
packages/nc-gui-v2/components/cell/attachment/utils.ts

@ -1,19 +1,33 @@
import { message } from 'ant-design-vue'
import FileSaver from 'file-saver'
import { computed, inject, ref, useApi, useFileDialog, useInjectionState, useProject, watch } from '#imports'
import { ColumnInj, EditModeInj, IsPublicInj, MetaInj, ReadonlyInj } from '~/context'
import { isImage } from '~/utils'
import { NOCO } from '~/lib'
import {
ColumnInj,
EditModeInj,
IsPublicInj,
MetaInj,
NOCO,
ReadonlyInj,
computed,
inject,
isImage,
ref,
useApi,
useFileDialog,
useInjectionState,
useProject,
watch,
} from '#imports'
import MdiPdfBox from '~icons/mdi/pdf-box'
import MdiFileWordOutline from '~icons/mdi/file-word-outline'
import MdiFilePowerpointBox from '~icons/mdi/file-powerpoint-box'
import MdiFileExcelOutline from '~icons/mdi/file-excel-outline'
import IcOutlineInsertDriveFile from '~icons/ic/outline-insert-drive-file'
interface AttachmentProps {
interface AttachmentProps extends File {
data?: any
file: File
title: string
mimetype: string
}
export const [useProvideAttachmentCell, useAttachmentCell] = useInjectionState(
@ -22,22 +36,14 @@ export const [useProvideAttachmentCell, useAttachmentCell] = useInjectionState(
const isPublic = inject(IsPublicInj, ref(false))
const isForm = inject('isForm', false)
// todo: replace placeholder var
const isPublicGrid = $ref(false)
const meta = inject(MetaInj)!
const column = inject(ColumnInj)!
const editEnabled = inject(EditModeInj, ref(false))
/** keep user selected files data (in base encoded string format) and meta details */
const storedFilesData = ref<{ title: string; file: File }[]>([])
/** keep user selected File object */
const storedFiles = ref<File[]>([])
const storedFiles = ref<AttachmentProps[]>([])
const attachments = ref<File[]>([])
@ -54,37 +60,41 @@ export const [useProvideAttachmentCell, useAttachmentCell] = useInjectionState(
/** remove a file from our stored attachments (either locally stored or saved ones) */
function removeFile(i: number) {
if (isPublic.value) {
storedFilesData.value.splice(i, 1)
storedFiles.value.splice(i, 1)
updateModelValue(storedFilesData.value.map((storedFile) => storedFile.file))
updateModelValue(storedFiles.value.map((stored) => stored.file))
} else {
attachments.value.splice(i, 1)
updateModelValue(attachments.value)
}
}
/** save a file on select / drop, either locally (in-memory) or in the db */
async function onFileSelect(selectedFiles: FileList | File[]) {
if (!selectedFiles.length || isPublicGrid) return
if (!selectedFiles.length) return
if (isPublic.value) {
storedFiles.value.push(...selectedFiles)
storedFilesData.value.push(
storedFiles.value.push(
...(await Promise.all<AttachmentProps>(
Array.from(selectedFiles).map(
(file) =>
new Promise<AttachmentProps>((resolve) => {
const res: AttachmentProps = { file, title: file.name }
if (isImage(file.name, (file as any).mimetype)) {
const res: AttachmentProps = { ...file, file, title: file.name, mimetype: file.type }
if (isImage(file.name, (<any>file).mimetype ?? file.type)) {
const reader = new FileReader()
reader.onload = (e: any) => {
reader.onload = (e) => {
res.data = e.target?.result
resolve(res)
}
reader.onerror = () => {
resolve(res)
}
reader.readAsDataURL(file)
} else {
resolve(res)
@ -94,7 +104,7 @@ export const [useProvideAttachmentCell, useAttachmentCell] = useInjectionState(
)),
)
return updateModelValue(storedFilesData.value.map((storedFile) => storedFile.file))
return updateModelValue(storedFiles.value.map((stored) => stored.file))
}
const newAttachments = []
@ -149,17 +159,14 @@ export const [useProvideAttachmentCell, useAttachmentCell] = useInjectionState(
}
/** our currently visible items, either the locally stored or the ones from db, depending on isPublicForm status */
const visibleItems = computed<any[]>(() => (isPublic.value ? storedFilesData.value : attachments.value) || ([] as any[]))
const visibleItems = computed<any[]>(() => (isPublic.value ? storedFiles.value : attachments.value))
watch(files, (nextFiles) => nextFiles && onFileSelect(nextFiles))
return {
attachments,
storedFilesData,
visibleItems,
isPublic,
isForm,
isPublicGrid,
isReadonly,
meta,
column,

1
packages/nc-gui-v2/components/general/HelpAndSupport.vue

@ -25,6 +25,7 @@ const openSwaggerLink = () => {
</div>
<a-drawer
v-bind="$attrs"
v-model:visible="showDrawer"
class="h-full relative"
placement="right"

168
packages/nc-gui-v2/components/shared-view/Form.vue

@ -1,168 +0,0 @@
<script setup lang="ts">
import { RelationTypes, UITypes, isVirtualCol } from 'nocodb-sdk'
import { useSharedFormStoreOrThrow } from '#imports'
const {
sharedFormView,
submitForm,
v$,
formState,
notFound,
formColumns,
submitted,
secondsRemain,
passwordDlg,
password,
loadSharedView,
} = useSharedFormStoreOrThrow()
function isRequired(_columnObj: Record<string, any>, required = false) {
let columnObj = _columnObj
if (
columnObj.uidt === UITypes.LinkToAnotherRecord &&
columnObj.colOptions &&
columnObj.colOptions.type === RelationTypes.BELONGS_TO
) {
columnObj = formColumns.value?.find((c: Record<string, any>) => c.id === columnObj.colOptions.fk_child_column_id) as Record<
string,
any
>
}
return required || (columnObj && columnObj.rqd && !columnObj.cdf)
}
</script>
<template>
<div class="bg-primary !h-[100vh] overflow-auto w-full flex flex-col">
<div>
<img src="~/assets/img/icons/512x512-trans.png" width="30" class="mx-4 mt-2" />
</div>
<div class="m-4 mt-2 bg-white rounded p-2 flex-1">
<a-alert v-if="notFound" type="warning" class="mx-auto mt-10 max-w-[300px]" message="Not found"> </a-alert>
<template v-else-if="submitted">
<div class="flex justify-center">
<div v-if="sharedFormView" style="min-width: 350px" class="mt-3">
<a-alert type="success" outlined :message="sharedFormView.success_msg || 'Successfully submitted form data'">
</a-alert>
<p v-if="sharedFormView.show_blank_form" class="text-xs text-gray-500 text-center my-4">
New form will be loaded after {{ secondsRemain }} seconds
</p>
<div v-if="sharedFormView.submit_another_form" class="text-center">
<a-button type="primary" @click="submitted = false"> Submit Another Form</a-button>
</div>
</div>
</div>
</template>
<div v-else-if="sharedFormView" class="">
<a-row class="justify-center">
<a-col :md="20">
<div>
<div class="h-full m-0 rounded-b-0">
<div
class="nc-form-wrapper pb-10 rounded shadow-xl"
style="background: linear-gradient(180deg, #dbdbdb 0, #dbdbdb 200px, white 200px)"
>
<div class="mt-10 flex items-center justify-center flex-col">
<div class="nc-form-banner backgroundColor darken-1 flex-col justify-center flex">
<div class="flex items-center justify-center flex-1 h-[100px]">
<img src="~/assets/img/icon.png" width="50" class="mx-4" />
<span class="text-4xl font-weight-bold">NocoDB</span>
</div>
</div>
</div>
<div class="mx-auto nc-form bg-white shadow-lg p-2 mb-10 max-w-[600px] mx-auto rounded">
<h2 class="mt-4 text-4xl font-weight-bold text-left mx-4 mb-3 px-1">
{{ sharedFormView.heading }}
</h2>
<div class="text-lg text-left mx-4 py-2 px-1 text-gray-500">
{{ sharedFormView.subheading }}
</div>
<div class="h-full">
<div v-for="(field, index) in formColumns" :key="index" class="flex flex-col mt-4 px-4 space-y-2">
<div class="flex">
<SmartsheetHeaderVirtualCell
v-if="isVirtualCol(field)"
:column="{ ...field, title: field.label || field.title }"
:required="isRequired(field, field.required)"
:hide-menu="true"
/>
<SmartsheetHeaderCell
v-else
:column="{ ...field, title: field.label || field.title }"
:required="isRequired(field, field.required)"
:hide-menu="true"
/>
</div>
<div v-if="isVirtualCol(field)" class="mt-0">
<SmartsheetVirtualCell class="mt-0 nc-input" :column="field" />
<div v-if="field.description" class="text-gray-500 text-[10px] mb-2 ml-1">{{ field.description }}</div>
<template v-if="v$.virtual.$dirty && v$.virtual?.[field.title]">
<div v-for="error of v$.virtual[field.title].$errors" :key="error" class="text-xs text-red-500">
{{ error.$message }}
</div>
</template>
</div>
<div v-else class="mt-0">
<SmartsheetCell
v-model="formState[field.title]"
class="nc-input"
:column="field"
:edit-enabled="true"
/>
<div v-if="field.description" class="text-gray-500 text-[10px] mb-2 ml-1">{{ field.description }}</div>
<template v-if="v$.localState.$dirty && v$.localState?.[field.title]">
<div v-for="error of v$.localState[field.title].$errors" :key="error" class="text-xs text-red-500">
{{ error.$message }}
</div>
</template>
</div>
</div>
<div class="text-center my-9">
<a-button type="primary" size="large" @click="submitForm(formState, additionalState)"> Submit</a-button>
</div>
</div>
</div>
</div>
</div>
</div>
</a-col>
</a-row>
</div>
</div>
<a-modal
v-model:visible="passwordDlg"
:closable="false"
width="28rem"
centered
:footer="null"
:mask-closable="false"
@close="passwordDlg = false"
>
<div class="w-full flex flex-col">
<a-typography-title :level="4">This shared view is protected</a-typography-title>
<a-form ref="formRef" :model="{ password }" class="mt-2" @finish="loadSharedView">
<a-form-item name="password" :rules="[{ required: true, message: 'Password is required' }]">
<a-input-password v-model:value="password" placeholder="Enter password" />
</a-form-item>
<a-button type="primary" html-type="submit">Unlock</a-button>
</a-form>
</div>
</a-modal>
</div>
</template>
<style scoped lang="scss">
.nc-input {
@apply w-full !bg-white rounded px-2 py-2 min-h-[40px] mt-2 mb-2 flex items-center border-solid border-1 border-primary;
}
.nc-form-wrapper {
@apply my-0 mx-auto max-w-[800px];
}
</style>

39
packages/nc-gui-v2/components/smartsheet-toolbar/SortListMenu.vue

@ -1,27 +1,34 @@
<script setup lang="ts">
import type { ColumnType } from 'nocodb-sdk'
import FieldListAutoCompleteDropdown from './FieldListAutoCompleteDropdown.vue'
import { getSortDirectionOptions } from '~/utils/sortUtils'
import { computed, inject, useViewSorts } from '#imports'
import { ActiveViewInj, IsLockedInj, MetaInj, ReloadViewDataHookInj } from '~/context'
import MdiMenuDownIcon from '~icons/mdi/menu-down'
import MdiSortIcon from '~icons/mdi/sort'
import MdiDeleteIcon from '~icons/mdi/close-box'
import MdiAddIcon from '~icons/mdi/plus'
import {
ActiveViewInj,
IsLockedInj,
MetaInj,
ReloadViewDataHookInj,
computed,
getSortDirectionOptions,
inject,
ref,
useViewSorts,
watch,
} from '#imports'
const meta = inject(MetaInj)
const view = inject(ActiveViewInj)
const isLocked = inject(IsLockedInj)
const isLocked = inject(IsLockedInj, ref(false))
const reloadDataHook = inject(ReloadViewDataHookInj)
const { sorts, saveOrUpdate, loadSorts, addSort, deleteSort } = useViewSorts(view, () => reloadDataHook?.trigger())
const columns = computed(() => meta?.value?.columns || [])
const columnByID = computed<Record<string, ColumnType>>(() =>
columns?.value?.reduce((obj: any, col: any) => {
obj[col.id] = col
const columnByID = computed(() =>
columns.value.reduce((obj, col) => {
obj[col.id!] = col
return obj
}, {}),
}, {} as Record<string, ColumnType>),
)
watch(
@ -38,10 +45,10 @@ watch(
<div :class="{ 'nc-badge nc-active-btn': sorts?.length }">
<a-button v-t="['c:sort']" class="nc-sort-menu-btn nc-toolbar-btn" :disabled="isLocked"
><div class="flex items-center gap-1">
<MdiSortIcon />
<MdiSort />
<!-- Sort -->
<span class="text-capitalize !text-sm font-weight-normal">{{ $t('activity.sort') }}</span>
<MdiMenuDownIcon class="text-grey" />
<MdiMenuDown class="text-grey" />
</div>
</a-button>
</div>
@ -49,7 +56,7 @@ watch(
<div class="bg-gray-50 p-6 shadow-lg menu-filter-dropdown min-w-[400px] max-h-[max(80vh,500px)] overflow-auto !border">
<div v-if="sorts?.length" class="sort-grid mb-2" @click.stop>
<template v-for="(sort, i) in sorts || []" :key="i">
<MdiDeleteIcon class="nc-sort-item-remove-btn text-grey self-center" small @click.stop="deleteSort(sort, i)" />
<MdiCloseBox class="nc-sort-item-remove-btn text-grey self-center" small @click.stop="deleteSort(sort, i)" />
<FieldListAutoCompleteDropdown
v-model="sort.fk_column_id"
@ -79,7 +86,7 @@ watch(
</div>
<a-button class="text-capitalize mb-1 mt-4" type="primary" ghost @click.stop="addSort">
<div class="flex gap-1 items-center">
<MdiAddIcon />
<MdiPlus />
<!-- Add Sort Option -->
{{ $t('activity.addSort') }}
</div>

12
packages/nc-gui-v2/components/smartsheet/Form.vue

@ -152,9 +152,8 @@ function onMoveCallback(event: any) {
function onMove(event: any) {
const { newIndex, element, oldIndex } = event.added || event.moved || event.removed
console.log(event)
if (shouldSkipColumn(element)) {
console.log('SKIPPED')
return
}
@ -408,7 +407,14 @@ onMounted(async () => {
</div>
</div>
</div>
<Draggable :list="hiddenColumns" draggable=".item" group="form-inputs" @start="drag = true" @end="drag = false">
<Draggable
:list="hiddenColumns"
item-key="id"
draggable=".item"
group="form-inputs"
@start="drag = true"
@end="drag = false"
>
<template #item="{ element }">
<a-card
size="small"

5
packages/nc-gui-v2/components/smartsheet/Grid.vue

@ -15,6 +15,7 @@ import {
PaginationDataInj,
ReadonlyInj,
ReloadViewDataHookInj,
createEventHook,
enumColor,
inject,
onClickOutside,
@ -44,8 +45,8 @@ const fields = inject(FieldsInj, ref([]))
const readOnly = inject(ReadonlyInj, false)
const isLocked = inject(IsLockedInj, ref(false))
const reloadViewDataHook = inject(ReloadViewDataHookInj)
const openNewRecordFormHook = inject(OpenNewRecordFormHookInj)
const reloadViewDataHook = inject(ReloadViewDataHookInj, createEventHook())
const openNewRecordFormHook = inject(OpenNewRecordFormHookInj, createEventHook())
const { isUIAllowed } = useUIPermission()

62
packages/nc-gui-v2/composables/useSharedFormViewStore.ts

@ -1,12 +1,21 @@
import useVuelidate from '@vuelidate/core'
import { minLength, required } from '@vuelidate/validators'
import type { Ref } from 'vue'
import { message } from 'ant-design-vue'
import type { ColumnType, FormType, LinkToAnotherRecordType, TableType, ViewType } from 'nocodb-sdk'
import { ErrorMessages, RelationTypes, UITypes, isVirtualCol } from 'nocodb-sdk'
import type { Ref } from 'vue'
import { SharedViewPasswordInj } from '~/context'
import { extractSdkResponseErrorMsg } from '~/utils'
import { useInjectionState, useMetas } from '#imports'
import {
SharedViewPasswordInj,
computed,
extractSdkResponseErrorMsg,
provide,
ref,
useApi,
useInjectionState,
useMetas,
useProvideSmartsheetRowStore,
watch,
} from '#imports'
const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((sharedViewId: string) => {
const progress = ref(false)
@ -23,8 +32,10 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
const meta = ref<TableType>()
const columns = ref<(ColumnType & { required?: boolean; show?: boolean })[]>()
const { $api } = useNuxtApp()
const { api, isLoading } = useApi()
const { metas, setMeta } = useMetas()
const formState = ref({})
const { state: additionalState } = useProvideSmartsheetRowStore(
@ -37,11 +48,11 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
)
const formColumns = computed(() =>
columns?.value?.filter((c) => c.show)?.filter((col) => !isVirtualCol(col) || col.uidt === UITypes.LinkToAnotherRecord),
columns.value?.filter((c) => c.show).filter((col) => !isVirtualCol(col) || col.uidt === UITypes.LinkToAnotherRecord),
)
const loadSharedView = async () => {
try {
const viewMeta = await $api.public.sharedViewMetaGet(sharedViewId, {
const viewMeta: Record<string, any> = await api.public.sharedViewMetaGet(sharedViewId, {
headers: {
'xc-password': password.value,
},
@ -54,9 +65,10 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
meta.value = viewMeta.model
columns.value = viewMeta.model?.columns
setMeta(viewMeta.model)
await setMeta(viewMeta.model)
const relatedMetas = { ...viewMeta.relatedMetas }
Object.keys(relatedMetas).forEach((key) => setMeta(relatedMetas[key]))
} catch (e: any) {
if (e.response && e.response.status === 404) {
@ -68,11 +80,14 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
}
const validators = computed(() => {
const obj: any = {
const obj: Record<string, Record<string, any>> = {
localState: {},
virtual: {},
}
for (const column of formColumns?.value ?? []) {
if (!formColumns.value) return obj
for (const column of formColumns.value) {
if (
!isVirtualCol(column) &&
((column.rqd && !column.cdf) || (column.pk && !(column.ai || column.cdf)) || (column as any).required)
@ -103,7 +118,7 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
const v$ = useVuelidate(
validators,
computed(() => ({ localState: formState?.value, virtual: additionalState?.value })),
computed(() => ({ localState: formState.value, virtual: additionalState.value })),
)
const submitForm = async () => {
@ -113,18 +128,20 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
}
progress.value = true
const data: Record<string, any> = { ...(formState?.value ?? {}), ...(additionalState?.value || {}) }
const data: Record<string, any> = { ...formState.value, ...additionalState.value }
const attachment: Record<string, any> = {}
for (const col of metas?.value?.[sharedView?.value?.fk_model_id as string]?.columns ?? []) {
/** find attachments in form data */
for (const col of metas.value?.[sharedView.value?.fk_model_id as string]?.columns) {
if (col.uidt === UITypes.Attachment) {
attachment[`_${col.title}`] = data[col.title!]
delete data[col.title!]
if (data[col.title]) {
attachment[`_${col.title}`] = data[col.title].map((item: { file: File }) => item.file)
}
}
}
await $api.public.dataCreate(
sharedView?.value?.uuid as string,
await api.public.dataCreate(
(sharedView.value as any)?.uuid as string,
{
data,
...attachment,
@ -139,7 +156,7 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
submitted.value = true
progress.value = false
await message.success(sharedFormView.value?.success_msg || 'Saved successfully.')
await message.success(sharedFormView.value?.sucess_msg || 'Saved successfully.')
} catch (e: any) {
console.log(e)
await message.error(await extractSdkResponseErrorMsg(e))
@ -148,13 +165,15 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
}
/** reset form if show_blank_form is true */
watch(submitted, (nextVal: boolean) => {
if (nextVal && sharedFormView.value?.show_blank_form) {
watch(submitted, (nextVal) => {
if (nextVal && (sharedFormView.value as any)?.show_blank_form) {
secondsRemain.value = 5
const intvl = setInterval(() => {
secondsRemain.value = secondsRemain.value - 1
if (secondsRemain.value < 0) {
submitted.value = false
clearInterval(intvl)
}
}, 1000)
@ -185,6 +204,7 @@ const [useProvideSharedFormStore, useSharedFormStore] = useInjectionState((share
submitted,
secondsRemain,
passwordDlg,
isLoading,
}
}, 'expanded-form-store')
@ -192,6 +212,8 @@ export { useProvideSharedFormStore }
export function useSharedFormStoreOrThrow() {
const sharedFormStore = useSharedFormStore()
if (sharedFormStore == null) throw new Error('Please call `useProvideSharedFormStore` on the appropriate parent component')
return sharedFormStore
}

28
packages/nc-gui-v2/composables/useSmartsheetRowStore.ts

@ -2,27 +2,41 @@ import { message } from 'ant-design-vue'
import { UITypes } from 'nocodb-sdk'
import type { ColumnType, LinkToAnotherRecordType, RelationTypes, TableType } from 'nocodb-sdk'
import type { Ref } from 'vue'
import type { MaybeRef } from '@vueuse/core'
import type { Row } from './useViewData'
import { useInjectionState, useMetas, useNuxtApp, useProject, useVirtualCell } from '#imports'
import { NOCO } from '~/lib'
import { deepCompare, extractPkFromRow, extractSdkResponseErrorMsg } from '~/utils'
import {
NOCO,
computed,
deepCompare,
extractPkFromRow,
extractSdkResponseErrorMsg,
ref,
unref,
useInjectionState,
useMetas,
useNuxtApp,
useProject,
useVirtualCell,
} from '#imports'
const [useProvideSmartsheetRowStore, useSmartsheetRowStore] = useInjectionState((meta: Ref<TableType>, row: Ref<Row>) => {
const [useProvideSmartsheetRowStore, useSmartsheetRowStore] = useInjectionState((meta: Ref<TableType>, row: MaybeRef<Row>) => {
const { $api } = useNuxtApp()
const { project } = useProject()
const { metas } = useMetas()
// state
const state = ref<Record<string, Record<string, any> | Record<string, any>[] | null>>({})
// getters
const isNew = computed(() => row.value?.rowMeta?.new ?? false)
const isNew = computed(() => unref(row).rowMeta?.new ?? false)
// actions
const addLTARRef = async (value: Record<string, any>, column: ColumnType) => {
const { isHm, isMm, isBt } = $(useVirtualCell(ref(column)))
if (isHm || isMm) {
state.value[column.title!] = state.value[column.title!] || []
if (!state.value[column.title!]) state.value[column.title!] = []
if (state.value[column.title!]!.find((ln: Record<string, any>) => deepCompare(ln, value))) {
return message.info('This value is already in the list')
@ -106,6 +120,8 @@ export { useProvideSmartsheetRowStore }
export function useSmartsheetRowStoreOrThrow() {
const smartsheetRowStore = useSmartsheetRowStore()
if (smartsheetRowStore == null) throw new Error('Please call `useSmartsheetRowStore` on the appropriate parent component')
return smartsheetRowStore
}

1
packages/nc-gui-v2/composables/useViewColumns.ts

@ -51,6 +51,7 @@ export function useViewColumns(view: Ref<ViewType> | undefined, meta: ComputedRe
[curr.fk_column_id]: curr,
}
}, {})
fields.value = meta.value?.columns
?.map((column: ColumnType) => {
const currentColumnField = fieldById[column.id!] || {}

12
packages/nc-gui-v2/layouts/default.vue

@ -1,14 +1,14 @@
<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
import { useHead, useRoute } from '#imports'
import { useTitle } from '@vueuse/core'
import { useI18n, useRoute, useSidebar } from '#imports'
const route = useRoute()
const { te, t } = useI18n()
useHead({
title: route.meta?.title && te(route.meta.title as string) ? `${t(route.meta.title as string)} | NocoDB` : 'NocoDB',
})
const { hasSidebar } = useSidebar()
useTitle(route.meta?.title && te(route.meta.title) ? `${t(route.meta.title)} | NocoDB` : 'NocoDB')
</script>
<script lang="ts">
@ -19,7 +19,7 @@ export default {
<template>
<div class="w-full h-full">
<Teleport to="#nc-sidebar-left">
<Teleport :to="hasSidebar ? '#nc-sidebar-left' : null" :disabled="!hasSidebar">
<slot name="sidebar" />
</Teleport>

1
packages/nc-gui-v2/nuxt-shim.d.ts vendored

@ -30,5 +30,6 @@ declare module 'vue-router' {
requiresAuth?: boolean
public?: boolean
hideHeader?: boolean
title?: string
}
}

30
packages/nc-gui-v2/pages/[projectType]/form/[viewId].vue

@ -1,23 +1,35 @@
<script setup lang="ts">
import type { Ref } from 'vue'
import type { TableType } from 'nocodb-sdk/build/main'
import { useProvideSharedFormStore } from '~/composables/useSharedFormViewStore'
import { IsFormInj, IsPublicInj, MetaInj, ReloadViewDataHookInj } from '~/context'
import { createEventHook, definePageMeta, provide, ref, useProvideSmartsheetStore, useRoute } from '#imports'
import type { TableType } from 'nocodb-sdk'
import {
IsFormInj,
IsPublicInj,
MetaInj,
ReloadViewDataHookInj,
createEventHook,
definePageMeta,
provide,
ref,
useProvideSharedFormStore,
useProvideSmartsheetStore,
useRoute,
useSidebar,
} from '#imports'
definePageMeta({
public: true,
})
const route = useRoute()
useSidebar({ hasSidebar: false })
const reloadEventHook = createEventHook<void>()
const route = useRoute()
const { loadSharedView, sharedView, meta, notFound } = useProvideSharedFormStore(route.params.viewId as string)
await loadSharedView()
if (!notFound.value) {
provide(ReloadViewDataHookInj, reloadEventHook)
provide(ReloadViewDataHookInj, createEventHook())
provide(MetaInj, meta)
provide(IsPublicInj, ref(true))
provide(IsFormInj, ref(true))
@ -27,5 +39,7 @@ if (!notFound.value) {
</script>
<template>
<SharedViewForm />
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>

174
packages/nc-gui-v2/pages/[projectType]/form/[viewId]/index.vue

@ -0,0 +1,174 @@
<script setup lang="ts">
import { RelationTypes, UITypes, isVirtualCol } from 'nocodb-sdk'
import { useSharedFormStoreOrThrow } from '#imports'
const {
sharedFormView,
submitForm,
v$,
formState,
notFound,
formColumns,
submitted,
secondsRemain,
passwordDlg,
password,
loadSharedView,
isLoading,
} = useSharedFormStoreOrThrow()
function isRequired(_columnObj: Record<string, any>, required = false) {
let columnObj = _columnObj
if (
columnObj.uidt === UITypes.LinkToAnotherRecord &&
columnObj.colOptions &&
columnObj.colOptions.type === RelationTypes.BELONGS_TO
) {
columnObj = formColumns.value?.find((c) => c.id === columnObj.colOptions.fk_child_column_id) as Record<string, any>
}
return !!(required || (columnObj && columnObj.rqd && !columnObj.cdf))
}
</script>
<template>
<div
class="nc-form-view md:bg-primary bg-opacity-5 h-full min-h-[600px] flex flex-col justify-center items-center nc-form-signin"
>
<div
class="bg-white mt-[60px] relative flex flex-col justify-center gap-2 w-full lg:max-w-1/2 max-w-500px mx-auto p-8 md:(rounded-lg border-1 border-gray-200 shadow-xl)"
>
<general-noco-icon class="color-transition hover:(ring ring-accent)" :class="[isLoading ? 'animated-bg-gradient' : '']" />
<h1 class="prose-2xl font-bold self-center my-4">{{ sharedFormView.heading }}</h1>
<h2 v-if="sharedFormView.subheading" class="prose-lg text-gray-500 self-center">{{ sharedFormView.subheading }}</h2>
<a-alert v-if="notFound" type="warning" class="my-4 text-center" message="Not found" />
<template v-else-if="submitted">
<div class="flex justify-center">
<div v-if="sharedFormView" class="min-w-350px mt-3">
<a-alert
type="success"
class="my-4 text-center"
outlined
:message="sharedFormView.success_msg || 'Successfully submitted form data'"
/>
<p v-if="sharedFormView.show_blank_form" class="text-xs text-gray-500 text-center my-4">
New form will be loaded after {{ secondsRemain }} seconds
</p>
<div v-if="sharedFormView.submit_another_form" class="text-center">
<a-button type="primary" @click="submitted = false"> Submit Another Form</a-button>
</div>
</div>
</div>
</template>
<template v-else-if="sharedFormView">
<div class="nc-form-wrapper">
<div class="nc-form h-full max-w-3/4 mx-auto">
<div v-for="(field, index) in formColumns" :key="index" class="flex flex-col my-6 gap-2">
<div class="flex">
<SmartsheetHeaderVirtualCell
v-if="isVirtualCol(field)"
:column="{ ...field, title: field.label || field.title }"
:required="isRequired(field, field.required)"
:hide-menu="true"
/>
<SmartsheetHeaderCell
v-else
:column="{ ...field, title: field.label || field.title }"
:required="isRequired(field, field.required)"
:hide-menu="true"
/>
</div>
<div v-if="isVirtualCol(field)" class="mt-0">
<SmartsheetVirtualCell class="mt-0 nc-input" :column="field" />
<div v-if="field.description" class="text-gray-500 text-[10px] mb-2 ml-1">{{ field.description }}</div>
<template v-if="v$.virtual.$dirty && v$.virtual?.[field.title]">
<div v-for="error of v$.virtual[field.title].$errors" :key="error" class="text-xs text-red-500">
{{ error.$message }}
</div>
</template>
</div>
<div v-else class="mt-0">
<SmartsheetCell v-model="formState[field.title]" class="nc-input" :column="field" :edit-enabled="true" />
<div v-if="field.description" class="text-gray-500 text-[10px] mb-2 ml-1">{{ field.description }}</div>
<template v-if="v$.localState.$dirty && v$.localState?.[field.title]">
<div v-for="error of v$.localState[field.title].$errors" :key="error" class="text-xs text-red-500">
{{ error.$message }}
</div>
</template>
</div>
</div>
<div class="text-center my-9">
<button type="submit" class="submit" @click="submitForm">
{{ $t('general.submit') }}
</button>
</div>
</div>
</div>
</template>
<a-modal
v-model:visible="passwordDlg"
:closable="false"
width="28rem"
centered
:footer="null"
:mask-closable="false"
@close="passwordDlg = false"
>
<div class="w-full flex flex-col">
<a-typography-title :level="4">This shared view is protected</a-typography-title>
<a-form ref="formRef" :model="{ password }" class="mt-2" @finish="loadSharedView">
<a-form-item name="password" :rules="[{ required: true, message: $t('msg.error.signUpRules.passwdRequired') }]">
<a-input-password v-model:value="password" :placeholder="$t('msg.info.signUp.enterPassword')" />
</a-form-item>
<!-- todo: i18n -->
<a-button type="primary" html-type="submit">Unlock</a-button>
</a-form>
</div>
</a-modal>
</div>
</div>
</template>
<style lang="scss">
.nc-form-view {
.nc-input {
@apply w-full rounded p-2 min-h-[40px] flex items-center border-solid border-1 border-primary;
}
.submit {
@apply z-1 relative color-transition rounded p-3 text-white shadow-sm;
&::after {
@apply rounded absolute top-0 left-0 right-0 bottom-0 transition-all duration-150 ease-in-out bg-primary;
content: '';
z-index: -1;
}
&:hover::after {
@apply transform scale-110 ring ring-accent;
}
&:active::after {
@apply ring ring-accent;
}
}
}
</style>

5
packages/nc-gui-v2/utils/urlUtils.ts

@ -21,10 +21,11 @@ export const replaceUrlsWithLink = (text: string): boolean | string => {
export const isValidURL = (str: string) => {
const pattern =
/^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00A1-\uFFFF0-9]-*)*[a-z\u00A1-\uFFFF0-9]+)(?:\.(?:[a-z\u00A1-\uFFFF0-9]-*)*[a-z\u00A1-\uFFFF0-9]+)*(?:\.(?:[a-z\u00A1-\uFFFF]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i
return !!pattern.test(str)
return pattern.test(str)
}
export const openLink = (path: string, baseURL: string, target = '_blank') => {
export const openLink = (path: string, baseURL?: string, target = '_blank') => {
const url = new URL(path, baseURL)
window.open(url.href, target)
}

4
packages/nc-gui-v2/windi.config.ts

@ -65,10 +65,6 @@ export default defineConfig({
primary: 'rgba(var(--color-primary), var(--tw-bg-opacity))',
accent: 'rgba(var(--color-accent), var(--tw-bg-opacity))',
},
ringColor: {
primary: 'rgba(var(--color-primary), var(--tw-ring-opacity))',
accent: 'rgba(var(--color-accent), var(--tw-ring-opacity))',
},
colors: {
...windiColors,
...themeColors,

Loading…
Cancel
Save