feat: Show multiple formula expression examples (#5981)

* Added support for multiple examples in formula expression help tooltip.

* Show an icon to indicate that an example can be inserted.
This commit is contained in:
Tsering Paljor authored and GitHub committed 2026-09-10 13:28:40 +04:00
1 parent a398de7351
commit e995e8f937
18 files changed
+900 -124

No files matched your search

@@ -0,0 +1,9 @@
{
"type": "feature",
"message": "Added support for multiple examples in formula expression help tooltip.",
"issue_origin": "github",
"issue_number": 5442,
"domain": "core",
"bullet_points": [],
"created_at": "2026-09-03"
}
+1
View File
@@ -686,6 +686,7 @@
"minuteDescription": "Returns the minute from the date time argument.",
"secondDescription": "Returns the second from the date time argument.",
"todayDescription": "Returns the current date.",
"nowDescription": "Returns the current date and time.",
"getPropertyDescription": "Returns the property from the object.",
"randomIntDescription": "Returns a random integer from the range specified by the arguments.",
"randomFloatDescription": "Returns a random float from the range specified by the arguments.",
@@ -42,6 +42,75 @@
@extend %mb-16;
}
&__examples {
display: flex;
flex-direction: column;
gap: 12px;
// Fits three examples, including the extra padding of the clickable
// variant. Longer lists scroll.
max-height: 260px;
overflow-y: auto;
// Clickable examples carry their own padding so the hover background can
// bleed past the snippet. Offset the container by the same amount so the
// snippets stay aligned with the label above.
&--clickable {
margin: 0 -6px;
padding: 0 6px;
}
}
&__example-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 12px;
font-size: 12px;
color: $palette-neutral-1100;
}
&__example-result {
min-width: 0;
overflow-wrap: anywhere;
}
// Signals that clicking the example inserts it into the formula. Pushed to
// the far end of the footer so it sits opposite the result, and stays there
// when the example has no result.
&__example-insert-icon {
margin-left: auto;
flex-shrink: 0;
font-size: 12px;
color: $palette-neutral-700;
}
&__example--clickable {
cursor: pointer;
padding: 6px;
@include rounded($rounded);
&:hover {
background: $palette-neutral-200;
.node-help-tooltip__example-insert-icon {
color: $palette-neutral-1200;
}
}
.node-help-tooltip__example-code {
pointer-events: none;
}
}
&__examples-hint {
margin: 8px 0 0;
font-size: 11px;
color: $palette-neutral-700;
}
}
.node-help-tooltip-context {
@@ -15,6 +15,7 @@
:loading="loading"
@node-selected="$emit('node-selected', $event)"
@node-unselected="$emit('node-unselected')"
@example-click="$emit('example-click', $event)"
/>
<div
v-if="advancedModeEnabled"
@@ -113,14 +114,10 @@ export default {
required: true,
},
},
emits: ['mode-changed', 'node-selected', 'node-unselected'],
emits: ['mode-changed', 'node-selected', 'node-unselected', 'example-click'],
data() {
return {
searchQuery: '',
tooltip: {
functionData: null,
},
tooltipTimer: null,
tabs: [],
isModalVisible: false,
}
@@ -141,7 +138,6 @@ export default {
},
activeTabIndex() {
this.searchQuery = ''
this.hideTooltip()
},
},
created() {
@@ -165,7 +161,6 @@ export default {
},
hide() {
this.$refs.context.hide()
this.hideTooltip()
},
getTabTitle(tabName) {
const titleMap = {
@@ -203,48 +198,6 @@ export default {
this.$emit('mode-changed', 'advanced')
}
},
onFunctionHover(item, tabName, event) {
if (tabName !== 'Functions') {
return
}
if (this.tooltipTimer) {
clearTimeout(this.tooltipTimer)
}
this.tooltip.functionData = {
name: item.name,
description: item.description,
example: item.example,
icon: item.icon,
}
this.tooltipTimer = setTimeout(() => {
if (this.$refs.functionHelpTooltip) {
this.$refs.functionHelpTooltip.show(
event.target,
'bottom',
'right',
5,
10
)
}
}, 300)
},
onFunctionLeave() {
if (this.tooltipTimer) {
clearTimeout(this.tooltipTimer)
this.tooltipTimer = null
}
this.hideTooltip()
},
hideTooltip() {
if (this.$refs.functionHelpTooltip) {
this.$refs.functionHelpTooltip.hide()
}
this.tooltip.functionData = null
},
showAdvancedModeModal() {
this.$refs.advancedModeModal.show()
},
@@ -69,11 +69,13 @@
:enabled-modes="enabledModes"
@node-selected="handleNodeSelected"
@node-unselected="unSelectNode"
@example-click="handleExampleSelected"
@mode-changed="handleModeChange"
@mousedown="onContextMouseDown"
/>
<NodeHelpTooltip
v-if="!readOnly"
ref="nodeHelpTooltip"
:node="hoveredFunctionNode"
:nodes-hierarchy="nodesHierarchy"
@@ -398,17 +400,24 @@ export default {
this.$refs.formulaInputExplorerContext?.hide()
},
}),
FunctionHelpTooltipExtension.configure({
functionDefinitions: this.formulaRegistry.definitions,
onShowTooltip: (el, node) => {
this.hoveredFunctionNode = node
this.$refs.nodeHelpTooltip?.show(el, 'bottom', 'right', 6, 10)
},
onHideTooltip: () => {
this.$refs.nodeHelpTooltip?.hide()
this.hoveredFunctionNode = null
},
}),
// Read-only fields are display-only snippets (e.g. the examples
// rendered inside `NodeHelpTooltip` itself), so they must not spawn
// their own hover help tooltip.
...(this.readOnly
? []
: [
FunctionHelpTooltipExtension.configure({
functionDefinitions: this.formulaRegistry.definitions,
onShowTooltip: (el, node) => {
this.hoveredFunctionNode = node
this.$refs.nodeHelpTooltip?.show(el, 'bottom', 'right', 6, 10)
},
onHideTooltip: () => {
this.$refs.nodeHelpTooltip?.hide()
this.hoveredFunctionNode = null
},
}),
]),
...this.formulaComponents,
]
@@ -598,7 +607,11 @@ export default {
* renders without any error styling until the field is touched.
*/
validateFormula(formula) {
if (this.isRawMode) {
// Raw mode holds plain text, not a formula. Read-only fields are
// display-only snippets (e.g. the examples in the help tooltip) that
// never show an error context, so don't paint them as errors either:
// an example may deliberately be incomplete, like `get()` without a path.
if (this.isRawMode || this.readOnly) {
this.isFormulaInvalid = false
this.formulaErrorContext = { scope: null, title: '', message: '' }
return true
@@ -697,6 +710,22 @@ export default {
break
}
},
/**
* Inserts a clicked help-tooltip example at the cursor. Only advanced
* mode can host the function nodes examples parse into; the explorer's
* function tab (and thus a clickable tooltip) only exists in that mode.
*/
handleExampleSelected(example) {
if (this.mode !== 'advanced') {
return
}
const content = this.toContent(example.formula)
const fragment = content?.content?.[0]?.content
if (!fragment) {
return
}
this.editor.commands.insertFormulaFragment(fragment)
},
onContextMouseDown() {
this.editor?.commands.handleContextMouseDown()
},
@@ -363,6 +363,17 @@ export const FormulaInsertionExtension = Extension.create({
commands.focus()
return true
},
insertFormulaFragment:
(content) =>
({ commands }) => {
// ZWS-bracketed like the other insert commands; ZWSManagementExtension
// removes any consecutive ZWS this may create.
commands.insertContent([zwsTextJSON(), ...content, zwsTextJSON()])
commands.focus()
return true
},
insertOperator:
@@ -28,6 +28,7 @@
:allow-node-selection="allowNodeSelection"
@reset-search="resetSearch"
@node-selected="$emit('node-selected', $event)"
@example-click="$emit('example-click', $event)"
@toggle="toggleNode"
/>
</Tab>
@@ -43,6 +44,7 @@
:allow-node-selection="allowNodeSelection"
@reset-search="resetSearch"
@node-selected="$emit('node-selected', $event)"
@example-click="$emit('example-click', $event)"
@toggle="toggleNode"
/>
</template>
@@ -96,7 +98,7 @@ export default {
validator: (value) => ['none', 'all', 'array', 'object'].includes(value),
},
},
emits: ['node-selected', 'node-toggled', 'node-unselected'],
emits: ['node-selected', 'node-toggled', 'node-unselected', 'example-click'],
data() {
return {
activeTabIndex: 0,
@@ -27,7 +27,14 @@
>
{{ $t('dataExplorerNode.selectNode') }}
</span>
<NodeHelpTooltip ref="nodeHelpTooltip" :node="node" />
<NodeHelpTooltip
ref="nodeHelpTooltip"
:node="node"
clickable-examples
@example-click="onExampleClick"
@mouseenter="onTooltipEnter"
@mouseleave="onTooltipLeave"
/>
</div>
<div v-if="hasChildren && isOpen" class="node-explorer-content__children">
<template v-if="node.type !== 'array'">
@@ -50,6 +57,7 @@
:search="search"
@click="$emit('click', $event)"
@toggle="$emit('toggle', $event)"
@example-click="$emit('example-click', $event)"
/>
</template>
<div v-else>
@@ -66,6 +74,7 @@
:search-path="`${searchPath}.__any__`"
@click="$emit('click', $event)"
@toggle="$emit('toggle', $event)"
@example-click="$emit('example-click', $event)"
/>
<button
v-tooltip="$t('dataExplorerNode.showMore')"
@@ -127,9 +136,9 @@ export default {
validator: (value) => ['none', 'all', 'array', 'object'].includes(value),
},
},
emits: ['click', 'toggle'],
emits: ['click', 'toggle', 'example-click'],
data() {
return { count: 3, tooltipTimer: null }
return { count: 3, tooltipTimer: null, tooltipHideTimer: null }
},
computed: {
hasChildren() {
@@ -188,6 +197,13 @@ export default {
return []
},
},
beforeUnmount() {
if (this.tooltipTimer) {
clearTimeout(this.tooltipTimer)
this.tooltipTimer = null
}
this.cancelTooltipHide()
},
methods: {
showNodeSelector(node) {
if (this.depth === 0) {
@@ -232,11 +248,11 @@ export default {
if (this.tooltipTimer) {
clearTimeout(this.tooltipTimer)
}
this.cancelTooltipHide()
if (
(node.type === 'function' || node.type === 'operator') &&
node.example &&
node.description
(node.examples?.length || node.description)
) {
this.tooltipTimer = setTimeout(() => {
if (this.$refs.nodeHelpTooltip) {
@@ -257,7 +273,33 @@ export default {
this.tooltipTimer = null
}
// Hide with a delay so the mouse can travel from the node row into the
// tooltip; entering the tooltip cancels the pending hide.
this.armTooltipHide()
},
onTooltipEnter() {
this.cancelTooltipHide()
},
onExampleClick(example) {
this.cancelTooltipHide()
this.hideTooltip()
this.$emit('example-click', example)
},
onTooltipLeave() {
this.armTooltipHide()
},
armTooltipHide() {
this.cancelTooltipHide()
this.tooltipHideTimer = setTimeout(() => {
this.tooltipHideTimer = null
this.hideTooltip()
}, 250)
},
cancelTooltipHide() {
if (this.tooltipHideTimer) {
clearTimeout(this.tooltipHideTimer)
this.tooltipHideTimer = null
}
},
hideTooltip() {
if (this.$refs.nodeHelpTooltip) {
@@ -38,6 +38,7 @@
:allow-node-selection="allowNodeSelection"
@click="$emit('node-selected', $event)"
@toggle="$emit('toggle', $event)"
@example-click="$emit('example-click', $event)"
/>
</div>
</div>
@@ -88,6 +89,12 @@ export default {
validator: (value) => ['none', 'all', 'array', 'object'].includes(value),
},
},
emits: ['node-selected', 'reset-search', 'toggle', 'update:modelValue'],
emits: [
'node-selected',
'example-click',
'reset-search',
'toggle',
'update:modelValue',
],
}
</script>
@@ -1,6 +1,11 @@
<template>
<Context ref="context" class="node-help-tooltip-context">
<div v-if="node" class="node-help-tooltip">
<div
v-if="node"
class="node-help-tooltip"
@mouseenter="$emit('mouseenter')"
@mouseleave="$emit('mouseleave')"
>
<div class="node-help-tooltip__header">
<div class="node-help-tooltip__icon">
<i
@@ -14,28 +19,62 @@
</div>
<div class="node-help-tooltip__content">
<p class="node-help-tooltip__description">
<p v-if="node.description" class="node-help-tooltip__description">
{{ node.description }}
</p>
<FormGroup
v-if="node.example"
class="node-help-tooltip__example"
:label="$t('nodeHelpTooltip.exampleLabel')"
small-label
required
:helper-text="
$t('nodeHelpTooltip.result', { result: node.example.result })
"
>
<FormulaInputField
class="node-help-tooltip__example-code"
:value="node.example.formula"
:read-only="true"
:nodes-hierarchy="nodesHierarchy"
mode="advanced"
/>
</FormGroup>
<template v-if="node.examples && node.examples.length > 0">
<label class="control__label control__label--small">
{{
$t('nodeHelpTooltip.exampleLabel', {
count: node.examples.length,
})
}}
</label>
<div
class="node-help-tooltip__examples"
:class="{
'node-help-tooltip__examples--clickable': clickableExamples,
}"
>
<div
v-for="(example, index) in node.examples"
:key="index"
class="node-help-tooltip__example"
:class="{
'node-help-tooltip__example--clickable': clickableExamples,
}"
@mousedown="onExampleMouseDown"
@click="onExampleClick(example, $event)"
>
<FormulaInputField
class="node-help-tooltip__example-code"
:value="example.formula"
:read-only="true"
:nodes-hierarchy="nodesHierarchy"
mode="advanced"
/>
<div
v-if="example.result || clickableExamples"
class="node-help-tooltip__example-footer"
>
<span
v-if="example.result"
class="node-help-tooltip__example-result"
>
{{ $t('nodeHelpTooltip.result', { result: example.result }) }}
</span>
<i
v-if="clickableExamples"
class="node-help-tooltip__example-insert-icon iconoir-arrow-right"
></i>
</div>
</div>
</div>
<p v-if="clickableExamples" class="node-help-tooltip__examples-hint">
{{ $t('nodeHelpTooltip.clickToInsert') }}
</p>
</template>
</div>
</div>
</Context>
@@ -67,8 +106,33 @@ export default {
required: false,
default: () => [],
},
clickableExamples: {
type: Boolean,
required: false,
default: false,
},
},
emits: ['example-click', 'mouseenter', 'mouseleave'],
methods: {
onExampleMouseDown(event) {
if (this.clickableExamples) {
// The tooltip is teleported to <body>, so a mousedown here would blur
// the formula editor and unmount the explorer (tooltip included)
// before the click can land. Preventing the default keeps focus in
// the editor, which also preserves the cursor position the example
// will be inserted at.
event.preventDefault()
}
},
onExampleClick(example, event) {
if (this.clickableExamples) {
// Keep the click from reaching the document-level click-outside
// handlers, which would treat it as outside the formula context and
// hide the explorer.
event.stopPropagation()
this.$emit('example-click', example)
}
},
show(
targetElement,
verticalPosition = 'bottom',
+12 -10
View File
@@ -352,15 +352,16 @@ export const buildFormulaFunctionNodes = (app) => {
// Get description and examples
let description = null
let example = null
let examples = null
try {
description = instance.getDescription()
} catch (e) {
// Method not implemented
}
try {
const examples = instance.getExamples()
example = examples && examples.length > 0 ? examples[0] : null
const typeExamples = instance.getExamples()
examples =
typeExamples && typeExamples.length > 0 ? typeExamples : null
} catch (e) {
// Method not implemented
}
@@ -369,7 +370,7 @@ export const buildFormulaFunctionNodes = (app) => {
name: func.name,
type: 'function',
description,
example,
examples,
highlightingColor: 'blue',
icon: func.icon,
identifier: null,
@@ -384,7 +385,7 @@ export const buildFormulaFunctionNodes = (app) => {
order: null,
signature: null,
description: null,
example: null,
examples: null,
highlightingColor: null,
icon: null,
nodes: categoryNodes,
@@ -401,7 +402,7 @@ export const buildFormulaFunctionNodes = (app) => {
order: null,
signature: null,
description: null,
example: null,
examples: null,
highlightingColor: 'blue',
icon: null,
nodes: functionCategories,
@@ -468,14 +469,15 @@ export const buildFormulaFunctionNodes = (app) => {
}
const description = instance.getDescription()
const examples = instance.getExamples()
const example = examples && examples.length > 0 ? examples[0] : null
const typeExamples = instance.getExamples()
const examples =
typeExamples && typeExamples.length > 0 ? typeExamples : null
categoryNodes.push({
name: op.name,
type: 'operator',
description,
example,
examples,
highlightingColor: 'green',
icon: op.icon,
identifier: null,
@@ -486,7 +488,7 @@ export const buildFormulaFunctionNodes = (app) => {
operatorCategories.push({
name: category.name,
example: null,
examples: null,
signature: null,
highlightingColor: null,
icon: null,
+3 -2
View File
@@ -1319,8 +1319,9 @@
"notAllowedDescription": "Adding 2FA is only possible to password-based accounts."
},
"nodeHelpTooltip": {
"exampleLabel": "Example",
"result": "Result: {result}"
"exampleLabel": "Example | Examples",
"result": "Result: {result}",
"clickToInsert": "Click an example to insert it"
},
"enableWithQRCode": {
"scanQRCode": "Scan QR code",
@@ -297,10 +297,6 @@ export class RuntimeConcat extends RuntimeFormulaFunction {
getExamples() {
return [
{ formula: "concat('Hello,', ' World!')", result: '"Hello, world!"' },
{
formula: "concat(get('data_source.1.0.field_1'), ' bar')",
result: '"foo bar"',
},
]
}
}
@@ -386,12 +382,11 @@ export class RuntimeGet extends RuntimeFormulaFunction {
}
getExamples() {
return [
{
formula: "get('previous_node.1.body')",
result: "'Hello world'",
},
]
// The help tooltip renders examples against the live data of the page or
// workflow being edited, so any placeholder path would show up as an
// invalid reference. Show the bare call instead; the data nodes in the
// explorer insert a `get()` with a real path for the user.
return [{ formula: 'get()', result: '' }]
}
/**
@@ -1317,6 +1312,14 @@ export class RuntimeRound extends RuntimeFormulaFunction {
formula: "round('12.345', 2)",
result: '12.35',
},
{
formula: 'round(3.14159)',
result: '3.14',
},
{
formula: 'round(10 / 3, 1)',
result: '3.3',
},
]
}
}
@@ -1393,10 +1396,6 @@ export class RuntimeIsEven extends RuntimeFormulaFunction {
formula: 'is_even(12)',
result: 'true',
},
{
formula: 'is_even(13)',
result: 'false',
},
]
}
}
@@ -1433,10 +1432,6 @@ export class RuntimeIsOdd extends RuntimeFormulaFunction {
formula: 'is_odd(11)',
result: 'true',
},
{
formula: 'is_odd(12)',
result: 'false',
},
]
}
}
@@ -1527,6 +1522,10 @@ export class RuntimeDay extends RuntimeFormulaFunction {
formula: "day('2025-10-16 11:05:38')",
result: '16',
},
{
formula: 'day(today())',
result: '16',
},
]
}
}
@@ -1564,6 +1563,10 @@ export class RuntimeMonth extends RuntimeFormulaFunction {
formula: "month('2025-10-16 11:05:38')",
result: '9',
},
{
formula: 'month(now())',
result: '9',
},
]
}
}
@@ -1600,6 +1603,10 @@ export class RuntimeYear extends RuntimeFormulaFunction {
formula: "year('2025-10-16 11:05:38')",
result: '2025',
},
{
formula: 'year(today())',
result: '2025',
},
]
}
}
@@ -1672,6 +1679,10 @@ export class RuntimeMinute extends RuntimeFormulaFunction {
formula: "minute('2025-10-16T11:05:38')",
result: '5',
},
{
formula: 'minute(now())',
result: '5',
},
]
}
}
@@ -1708,6 +1719,10 @@ export class RuntimeSecond extends RuntimeFormulaFunction {
formula: "second('2025-10-16 11:05:38')",
result: '38',
},
{
formula: 'second(now())',
result: '38',
},
]
}
}
@@ -1733,6 +1748,11 @@ export class RuntimeNow extends RuntimeFormulaFunction {
return new Date()
}
getDescription() {
const { $i18n: i18n } = this.app
return i18n.t('runtimeFormulaTypes.nowDescription')
}
getExamples() {
return [
{
@@ -1814,6 +1834,10 @@ export class RuntimeGetProperty extends RuntimeFormulaFunction {
formula: 'get_property(\'{"cherry": "red"}\', \'cherry\')',
result: "'red'",
},
{
formula: 'get_property(from_json(\'{"name": "Ada"}\'), \'name\')',
result: "'Ada'",
},
]
}
}
@@ -2149,6 +2173,10 @@ export class RuntimeReplace extends RuntimeFormulaFunction {
formula: "replace('Hello, world!', 'l', '-')",
result: "'He--o, wor-d!'",
},
{
formula: "replace('2025-10-16', '-', '/')",
result: "'2025/10/16'",
},
]
}
}
@@ -2890,6 +2918,10 @@ export class RuntimeToJson extends RuntimeFormulaFunction {
formula: "concat('{\"value\": ', to_json('foo \"bar\"'), '}')",
result: '\'{"value": "foo \\"bar\\""}\'',
},
{
formula: "to_json(to_array('a, b'))",
result: '\'["a","b"]\'',
},
]
}
}
@@ -3041,10 +3073,6 @@ export class RuntimeNumberFormat extends RuntimeFormulaFunction {
getExamples() {
return [
{
formula: "number_format(1000000, 2, ',', '.')",
result: "'1,000,000.00'",
},
{
formula: 'number_format(1000000)',
result: "'1,000,000'",
@@ -3053,6 +3081,10 @@ export class RuntimeNumberFormat extends RuntimeFormulaFunction {
formula: 'number_format(1000000, 2)',
result: "'1,000,000.00'",
},
{
formula: "number_format(1000000, 2, '.', ',')",
result: "'1.000.000,00'",
},
]
}
}
@@ -3294,7 +3326,7 @@ export class RuntimeDurationFormat extends RuntimeFormulaFunction {
result: "'1:30:25.2'",
},
{
formula: "duration_format(get('Duration'), 'd h:mm')",
formula: "duration_format(to_duration('26:30', 'h:mm'), 'd h:mm')",
result: "'1 2:30'",
},
]
@@ -4,7 +4,7 @@ const transformNode = (node) => ({
description: node.description || null,
icon: node.icon || 'iconoir-database',
highlightingColor: null,
example: null,
examples: null,
order: node.order || null,
signature: null,
nodes: node.nodes
@@ -0,0 +1,208 @@
import { vi } from 'vitest'
import { nextTick } from 'vue'
import { TestApp } from '@baserow/test/helpers/testApp'
import NodeExplorerContent from '@baserow/modules/core/components/nodeExplorer/NodeExplorerContent.vue'
// Tooltip examples are normally read-only tiptap editors, which are not
// relevant to the hover behaviour tested here.
const FormulaInputFieldStub = {
props: { value: { type: String, default: '' } },
template: '<code class="formula-input-field-stub">{{ value }}</code>',
}
// Must match the delays used by `NodeExplorerContent`.
const SHOW_DELAY = 300
const HIDE_DELAY = 250
function functionNode(overrides = {}) {
return {
name: 'upper',
type: 'function',
description: 'Converts a string to uppercase.',
icon: 'iconoir-text',
identifier: null,
signature: null,
highlightingColor: 'blue',
examples: [
{ formula: "upper('hello')", result: "'HELLO'" },
{ formula: "upper('MiXeD')", result: "'MIXED'" },
],
...overrides,
}
}
describe('NodeExplorerContent help tooltip', () => {
let testApp = null
beforeEach(() => {
testApp = new TestApp()
})
afterEach(async () => {
vi.useRealTimers()
await testApp.afterEach()
})
async function mountContent(node, props = {}) {
const wrapper = await testApp.mount(NodeExplorerContent, {
props: {
node,
depth: 1,
path: node.name,
searchPath: node.name,
openNodes: new Set(),
...props,
},
global: {
provide: { getFormulaMode: () => 'advanced', nodesHierarchy: [] },
stubs: { FormulaInputField: FormulaInputFieldStub },
},
})
// Only the hover timers must be fake; mounting itself runs on real ones.
vi.useFakeTimers()
return wrapper
}
/**
* Lets the tooltip Context finish showing/hiding: `show()` awaits a tick
* before positioning and the class change needs another render.
*/
async function settle() {
for (let i = 0; i < 3; i++) {
await nextTick()
}
}
function tooltipVisible(wrapper) {
const context = wrapper.find('.node-help-tooltip-context')
return context.exists() && !context.classes('visibility-hidden')
}
async function hoverRow(wrapper, index = 0) {
await wrapper
.findAll('.node-explorer-content__content')
[index].trigger('mouseenter')
vi.advanceTimersByTime(SHOW_DELAY)
await settle()
}
test('shows the tooltip after hovering a function node for a moment', async () => {
const wrapper = await mountContent(functionNode())
const row = wrapper.find('.node-explorer-content__content')
await row.trigger('mouseenter')
vi.advanceTimersByTime(SHOW_DELAY - 1)
await settle()
expect(tooltipVisible(wrapper)).toBe(false)
vi.advanceTimersByTime(1)
await settle()
expect(tooltipVisible(wrapper)).toBe(true)
expect(wrapper.findAll('.node-help-tooltip__example')).toHaveLength(2)
expect(
wrapper.find('.node-help-tooltip__examples--clickable').exists()
).toBe(true)
})
test('shows a description-only tooltip for a node without examples', async () => {
const wrapper = await mountContent(functionNode({ examples: null }))
await hoverRow(wrapper)
expect(tooltipVisible(wrapper)).toBe(true)
expect(wrapper.find('.node-help-tooltip__description').text()).toBe(
'Converts a string to uppercase.'
)
expect(wrapper.find('.node-help-tooltip__examples').exists()).toBe(false)
})
test('does not show a tooltip for a node without description or examples', async () => {
const wrapper = await mountContent(
functionNode({ examples: null, description: null })
)
await hoverRow(wrapper)
expect(tooltipVisible(wrapper)).toBe(false)
})
test('cancels a pending tooltip when the mouse leaves early', async () => {
const wrapper = await mountContent(functionNode())
const row = wrapper.find('.node-explorer-content__content')
await row.trigger('mouseenter')
vi.advanceTimersByTime(SHOW_DELAY / 2)
await row.trigger('mouseleave')
vi.advanceTimersByTime(SHOW_DELAY)
await settle()
expect(tooltipVisible(wrapper)).toBe(false)
})
test('hides the tooltip with a delay after leaving the node', async () => {
const wrapper = await mountContent(functionNode())
await hoverRow(wrapper)
await wrapper.find('.node-explorer-content__content').trigger('mouseleave')
vi.advanceTimersByTime(HIDE_DELAY - 1)
await settle()
expect(tooltipVisible(wrapper)).toBe(true)
vi.advanceTimersByTime(1)
await settle()
expect(tooltipVisible(wrapper)).toBe(false)
})
test('keeps the tooltip open while the mouse is inside it', async () => {
const wrapper = await mountContent(functionNode())
await hoverRow(wrapper)
const tooltip = wrapper.find('.node-help-tooltip')
await wrapper.find('.node-explorer-content__content').trigger('mouseleave')
vi.advanceTimersByTime(HIDE_DELAY / 2)
await tooltip.trigger('mouseenter')
vi.advanceTimersByTime(HIDE_DELAY * 2)
await settle()
expect(tooltipVisible(wrapper)).toBe(true)
await tooltip.trigger('mouseleave')
vi.advanceTimersByTime(HIDE_DELAY)
await settle()
expect(tooltipVisible(wrapper)).toBe(false)
})
test('re-emits a clicked example and hides the tooltip', async () => {
const node = functionNode()
const wrapper = await mountContent(node)
await hoverRow(wrapper)
await wrapper.findAll('.node-help-tooltip__example')[1].trigger('click')
await settle()
expect(wrapper.emitted('example-click')).toEqual([[node.examples[1]]])
expect(tooltipVisible(wrapper)).toBe(false)
})
test('forwards example clicks from nested nodes', async () => {
const child = functionNode()
const category = {
name: 'Text',
description: null,
examples: null,
icon: null,
identifier: null,
nodes: [child],
}
const wrapper = await mountContent(category, {
depth: 0,
path: null,
searchPath: '',
})
// Row 0 is the category itself, row 1 its child function.
await hoverRow(wrapper, 1)
await wrapper.find('.node-help-tooltip__example').trigger('click')
expect(wrapper.emitted('example-click')).toEqual([[child.examples[0]]])
})
})
@@ -0,0 +1,232 @@
import { vi } from 'vitest'
import flushPromises from 'flush-promises'
import { TestApp } from '@baserow/test/helpers/testApp'
import NodeHelpTooltip from '@baserow/modules/core/components/nodeExplorer/NodeHelpTooltip.vue'
// Each example is normally rendered as a read-only tiptap editor. That is
// irrelevant here, so render the formula as plain text instead.
const FormulaInputFieldStub = {
props: { value: { type: String, default: '' } },
template: '<code class="formula-input-field-stub">{{ value }}</code>',
}
const upperNode = {
name: 'upper',
type: 'function',
description: 'Converts a string to uppercase.',
icon: 'iconoir-text',
examples: [
{ formula: "upper('hello')", result: "'HELLO'" },
{ formula: "upper(concat('a', 'b'))", result: "'AB'" },
{ formula: "upper('MiXeD')", result: "'MIXED'" },
],
}
describe('NodeHelpTooltip', () => {
let testApp = null
let target = null
beforeEach(() => {
testApp = new TestApp()
target = document.createElement('div')
document.body.appendChild(target)
})
afterEach(async () => {
target.remove()
await testApp.afterEach()
})
async function mountTooltip(props = {}) {
const wrapper = await testApp.mount(NodeHelpTooltip, {
props: { node: upperNode, ...props },
global: {
provide: { nodesHierarchy: [] },
stubs: { FormulaInputField: FormulaInputFieldStub },
},
})
// The Context only renders its content once shown, which is what the node
// explorer does when a node is hovered.
wrapper.vm.show(target)
await flushPromises()
return wrapper
}
test('renders every example of the node', async () => {
const wrapper = await mountTooltip()
expect(wrapper.find('.node-help-tooltip__title').text()).toBe('upper')
expect(wrapper.find('.node-help-tooltip__description').text()).toBe(
'Converts a string to uppercase.'
)
expect(wrapper.find('.node-help-tooltip .control__label').text()).toBe(
'nodeHelpTooltip.exampleLabel - 3'
)
const examples = wrapper.findAll('.node-help-tooltip__example')
expect(
examples.map((example) =>
example.find('.formula-input-field-stub').text()
)
).toEqual(["upper('hello')", "upper(concat('a', 'b'))", "upper('MiXeD')"])
// The i18n mock only interpolates `count`, so the result line renders as
// the bare key.
expect(
examples.map((example) =>
example.find('.node-help-tooltip__example-result').text()
)
).toEqual(Array(3).fill('nodeHelpTooltip.result'))
})
test('renders no example section for a node without examples', async () => {
const wrapper = await mountTooltip({
node: { ...upperNode, examples: null },
})
expect(wrapper.find('.node-help-tooltip__description').exists()).toBe(true)
expect(wrapper.find('.node-help-tooltip__examples').exists()).toBe(false)
expect(wrapper.find('.node-help-tooltip__examples-hint').exists()).toBe(
false
)
})
test('renders no result line for an example without one', async () => {
const wrapper = await mountTooltip({
node: {
...upperNode,
examples: [{ formula: 'get()', result: '' }],
},
})
const examples = wrapper.findAll('.node-help-tooltip__example')
expect(examples).toHaveLength(1)
expect(examples[0].find('.formula-input-field-stub').text()).toBe('get()')
expect(
examples[0].find('.node-help-tooltip__example-result').exists()
).toBe(false)
expect(
examples[0].find('.node-help-tooltip__example-footer').exists()
).toBe(false)
})
test('renders no description for a node without one', async () => {
const wrapper = await mountTooltip({
node: { ...upperNode, description: null },
})
expect(wrapper.find('.node-help-tooltip__title').text()).toBe('upper')
expect(wrapper.find('.node-help-tooltip__description').exists()).toBe(false)
expect(wrapper.findAll('.node-help-tooltip__example')).toHaveLength(3)
})
test('is display-only by default', async () => {
const wrapper = await mountTooltip()
const documentClick = vi.fn()
document.addEventListener('click', documentClick)
expect(
wrapper.find('.node-help-tooltip__examples--clickable').exists()
).toBe(false)
expect(
wrapper.find('.node-help-tooltip__example--clickable').exists()
).toBe(false)
expect(wrapper.find('.node-help-tooltip__examples-hint').exists()).toBe(
false
)
expect(
wrapper.find('.node-help-tooltip__example-insert-icon').exists()
).toBe(false)
await wrapper.findAll('.node-help-tooltip__example')[1].trigger('click')
expect(wrapper.emitted('example-click')).toBeUndefined()
// Nothing intercepts the click, so it bubbles up to the document.
expect(documentClick).toHaveBeenCalledTimes(1)
document.removeEventListener('click', documentClick)
})
test('emits the clicked example when examples are clickable', async () => {
const wrapper = await mountTooltip({ clickableExamples: true })
expect(
wrapper.find('.node-help-tooltip__examples--clickable').exists()
).toBe(true)
expect(
wrapper.findAll('.node-help-tooltip__example--clickable')
).toHaveLength(3)
expect(wrapper.find('.node-help-tooltip__examples-hint').text()).toBe(
'nodeHelpTooltip.clickToInsert'
)
// Every example carries the insert arrow at the end of its footer.
expect(
wrapper
.findAll('.node-help-tooltip__example')
.map((example) =>
example
.find('.node-help-tooltip__example-footer > :last-child')
.classes()
)
).toEqual(
Array(3).fill([
'node-help-tooltip__example-insert-icon',
'iconoir-arrow-right',
])
)
await wrapper.findAll('.node-help-tooltip__example')[1].trigger('click')
expect(wrapper.emitted('example-click')).toEqual([[upperNode.examples[1]]])
})
test('shows the insert arrow for a clickable example without a result', async () => {
const wrapper = await mountTooltip({
clickableExamples: true,
node: {
...upperNode,
examples: [{ formula: 'get()', result: '' }],
},
})
const footer = wrapper.find('.node-help-tooltip__example-footer')
expect(footer.find('.node-help-tooltip__example-result').exists()).toBe(
false
)
expect(
footer.find('.node-help-tooltip__example-insert-icon').exists()
).toBe(true)
})
test('keeps example clicks from blurring the editor or reaching the document', async () => {
const wrapper = await mountTooltip({ clickableExamples: true })
const documentClick = vi.fn()
document.addEventListener('click', documentClick)
const example = wrapper.find('.node-help-tooltip__example')
// The tooltip lives outside the formula editor, so a mousedown would blur
// the editor and close the explorer before the click lands.
const mousedown = new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
})
example.element.dispatchEvent(mousedown)
expect(mousedown.defaultPrevented).toBe(true)
// The click must not reach the document-level click-outside handlers.
await example.trigger('click')
expect(documentClick).not.toHaveBeenCalled()
expect(wrapper.emitted('example-click')).toHaveLength(1)
document.removeEventListener('click', documentClick)
})
test('reports the mouse entering and leaving it', async () => {
const wrapper = await mountTooltip()
const tooltip = wrapper.find('.node-help-tooltip')
await tooltip.trigger('mouseenter')
expect(wrapper.emitted('mouseenter')).toHaveLength(1)
expect(wrapper.emitted('mouseleave')).toBeUndefined()
await tooltip.trigger('mouseleave')
expect(wrapper.emitted('mouseleave')).toHaveLength(1)
})
})
@@ -198,6 +198,19 @@ describe('FormulaInputField validates on display', () => {
const wrapper = await mountField('$formula: now()')
expect(wrapper.emitted('update:invalid').at(-1)).toEqual([true])
})
it('does not flag an incomplete formula in a read-only field', async () => {
// Read-only fields display snippets such as the help tooltip's `get()`
// example, which is deliberately missing its path.
const wrapper = await testApp.mount(FormulaInputField, {
props: { value: 'get()', mode: 'advanced', readOnly: true },
})
await wrapper.vm.$nextTick()
expect(wrapper.vm.isFormulaInvalid).toBe(false)
expect(wrapper.find('.formula-input-field--error').exists()).toBe(false)
expect(wrapper.emitted('update:invalid')).toBeUndefined()
})
})
describe('FormulaInputField mode changes', () => {
@@ -369,3 +382,69 @@ describe('FormulaInputField mode changes', () => {
expect(wrapper.emitted('input').at(-1)).toEqual([''])
})
})
// ── Help tooltip example insertion ──────────────────────────────────
// Clicking an example in the Data Explorer's help tooltip inserts that
// example's formula into the editor at the cursor.
describe('FormulaInputField example insertion', () => {
let testApp = null
beforeEach(() => {
testApp = new TestApp()
})
afterEach(async () => {
await testApp.afterEach()
})
const example = { formula: "upper('hello')", result: "'HELLO'" }
/** The editor text without the zero-width spaces used for cursor slots. */
function editorText(wrapper) {
return wrapper
.find('.formula-input-field')
.text()
.replace(/\u200b/g, '')
}
it('inserts the example into an empty advanced-mode field', async () => {
const wrapper = await testApp.mount(FormulaInputField, {
props: { value: '', mode: 'advanced' },
})
expect(wrapper.emitted('input')).toBeUndefined()
wrapper.vm.handleExampleSelected(example)
await wrapper.vm.$nextTick()
expect(editorText(wrapper)).toBe("upper('hello')")
expect(wrapper.emitted('input').at(-1)).toEqual(["upper('hello')"])
})
it('inserts the example at the cursor', async () => {
const wrapper = await testApp.mount(FormulaInputField, {
props: { value: 'lower()', mode: 'advanced' },
})
// Place the cursor in the (empty) argument slot of `lower(`: ZWS (1),
// function node (1), so position 3 sits right after the function name.
wrapper.vm.editor.commands.setTextSelection(3)
wrapper.vm.handleExampleSelected(example)
await wrapper.vm.$nextTick()
expect(editorText(wrapper)).toBe("lower(upper('hello'))")
expect(wrapper.emitted('input').at(-1)).toEqual(["lower(upper('hello'))"])
})
it('ignores examples in simple mode', async () => {
const wrapper = await testApp.mount(FormulaInputField, {
props: { value: '', mode: 'simple' },
})
wrapper.vm.handleExampleSelected(example)
await wrapper.vm.$nextTick()
expect(editorText(wrapper)).toBe('')
expect(wrapper.emitted('input')).toBeUndefined()
})
})
@@ -59,6 +59,8 @@ import {
RuntimeToDatetime,
} from '@baserow/modules/core/runtimeFormulaTypes'
import { Timedelta } from '@baserow/modules/core/runtimeFormulaArgumentTypes'
import * as runtimeFormulaTypes from '@baserow/modules/core/runtimeFormulaTypes'
import parseBaserowFormula from '@baserow/modules/core/formula/parser/parser'
import { expect } from 'vitest'
/** Tests for the RuntimeConcat class. */
@@ -2757,3 +2759,36 @@ describe('RuntimeToDatetime', () => {
expect(result).toBe(expected)
})
})
/**
* Every runtime formula type feeds the help tooltip in the formula editor,
* which renders all of its examples and lets the user insert them. Keep the
* examples present and syntactically valid.
*/
describe('runtime formula type examples', () => {
const { RuntimeFormulaFunction } = runtimeFormulaTypes
const formulaTypes = Object.values(runtimeFormulaTypes).filter(
(candidate) =>
typeof candidate === 'function' &&
candidate !== RuntimeFormulaFunction &&
candidate.prototype instanceof RuntimeFormulaFunction
)
test('finds the runtime formula types to check', () => {
expect(formulaTypes.length).toBeGreaterThan(0)
})
test.each(
formulaTypes.map((FormulaType) => [FormulaType.getType(), FormulaType])
)('%s defines parsable examples', (type, FormulaType) => {
const examples = new FormulaType().getExamples()
expect(examples.length).toBeGreaterThan(0)
for (const example of examples) {
expect(typeof example.formula).toBe('string')
expect(example.formula).not.toBe('')
expect(typeof example.result).toBe('string')
expect(() => parseBaserowFormula(example.formula)).not.toThrow()
}
})
})