mirror of https://github.com/nocodb/nocodb
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
675 lines
22 KiB
675 lines
22 KiB
2 years ago
|
<script setup lang="ts">
|
||
2 years ago
|
import type { Ref } from 'vue'
|
||
2 years ago
|
import type { ListItem as AntListItem } from 'ant-design-vue'
|
||
2 years ago
|
import jsep from 'jsep'
|
||
2 years ago
|
import type { ColumnType } from 'nocodb-sdk'
|
||
2 years ago
|
import { UITypes, jsepCurlyHook } from 'nocodb-sdk'
|
||
2 years ago
|
import {
|
||
2 years ago
|
MetaInj,
|
||
2 years ago
|
NcAutocompleteTree,
|
||
|
formulaList,
|
||
|
formulaTypes,
|
||
|
formulas,
|
||
|
getUIDTIcon,
|
||
|
getWordUntilCaret,
|
||
|
insertAtCursor,
|
||
2 years ago
|
onMounted,
|
||
|
useColumnCreateStoreOrThrow,
|
||
|
useDebounceFn,
|
||
2 years ago
|
validateDateWithUnknownFormat,
|
||
2 years ago
|
} from '#imports'
|
||
2 years ago
|
|
||
2 years ago
|
interface Props {
|
||
|
value: Record<string, any>
|
||
|
}
|
||
|
|
||
|
const props = defineProps<Props>()
|
||
|
const emit = defineEmits(['update:value'])
|
||
|
const vModel = useVModel(props, 'value', emit)
|
||
|
|
||
|
const { setAdditionalValidations, validateInfos, sqlUi, column } = useColumnCreateStoreOrThrow()
|
||
|
|
||
2 years ago
|
enum JSEPNode {
|
||
|
COMPOUND = 'Compound',
|
||
|
IDENTIFIER = 'Identifier',
|
||
|
MEMBER_EXP = 'MemberExpression',
|
||
|
LITERAL = 'Literal',
|
||
|
THIS_EXP = 'ThisExpression',
|
||
|
CALL_EXP = 'CallExpression',
|
||
|
UNARY_EXP = 'UnaryExpression',
|
||
|
BINARY_EXP = 'BinaryExpression',
|
||
|
ARRAY_EXP = 'ArrayExpression',
|
||
|
}
|
||
|
|
||
2 years ago
|
const meta = inject(MetaInj)
|
||
|
|
||
|
const columns = computed(() => meta?.value?.columns || [])
|
||
|
|
||
2 years ago
|
const validators = {
|
||
2 years ago
|
formula_raw: [
|
||
2 years ago
|
{
|
||
2 years ago
|
validator: (_: any, formula: any) => {
|
||
2 years ago
|
return new Promise<void>((resolve, reject) => {
|
||
2 years ago
|
const res = parseAndValidateFormula(formula)
|
||
|
if (res !== true) {
|
||
|
return reject(new Error(res))
|
||
2 years ago
|
}
|
||
2 years ago
|
resolve()
|
||
|
})
|
||
|
},
|
||
|
},
|
||
|
],
|
||
|
}
|
||
|
|
||
2 years ago
|
const availableFunctions = formulaList
|
||
|
|
||
|
const availableBinOps = ['+', '-', '*', '/', '>', '<', '==', '<=', '>=', '!=']
|
||
|
|
||
|
const autocomplete = ref(false)
|
||
|
|
||
2 years ago
|
const formulaRef = ref()
|
||
|
|
||
|
const sugListRef = ref()
|
||
|
|
||
2 years ago
|
const sugOptionsRef = ref<typeof AntListItem[]>([])
|
||
2 years ago
|
|
||
|
const wordToComplete = ref<string | undefined>('')
|
||
2 years ago
|
|
||
|
const selected = ref(0)
|
||
|
|
||
2 years ago
|
const sortOrder: Record<string, number> = {
|
||
2 years ago
|
column: 0,
|
||
|
function: 1,
|
||
|
op: 2,
|
||
|
}
|
||
2 years ago
|
|
||
|
const suggestionsList = computed(() => {
|
||
2 years ago
|
const unsupportedFnList = sqlUi.value.getUnsupportedFnList()
|
||
|
return [
|
||
|
...availableFunctions
|
||
2 years ago
|
.filter((fn: string) => !unsupportedFnList.includes(fn))
|
||
|
.map((fn: string) => ({
|
||
2 years ago
|
text: `${fn}()`,
|
||
|
type: 'function',
|
||
|
description: formulas[fn].description,
|
||
|
syntax: formulas[fn].syntax,
|
||
|
examples: formulas[fn].examples,
|
||
|
})),
|
||
|
...columns.value
|
||
2 years ago
|
.filter((c: Record<string, any>) => {
|
||
|
// skip system LTAR columns
|
||
|
if (c.uidt === UITypes.LinkToAnotherRecord && c.system) return false
|
||
|
// v1 logic? skip the current column
|
||
|
if (!column) return true
|
||
|
return column.value.id !== c.id
|
||
|
})
|
||
2 years ago
|
.map((c: any) => ({
|
||
|
text: c.title,
|
||
|
type: 'column',
|
||
|
icon: getUIDTIcon(c.uidt),
|
||
2 years ago
|
uidt: c.uidt,
|
||
2 years ago
|
})),
|
||
|
...availableBinOps.map((op: string) => ({
|
||
|
text: op,
|
||
|
type: 'op',
|
||
|
})),
|
||
|
]
|
||
2 years ago
|
})
|
||
|
|
||
2 years ago
|
// set default suggestion list
|
||
2 years ago
|
const suggestion: Ref<Record<string, any>[]> = ref(suggestionsList.value)
|
||
2 years ago
|
|
||
2 years ago
|
const acTree = computed(() => {
|
||
|
const ref = new NcAutocompleteTree()
|
||
|
for (const sug of suggestionsList.value) {
|
||
|
ref.add(sug)
|
||
|
}
|
||
|
return ref
|
||
|
})
|
||
|
|
||
|
function parseAndValidateFormula(formula: string) {
|
||
|
try {
|
||
|
const parsedTree = jsep(formula)
|
||
|
const metaErrors = validateAgainstMeta(parsedTree)
|
||
2 years ago
|
if (metaErrors.size) {
|
||
2 years ago
|
return [...metaErrors].join(', ')
|
||
|
}
|
||
|
return true
|
||
|
} catch (e: any) {
|
||
|
return e.message
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function validateAgainstMeta(parsedTree: any, errors = new Set(), typeErrors = new Set()) {
|
||
2 years ago
|
if (parsedTree.type === JSEPNode.CALL_EXP) {
|
||
2 years ago
|
// validate function name
|
||
|
if (!availableFunctions.includes(parsedTree.callee.name)) {
|
||
|
errors.add(`'${parsedTree.callee.name}' function is not available`)
|
||
|
}
|
||
|
// validate arguments
|
||
|
const validation = formulas[parsedTree.callee.name] && formulas[parsedTree.callee.name].validation
|
||
|
if (validation && validation.args) {
|
||
|
if (validation.args.rqd !== undefined && validation.args.rqd !== parsedTree.arguments.length) {
|
||
|
errors.add(`'${parsedTree.callee.name}' required ${validation.args.rqd} arguments`)
|
||
|
} else if (validation.args.min !== undefined && validation.args.min > parsedTree.arguments.length) {
|
||
|
errors.add(`'${parsedTree.callee.name}' required minimum ${validation.args.min} arguments`)
|
||
|
} else if (validation.args.max !== undefined && validation.args.max < parsedTree.arguments.length) {
|
||
|
errors.add(`'${parsedTree.callee.name}' required maximum ${validation.args.max} arguments`)
|
||
|
}
|
||
|
}
|
||
|
parsedTree.arguments.map((arg: Record<string, any>) => validateAgainstMeta(arg, errors))
|
||
|
|
||
|
// validate data type
|
||
2 years ago
|
if (parsedTree.callee.type === JSEPNode.IDENTIFIER) {
|
||
2 years ago
|
const expectedType = formulas[parsedTree.callee.name].type
|
||
|
if (expectedType === formulaTypes.NUMERIC) {
|
||
|
if (parsedTree.callee.name === 'WEEKDAY') {
|
||
|
// parsedTree.arguments[0] = date
|
||
|
validateAgainstType(
|
||
|
parsedTree.arguments[0],
|
||
|
formulaTypes.DATE,
|
||
|
(v: any) => {
|
||
|
if (!validateDateWithUnknownFormat(v)) {
|
||
|
typeErrors.add('The first parameter of WEEKDAY() should have date value')
|
||
|
}
|
||
|
},
|
||
|
typeErrors,
|
||
|
)
|
||
|
// parsedTree.arguments[1] = startDayOfWeek (optional)
|
||
|
validateAgainstType(
|
||
|
parsedTree.arguments[1],
|
||
|
formulaTypes.STRING,
|
||
|
(v: any) => {
|
||
|
if (
|
||
|
typeof v !== 'string' ||
|
||
|
!['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'].includes(v.toLowerCase())
|
||
|
) {
|
||
|
typeErrors.add(
|
||
|
'The second parameter of WEEKDAY() should have the value either "sunday", "monday", "tuesday", "wednesday", "thursday", "friday" or "saturday"',
|
||
|
)
|
||
|
}
|
||
|
},
|
||
|
typeErrors,
|
||
|
)
|
||
|
} else {
|
||
|
parsedTree.arguments.map((arg: Record<string, any>) => validateAgainstType(arg, expectedType, null, typeErrors))
|
||
|
}
|
||
|
} else if (expectedType === formulaTypes.DATE) {
|
||
|
if (parsedTree.callee.name === 'DATEADD') {
|
||
|
// parsedTree.arguments[0] = date
|
||
|
validateAgainstType(
|
||
|
parsedTree.arguments[0],
|
||
|
formulaTypes.DATE,
|
||
|
(v: any) => {
|
||
|
if (!validateDateWithUnknownFormat(v)) {
|
||
|
typeErrors.add('The first parameter of DATEADD() should have date value')
|
||
|
}
|
||
|
},
|
||
|
typeErrors,
|
||
|
)
|
||
|
// parsedTree.arguments[1] = numeric
|
||
|
validateAgainstType(
|
||
|
parsedTree.arguments[1],
|
||
|
formulaTypes.NUMERIC,
|
||
|
(v: any) => {
|
||
|
if (typeof v !== 'number') {
|
||
|
typeErrors.add('The second parameter of DATEADD() should have numeric value')
|
||
|
}
|
||
|
},
|
||
|
typeErrors,
|
||
|
)
|
||
|
// parsedTree.arguments[2] = ["day" | "week" | "month" | "year"]
|
||
|
validateAgainstType(
|
||
|
parsedTree.arguments[2],
|
||
|
formulaTypes.STRING,
|
||
|
(v: any) => {
|
||
|
if (!['day', 'week', 'month', 'year'].includes(v)) {
|
||
|
typeErrors.add('The third parameter of DATEADD() should have the value either "day", "week", "month" or "year"')
|
||
|
}
|
||
|
},
|
||
|
typeErrors,
|
||
|
)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
errors = new Set([...errors, ...typeErrors])
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.IDENTIFIER) {
|
||
2 years ago
|
if (
|
||
|
columns.value
|
||
2 years ago
|
.filter((c: Record<string, any>) => !column || column.value.id !== c.id)
|
||
2 years ago
|
.every((c: Record<string, any>) => c.title !== parsedTree.name)
|
||
|
) {
|
||
|
errors.add(`Column '${parsedTree.name}' is not available`)
|
||
|
}
|
||
|
|
||
|
// check circular reference
|
||
|
// e.g. formula1 -> formula2 -> formula1 should return circular reference error
|
||
|
|
||
|
// get all formula columns excluding itself
|
||
|
const formulaPaths = columns.value
|
||
2 years ago
|
.filter((c: Record<string, any>) => c.id !== column?.value.id && c.uidt === UITypes.Formula)
|
||
2 years ago
|
.reduce((res: Record<string, any>[], c: Record<string, any>) => {
|
||
|
// in `formula`, get all the target neighbours
|
||
|
// i.e. all column id (e.g. cl_xxxxxxxxxxxxxx) with formula type
|
||
|
const neighbours = (c.colOptions.formula.match(/cl_\w{14}/g) || []).filter(
|
||
|
(colId: string) => columns.value.filter((col: ColumnType) => col.id === colId && col.uidt === UITypes.Formula).length,
|
||
|
)
|
||
|
if (neighbours.length > 0) {
|
||
|
// e.g. formula column 1 -> [formula column 2, formula column3]
|
||
|
res.push({ [c.id]: neighbours })
|
||
|
}
|
||
|
return res
|
||
|
}, [])
|
||
|
// include target formula column (i.e. the one to be saved if applicable)
|
||
|
const targetFormulaCol = columns.value.find((c: ColumnType) => c.title === parsedTree.name && c.uidt === UITypes.Formula)
|
||
2 years ago
|
|
||
|
if (targetFormulaCol && column?.value.id) {
|
||
2 years ago
|
formulaPaths.push({
|
||
2 years ago
|
[column?.value?.id as string]: [targetFormulaCol.id],
|
||
2 years ago
|
})
|
||
|
}
|
||
|
const vertices = formulaPaths.length
|
||
|
if (vertices > 0) {
|
||
|
// perform kahn's algo for cycle detection
|
||
|
const adj = new Map()
|
||
|
const inDegrees = new Map()
|
||
|
// init adjacency list & indegree
|
||
2 years ago
|
|
||
2 years ago
|
for (const [_, v] of Object.entries(formulaPaths)) {
|
||
|
const src = Object.keys(v)[0]
|
||
|
const neighbours = v[src]
|
||
|
inDegrees.set(src, inDegrees.get(src) || 0)
|
||
|
for (const neighbour of neighbours) {
|
||
|
adj.set(src, (adj.get(src) || new Set()).add(neighbour))
|
||
|
inDegrees.set(neighbour, (inDegrees.get(neighbour) || 0) + 1)
|
||
|
}
|
||
|
}
|
||
|
const queue: string[] = []
|
||
|
// put all vertices with in-degree = 0 (i.e. no incoming edges) to queue
|
||
|
inDegrees.forEach((inDegree, col) => {
|
||
|
if (inDegree === 0) {
|
||
|
// in-degree = 0 means we start traversing from this node
|
||
|
queue.push(col)
|
||
|
}
|
||
|
})
|
||
|
// init count of visited vertices
|
||
|
let visited = 0
|
||
|
// BFS
|
||
|
while (queue.length !== 0) {
|
||
|
// remove a vertex from the queue
|
||
|
const src = queue.shift()
|
||
|
// if this node has neighbours, increase visited by 1
|
||
|
const neighbours = adj.get(src) || new Set()
|
||
|
if (neighbours.size > 0) {
|
||
|
visited += 1
|
||
|
}
|
||
|
// iterate each neighbouring nodes
|
||
|
neighbours.forEach((neighbour: string) => {
|
||
|
// decrease in-degree of its neighbours by 1
|
||
|
inDegrees.set(neighbour, inDegrees.get(neighbour) - 1)
|
||
|
// if in-degree becomes 0
|
||
|
if (inDegrees.get(neighbour) === 0) {
|
||
|
// then put the neighboring node to the queue
|
||
|
queue.push(neighbour)
|
||
|
}
|
||
|
})
|
||
|
}
|
||
|
// vertices not same as visited = cycle found
|
||
|
if (vertices !== visited) {
|
||
|
errors.add('Can’t save field because it causes a circular reference')
|
||
|
}
|
||
|
}
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.BINARY_EXP) {
|
||
2 years ago
|
if (!availableBinOps.includes(parsedTree.operator)) {
|
||
|
errors.add(`'${parsedTree.operator}' operation is not available`)
|
||
|
}
|
||
|
validateAgainstMeta(parsedTree.left, errors)
|
||
|
validateAgainstMeta(parsedTree.right, errors)
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.LITERAL || parsedTree.type === JSEPNode.UNARY_EXP) {
|
||
2 years ago
|
// do nothing
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.COMPOUND) {
|
||
2 years ago
|
if (parsedTree.body.length) {
|
||
|
errors.add('Can’t save field because the formula is invalid')
|
||
|
}
|
||
|
} else {
|
||
|
errors.add('Can’t save field because the formula is invalid')
|
||
|
}
|
||
|
return errors
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
function validateAgainstType(parsedTree: any, expectedType: string, func: any, typeErrors = new Set()) {
|
||
|
if (parsedTree === false || typeof parsedTree === 'undefined') {
|
||
|
return typeErrors
|
||
|
}
|
||
2 years ago
|
if (parsedTree.type === JSEPNode.LITERAL) {
|
||
2 years ago
|
if (typeof func === 'function') {
|
||
|
func(parsedTree.value)
|
||
|
} else if (expectedType === formulaTypes.NUMERIC) {
|
||
|
if (typeof parsedTree.value !== 'number') {
|
||
|
typeErrors.add('Numeric type is expected')
|
||
|
}
|
||
|
} else if (expectedType === formulaTypes.STRING) {
|
||
|
if (typeof parsedTree.value !== 'string') {
|
||
|
typeErrors.add('string type is expected')
|
||
|
}
|
||
|
}
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.IDENTIFIER) {
|
||
2 years ago
|
const col = columns.value.find((c) => c.title === parsedTree.name)
|
||
|
|
||
2 years ago
|
if (col === undefined) {
|
||
|
return
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
if (col.uidt === UITypes.Formula) {
|
||
2 years ago
|
const foundType = getRootDataType(jsep((col as any).formula_raw))
|
||
2 years ago
|
if (foundType === 'N/A') {
|
||
|
typeErrors.add(`Not supported to reference column ${col.title}`)
|
||
|
} else if (expectedType !== foundType) {
|
||
|
typeErrors.add(`Type ${expectedType} is expected but found Type ${foundType}`)
|
||
|
}
|
||
|
} else {
|
||
|
switch (col.uidt) {
|
||
|
// string
|
||
|
case UITypes.SingleLineText:
|
||
|
case UITypes.LongText:
|
||
|
case UITypes.MultiSelect:
|
||
|
case UITypes.SingleSelect:
|
||
|
case UITypes.PhoneNumber:
|
||
|
case UITypes.Email:
|
||
|
case UITypes.URL:
|
||
|
if (expectedType !== formulaTypes.STRING) {
|
||
|
typeErrors.add(
|
||
|
`Column '${parsedTree.name}' with ${formulaTypes.STRING} type is found but ${expectedType} type is expected`,
|
||
|
)
|
||
|
}
|
||
|
break
|
||
|
|
||
|
// numeric
|
||
|
case UITypes.Year:
|
||
|
case UITypes.Number:
|
||
|
case UITypes.Decimal:
|
||
|
case UITypes.Rating:
|
||
|
case UITypes.Count:
|
||
|
case UITypes.AutoNumber:
|
||
|
case UITypes.Currency:
|
||
|
if (expectedType !== formulaTypes.NUMERIC) {
|
||
|
typeErrors.add(
|
||
|
`Column '${parsedTree.name}' with ${formulaTypes.NUMERIC} type is found but ${expectedType} type is expected`,
|
||
|
)
|
||
|
}
|
||
|
break
|
||
|
|
||
|
// date
|
||
|
case UITypes.Date:
|
||
|
case UITypes.DateTime:
|
||
|
case UITypes.CreateTime:
|
||
|
case UITypes.LastModifiedTime:
|
||
|
if (expectedType !== formulaTypes.DATE) {
|
||
|
typeErrors.add(
|
||
|
`Column '${parsedTree.name}' with ${formulaTypes.DATE} type is found but ${expectedType} type is expected`,
|
||
|
)
|
||
|
}
|
||
|
break
|
||
|
|
||
|
// not supported
|
||
|
case UITypes.ForeignKey:
|
||
|
case UITypes.Attachment:
|
||
|
case UITypes.ID:
|
||
|
case UITypes.Time:
|
||
|
case UITypes.Percent:
|
||
|
case UITypes.Duration:
|
||
|
case UITypes.Rollup:
|
||
|
case UITypes.Lookup:
|
||
|
case UITypes.Barcode:
|
||
|
case UITypes.Button:
|
||
|
case UITypes.Checkbox:
|
||
|
case UITypes.Collaborator:
|
||
|
default:
|
||
|
typeErrors.add(`Not supported to reference column '${parsedTree.name}'`)
|
||
|
break
|
||
|
}
|
||
|
}
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.UNARY_EXP || parsedTree.type === JSEPNode.BINARY_EXP) {
|
||
2 years ago
|
if (expectedType !== formulaTypes.NUMERIC) {
|
||
|
// parsedTree.name won't be available here
|
||
|
typeErrors.add(`${formulaTypes.NUMERIC} type is found but ${expectedType} type is expected`)
|
||
|
}
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.CALL_EXP) {
|
||
2 years ago
|
if (formulas[parsedTree.callee.name]?.type && expectedType !== formulas[parsedTree.callee.name].type) {
|
||
|
typeErrors.add(`${expectedType} not matched with ${formulas[parsedTree.callee.name].type}`)
|
||
|
}
|
||
|
}
|
||
|
return typeErrors
|
||
|
}
|
||
|
|
||
|
function getRootDataType(parsedTree: any): any {
|
||
|
// given a parse tree, return the data type of it
|
||
2 years ago
|
if (parsedTree.type === JSEPNode.CALL_EXP) {
|
||
2 years ago
|
return formulas[parsedTree.callee.name].type
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.IDENTIFIER) {
|
||
2 years ago
|
const col = columns.value.find((c) => c.title === parsedTree.name) as Record<string, any>
|
||
|
if (col?.uidt === UITypes.Formula) {
|
||
2 years ago
|
return getRootDataType(jsep(col?.formula_raw))
|
||
2 years ago
|
} else {
|
||
|
switch (col?.uidt) {
|
||
|
// string
|
||
|
case UITypes.SingleLineText:
|
||
|
case UITypes.LongText:
|
||
|
case UITypes.MultiSelect:
|
||
|
case UITypes.SingleSelect:
|
||
|
case UITypes.PhoneNumber:
|
||
|
case UITypes.Email:
|
||
|
case UITypes.URL:
|
||
|
return formulaTypes.STRING
|
||
|
|
||
|
// numeric
|
||
|
case UITypes.Year:
|
||
|
case UITypes.Number:
|
||
|
case UITypes.Decimal:
|
||
|
case UITypes.Rating:
|
||
|
case UITypes.Count:
|
||
|
case UITypes.AutoNumber:
|
||
|
return formulaTypes.NUMERIC
|
||
|
|
||
|
// date
|
||
|
case UITypes.Date:
|
||
|
case UITypes.DateTime:
|
||
|
case UITypes.CreateTime:
|
||
|
case UITypes.LastModifiedTime:
|
||
|
return formulaTypes.DATE
|
||
|
|
||
|
// not supported
|
||
|
case UITypes.ForeignKey:
|
||
|
case UITypes.Attachment:
|
||
|
case UITypes.ID:
|
||
|
case UITypes.Time:
|
||
|
case UITypes.Currency:
|
||
|
case UITypes.Percent:
|
||
|
case UITypes.Duration:
|
||
|
case UITypes.Rollup:
|
||
|
case UITypes.Lookup:
|
||
|
case UITypes.Barcode:
|
||
|
case UITypes.Button:
|
||
|
case UITypes.Checkbox:
|
||
|
case UITypes.Collaborator:
|
||
|
default:
|
||
|
return 'N/A'
|
||
|
}
|
||
|
}
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.BINARY_EXP || parsedTree.type === JSEPNode.UNARY_EXP) {
|
||
2 years ago
|
return formulaTypes.NUMERIC
|
||
2 years ago
|
} else if (parsedTree.type === JSEPNode.LITERAL) {
|
||
2 years ago
|
return typeof parsedTree.value
|
||
|
} else {
|
||
|
return 'N/A'
|
||
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
function isCurlyBracketBalanced() {
|
||
|
// count number of opening curly brackets and closing curly brackets
|
||
2 years ago
|
const cntCurlyBrackets = (formulaRef.value.$el.value.match(/\{|}/g) || []).reduce(
|
||
|
(acc: Record<number, number>, cur: number) => {
|
||
|
acc[cur] = (acc[cur] || 0) + 1
|
||
|
return acc
|
||
|
},
|
||
|
{},
|
||
|
)
|
||
2 years ago
|
return (cntCurlyBrackets['{'] || 0) === (cntCurlyBrackets['}'] || 0)
|
||
|
}
|
||
|
|
||
2 years ago
|
function appendText(item: Record<string, any>) {
|
||
|
const text = item.text
|
||
2 years ago
|
const len = wordToComplete.value?.length || 0
|
||
2 years ago
|
|
||
2 years ago
|
if (item.type === 'function') {
|
||
2 years ago
|
vModel.value.formula_raw = insertAtCursor(formulaRef.value.$el, text, len, 1)
|
||
2 years ago
|
} else if (item.type === 'column') {
|
||
2 years ago
|
vModel.value.formula_raw = insertAtCursor(formulaRef.value.$el, `{${text}}`, len + +!isCurlyBracketBalanced())
|
||
2 years ago
|
} else {
|
||
2 years ago
|
vModel.value.formula_raw = insertAtCursor(formulaRef.value.$el, text, len)
|
||
2 years ago
|
}
|
||
|
autocomplete.value = false
|
||
2 years ago
|
wordToComplete.value = ''
|
||
2 years ago
|
if (item.type === 'function' || item.type === 'op') {
|
||
|
// if function / operator is chosen, display columns only
|
||
|
suggestion.value = suggestionsList.value.filter((f) => f.type === 'column')
|
||
|
} else {
|
||
|
// show all options if column is chosen
|
||
|
suggestion.value = suggestionsList.value
|
||
|
}
|
||
2 years ago
|
}
|
||
|
|
||
|
const handleInputDeb = useDebounceFn(function () {
|
||
|
handleInput()
|
||
|
}, 250)
|
||
|
|
||
|
function handleInput() {
|
||
|
selected.value = 0
|
||
2 years ago
|
suggestion.value = []
|
||
2 years ago
|
const query = getWordUntilCaret(formulaRef.value.$el)
|
||
2 years ago
|
const parts = query.split(/\W+/)
|
||
|
wordToComplete.value = parts.pop() || ''
|
||
2 years ago
|
suggestion.value = acTree.value
|
||
|
.complete(wordToComplete.value)
|
||
|
?.sort((x: Record<string, any>, y: Record<string, any>) => sortOrder[x.type] - sortOrder[y.type])
|
||
2 years ago
|
if (!isCurlyBracketBalanced()) {
|
||
|
suggestion.value = suggestion.value.filter((v: Record<string, any>) => v.type === 'column')
|
||
|
}
|
||
|
autocomplete.value = !!suggestion.value.length
|
||
|
}
|
||
|
|
||
|
function selectText() {
|
||
2 years ago
|
if (suggestion.value && selected.value > -1 && selected.value < suggestion.value.length) {
|
||
2 years ago
|
appendText(suggestion.value[selected.value])
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function suggestionListUp() {
|
||
|
if (suggestion.value) {
|
||
|
selected.value = --selected.value > -1 ? selected.value : suggestion.value.length - 1
|
||
|
scrollToSelectedOption()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function suggestionListDown() {
|
||
|
if (suggestion.value) {
|
||
|
selected.value = ++selected.value % suggestion.value.length
|
||
|
scrollToSelectedOption()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function scrollToSelectedOption() {
|
||
|
nextTick(() => {
|
||
|
if (sugOptionsRef.value[selected.value]) {
|
||
|
try {
|
||
|
sugListRef.value.$el.scrollTo({
|
||
|
top: sugOptionsRef.value[selected.value].$el.offsetTop,
|
||
|
behavior: 'smooth',
|
||
|
})
|
||
|
} catch (e) {}
|
||
|
}
|
||
|
})
|
||
|
}
|
||
|
|
||
|
// set default value
|
||
2 years ago
|
vModel.value.formula_raw = (column?.value?.colOptions as Record<string, any>)?.formula_raw || ''
|
||
2 years ago
|
|
||
2 years ago
|
// set additional validations
|
||
|
setAdditionalValidations({
|
||
|
...validators,
|
||
|
})
|
||
|
|
||
2 years ago
|
onMounted(() => {
|
||
|
jsep.plugins.register(jsepCurlyHook)
|
||
|
})
|
||
2 years ago
|
</script>
|
||
|
|
||
|
<template>
|
||
|
<div class="formula-wrapper">
|
||
2 years ago
|
<a-form-item v-bind="validateInfos.formula_raw" label="Formula">
|
||
2 years ago
|
<a-textarea
|
||
2 years ago
|
ref="formulaRef"
|
||
2 years ago
|
v-model:value="vModel.formula_raw"
|
||
2 years ago
|
class="mb-2 nc-formula-input"
|
||
2 years ago
|
@keydown.down.prevent="suggestionListDown"
|
||
|
@keydown.up.prevent="suggestionListUp"
|
||
|
@keydown.enter.prevent="selectText"
|
||
|
@change="handleInputDeb"
|
||
|
/>
|
||
2 years ago
|
</a-form-item>
|
||
2 years ago
|
<div class="text-gray-600 mt-2 mb-4 prose-sm">
|
||
2 years ago
|
Hint: Use {} to reference columns, e.g: {column_name}. For more, please check out
|
||
2 years ago
|
<a class="prose-sm" href="https://docs.nocodb.com/setup-and-usages/formulas#available-formula-features" target="_blank">
|
||
|
Formulas.
|
||
|
</a>
|
||
2 years ago
|
</div>
|
||
2 years ago
|
|
||
2 years ago
|
<div class="h-[250px] overflow-auto scrollbar-thin-primary">
|
||
2 years ago
|
<a-list ref="sugListRef" :data-source="suggestion" :locale="{ emptyText: 'No suggested formula was found' }">
|
||
2 years ago
|
<template #renderItem="{ item, index }">
|
||
|
<a-list-item
|
||
|
:ref="
|
||
|
(el) => {
|
||
|
sugOptionsRef[index] = el
|
||
|
}
|
||
|
"
|
||
2 years ago
|
class="cursor-pointer"
|
||
2 years ago
|
@click.prevent.stop="appendText(item)"
|
||
2 years ago
|
>
|
||
2 years ago
|
<a-list-item-meta>
|
||
|
<template #title>
|
||
|
<div class="flex">
|
||
2 years ago
|
<a-col :span="6">
|
||
|
<span class="prose-sm text-gray-600">{{ item.text }}</span>
|
||
|
</a-col>
|
||
|
<a-col :span="18">
|
||
|
<div v-if="item.type === 'function'" class="text-xs text-gray-500">
|
||
|
{{ item.description }} <br /><br />
|
||
|
Syntax: <br />
|
||
|
{{ item.syntax }} <br /><br />
|
||
|
Examples: <br />
|
||
|
<div v-for="(example, idx) of item.examples" :key="idx">
|
||
|
<div>({{ idx + 1 }}): {{ example }}</div>
|
||
|
</div>
|
||
|
</div>
|
||
|
<div v-if="item.type === 'column'" class="float-right mr-5 -mt-2">
|
||
2 years ago
|
<a-badge-ribbon :text="item.uidt" color="gray" />
|
||
2 years ago
|
</div>
|
||
|
</a-col>
|
||
2 years ago
|
</div>
|
||
2 years ago
|
</template>
|
||
2 years ago
|
|
||
2 years ago
|
<template #avatar>
|
||
2 years ago
|
<mdi-function v-if="item.type === 'function'" class="text-lg" />
|
||
|
<mdi-calculator v-if="item.type === 'op'" class="text-lg" />
|
||
2 years ago
|
<component :is="item.icon" v-if="item.type === 'column'" class="text-lg" />
|
||
2 years ago
|
</template>
|
||
|
</a-list-item-meta>
|
||
|
</a-list-item>
|
||
|
</template>
|
||
|
</a-list>
|
||
2 years ago
|
</div>
|
||
2 years ago
|
</div>
|
||
2 years ago
|
</template>
|