fix(editor): fix formula $-substitution corruption and sorted-grid row/formula desync
Build / Build-and-ng-test (pull_request) Successful in 5m23s
Lighthouse Checks / lighthouse (pull_request) Successful in 22m6s
Build / Build-and-test-development (pull_request) Successful in 25m7s

String.replace interpreted $&/$`/$'/$<digit> specially in DC.ORIG_VALUE/DC.USER_NAME substitutions, corrupting formulas whose cell data happened to contain a literal $. Separately, afterChange indexed dataSource with Handsontable's visual row instead of translating to physical (as beforeChange already does), desyncing EDIT_STATUS/overwritten-comment writes on a sorted grid. Investigating that surfaced a third, unrelated Handsontable bug: updateSettings() corrupts formula cell references whenever a sort is active, regardless of what it changes - fixed by clearing the sort around every updateSettings() call.
This commit is contained in:
YuryShkoda committed 2026-09-02 17:19:58 +03:00
1 parent 1ed31f2a49
commit e139c37fbf
6 files changed
+601 -21

No files matched your search

+80
View File
@@ -1770,6 +1770,86 @@ context('editor tests: ', function () {
})
})
})
// afterChange delivers Handsontable's own VISUAL row - the EDIT_STATUS/
// overwritten-comment sync hook must translate that to physical before
// touching dataSource (classifyRow, PK-matching), and the two methods it
// calls must translate back to visual for their own Handsontable/
// comments-plugin writes. ROW_STATUS_COL (=DC.ROW_STATUS) makes the
// EDIT_STATUS write directly observable, so sorting first (breaking
// visual/physical alignment) and editing the row that moved proves the
// fix end-to-end, not just that an unsorted grid still works.
it('53 | Editing a row after sorting updates DC.ROW_STATUS on that same row, not whatever row now visually sits in its old position', () => {
openTableFromTree('testdata', 'mpe_x_formula_test')
clickOnEdit(() => {
cy.get('.btn.btn-sm.btn-icon.btn-outline-danger', {
timeout: longerCommandTimeout
}).then(() => {
sortByColumn('PLAIN_TEXT_COL')
cy.get('.ht_clone_top .htCore thead tr th').then(($ths) => {
const pkColIndex = [...$ths].findIndex(
(th) => th.innerText.trim() === 'PRIMARY_KEY_FIELD'
)
const statusColIndex = [...$ths].findIndex(
(th) => th.innerText.trim() === 'ROW_STATUS_COL'
)
cy.get('.ht_master tbody tr').then((rows: any) => {
const visualRow = [...rows].findIndex(
(row: any) => row.childNodes[pkColIndex].innerText.trim() === '1'
)
// Rows 7-10 (their own pre-existing FORMULA_HARD_COL/
// FORMULA_SOFT_COL data, silently overwritten by the DQ rule -
// see test 28) already read 'M' from the very first render, so
// asserting a specific OTHER row is 'U' would be a coincidence
// of seed data, not a proof of anything. Snapshot every other
// row's own status instead, and assert none of them changed -
// that's what actually distinguishes "the edit landed on the
// right row" from "it landed on whatever moved into that
// visual slot".
const beforeStatuses = [...rows].map((row: any, i: number) =>
i === visualRow
? null
: row.childNodes[statusColIndex].innerText.trim()
)
getCellByHeaderAndRow(visualRow, 'ROW_STATUS_COL').should(
'have.text',
'U'
)
getCellByHeaderAndRow(visualRow, 'A_COL')
.dblclick({ force: true })
.then(() => {
cy.focused().clear().type('999{enter}')
})
// The edited row (PK=1) shows 'M' at its own visual position...
getCellByHeaderAndRow(visualRow, 'ROW_STATUS_COL').should(
'have.text',
'M'
)
// ...and every other row's status is exactly what it was
// before - none of them got the write meant for row PK=1.
cy.get('.ht_master tbody tr').should((rows2: any) => {
;[...rows2].forEach((row: any, i: number) => {
if (i === visualRow) return
const status = row.childNodes[statusColIndex].innerText.trim()
expect(status, `row ${i} status unchanged`).to.equal(
beforeStatuses[i]
)
})
})
})
})
})
})
})
})
// Handsontable virtualizes columns — with 18 columns on MPE_X_NEW, only
+97 -20
View File
@@ -649,6 +649,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
private ariaObserver: MutationObserver | undefined
private ariaCheckInterval: any | undefined
private gridResizeObserver: ResizeObserver | undefined
private pasteListener: ((event: ClipboardEvent) => void) | undefined
constructor(
private licenceService: LicenceService,
@@ -984,7 +985,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
this.excelUploadState = 'Validating-HOT'
hot.updateSettings(
this.updateSettingsSortSafe(
{
data: this.dataSource,
maxRows: Infinity
@@ -1009,7 +1010,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
* @param discardData wheter to discard data parsed from the file or to keep it in the table after dropping a attached excel file
*/
public discardPendingExcel(discardData?: boolean) {
this.hotInstance.updateSettings({
this.updateSettingsSortSafe({
maxRows: this.licenceState.value.editor_rows_allowed
})
@@ -1210,6 +1211,34 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
}
}
/**
* Wraps hot.updateSettings() to work around a genuine Handsontable
* multiColumnSorting + formulas plugin bug: calling updateSettings() -
* with ANY settings, even a bare {} - while a sort is active corrupts
* formula cell references, rendering '#REF!' instead of their computed
* value (reproduced directly: a bare {} settings object alone is enough
* to trigger it, independent of what it actually changes). Clearing the
* sort first and restoring it immediately afterward avoids the
* corruption entirely. Not needed for the very first updateSettings()
* call at initial table load, since nothing can be sorted yet then.
*/
private updateSettingsSortSafe(
settings: Handsontable.GridSettings,
render?: boolean
): void {
const hot = this.hotInstance
const columnSorting = hot.getPlugin('multiColumnSorting')
const sortConfigs = this.getCurrentSortConfigs()
if (sortConfigs.length > 0) columnSorting.clearSort()
hot.updateSettings(settings, render)
for (const sortConfig of sortConfigs) {
columnSorting.sort(sortConfig)
}
}
editTable(previewEdit?: boolean, newRow?: boolean) {
this.toggleHotPlugin('contextMenu', true)
@@ -1239,6 +1268,13 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
this.hotTable.readOnly = false
this.hotTable.data = this.dataSource
// Handsontable's multiColumnSorting + formulas integration corrupts
// formula cell references (renders '#REF!') if updateSettings() runs
// while a sort is still active, even for an unrelated setting -
// clear it first and restore the captured sortConfigs afterward
// (below), rather than leaving the sort applied across the call.
if (sortConfigs.length > 0) columnSorting.clearSort()
hot.updateSettings(
{
readOnly: this.hotTable.readOnly
@@ -1343,6 +1379,12 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
this.hotTable.data = this.dataSource
this.hotTable.readOnly = true
// See editTable()'s own comment - updateSettings() while a sort is
// still active corrupts formula cell references ('#REF!'), so clear it
// first and restore sortConfigs afterward (below) instead of leaving
// the sort applied across the call.
if (sortConfigs.length > 0) columnSorting.clearSort()
hot.updateSettings(
{
readOnly: this.hotTable.readOnly,
@@ -1727,6 +1769,13 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
* call after a row insert/delete/sort has moved things around). No-op if
* the row has no PK match in dataSourceRaw (a newly-inserted row) - see
* findOverwrittenCells for why that's never revertable.
*
* rowIndex is physical (matches dataSource's own order, same contract as
* syncOverwrittenComments()'s own dataSource.forEach caller below) -
* getDataAtRowProp and the comments plugin's own cell API all document a
* VISUAL row instead, so it's translated via hot.toVisualRow() for every
* Handsontable/plugin call, while dataSource itself stays indexed by the
* physical rowIndex throughout.
*/
private syncOverwrittenCommentForCell(rowIndex: number, prop: string): void {
const hot = this.hotInstance
@@ -1738,11 +1787,14 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
)
if (!rawRow) return
const visualRow = hot.toVisualRow(rowIndex)
if (visualRow === null) return
const colIndex = hot.propToCol(prop) as number
const commentsPlugin = hot.getPlugin('comments')
const currentValue = hot.getDataAtRowProp(rowIndex, prop)
const currentValue = hot.getDataAtRowProp(visualRow, prop)
const hasCommentAlready = !!commentsPlugin.getCommentAtCell(
rowIndex,
visualRow,
colIndex
)
@@ -1754,12 +1806,12 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
if (action === 'set') {
commentsPlugin.setCommentAtCell(
rowIndex,
visualRow,
colIndex,
`${EditorComponent.ORIGINAL_VALUE_COMMENT_PREFIX}${rawRow[prop]}`
)
} else if (action === 'remove') {
commentsPlugin.removeCommentAtCell(rowIndex, colIndex)
commentsPlugin.removeCommentAtCell(visualRow, colIndex)
}
}
@@ -1910,6 +1962,12 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
* HyperFormula is notified and dependents recalculate - the source string
* also lets the afterChange hook below recognise and ignore its own
* writes, avoiding infinite recursion.
*
* rowIndex is physical (matches dataSource's own order, same contract as
* addRow()/insertRowAtPosition()'s own callers) - setDataAtRowProp
* documents a VISUAL row instead, so it's translated via
* hot.toVisualRow() right before that one call, while dataSource itself
* stays indexed by the physical rowIndex.
*/
private updateEditStatusForRow(rowIndex: number): void {
const dataRow = this.dataSource[rowIndex]
@@ -1921,8 +1979,11 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
this.headerPks
)
const visualRow = this.hotInstance.toVisualRow(rowIndex)
if (visualRow === null) return
this.hotInstance.setDataAtRowProp(
rowIndex,
visualRow,
EDIT_STATUS_COLUMN_NAME,
status,
'editStatus'
@@ -1935,7 +1996,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
this.hotTable.data = this.dataSource
const hot = this.hotInstance
hot.updateSettings(
this.updateSettingsSortSafe(
{
data: this.dataSource,
colHeaders: getDisplayColHeaders(
@@ -2401,7 +2462,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
}
}
hot.updateSettings(
this.updateSettingsSortSafe(
{
data: this.dataSource,
colHeaders: getDisplayColHeaders(
@@ -2711,9 +2772,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
if (this.recordAction === 'ADD' && !confirmButtonClicked) {
this.dataSource = this.helperService.deepClone(this.prevDataSource)
const hot = this.hotInstance
hot.updateSettings(
this.updateSettingsSortSafe(
{
data: this.dataSource
},
@@ -2740,9 +2799,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
this.dataSource[closingRecordIndex] = this.currentEditRecord
this.hotTable.data[closingRecordIndex] = this.currentEditRecord
const hot = this.hotInstance
hot.updateSettings(
this.updateSettingsSortSafe(
{
data: this.dataSource
},
@@ -3515,7 +3572,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
this.useLabels
)
this.hotInstance.updateSettings({ colHeaders }, false)
this.updateSettingsSortSafe({ colHeaders }, false)
}
ngOnDestroy() {
@@ -3539,6 +3596,16 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
this.gridResizeObserver = undefined
}
// Remove the native paste listener (see its own registration comment -
// attached once on rootElement rather than per edit session)
if (this.pasteListener && this.hotInstance?.rootElement) {
this.hotInstance.rootElement.removeEventListener(
'paste',
this.pasteListener
)
this.pasteListener = undefined
}
// Cancel any pending debounced VA apply
if (this.vaDebounceTimer) {
clearTimeout(this.vaDebounceTimer)
@@ -3564,7 +3631,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
requestAnimationFrame(() => {
const hot = this.hotInstance
if (!hot || hot.isDestroyed) return
hot.updateSettings({ height: this.hotTable.height }, false)
this.updateSettingsSortSafe({ height: this.hotTable.height }, false)
hot.render()
})
})
@@ -4392,9 +4459,18 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
for (const change of changes) {
if (!change) continue
const [row, prop] = change
// changes gives the VISUAL row (Handsontable's own documented
// afterChange shape) - translate to physical before indexing
// dataSource, same as beforeChange's own hot.toPhysicalRow(changeRow)
// a few lines up. syncOverwrittenCommentForCell/updateEditStatusForRow
// both expect physical (they translate back to visual internally,
// only where a Handsontable API actually needs it).
const [visualRow, prop] = change
if (prop === EDIT_STATUS_COLUMN_NAME) continue
const row = hot.toPhysicalRow(visualRow)
if (row === null) continue
changedRows.add(row)
if (revertableCols.includes(prop)) {
@@ -4590,7 +4666,7 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
// element (paste events bubble) rather than attaching a new listener
// per edit session, to avoid accumulating listeners across repeated
// edits.
hot.rootElement.addEventListener('paste', (event: ClipboardEvent) => {
this.pasteListener = (event: ClipboardEvent) => {
const editor: any = hot.getActiveEditor()
if (!editor || editor.row === null || event.target !== editor.TEXTAREA)
return
@@ -4614,7 +4690,8 @@ export class EditorComponent implements OnInit, AfterViewInit, OnDestroy {
// manually so the editor's own input-tracking (autosize, its
// internal notion of the current value) picks up the change.
editor.TEXTAREA.dispatchEvent(new Event('input', { bubbles: true }))
})
}
hot.rootElement.addEventListener('paste', this.pasteListener)
hot.addHook(
'beforeAutofill',
@@ -0,0 +1,372 @@
import Handsontable from 'handsontable'
import { HyperFormula } from 'hyperformula'
import { classifyRow } from './classifyRow'
import { EDIT_STATUS_COLUMN_NAME } from '../../shared/dc-validator/utils/editStatusColumnRule'
import { parseFormulaRule } from '../../shared/dc-validator/utils/parseFormulaRule'
/**
* afterChange delivers changes as [visualRow, prop, oldValue, newValue] -
* Handsontable's own documented behaviour. Once multiColumnSorting reorders
* the grid, visual row order no longer matches dataSource's physical order.
* editor.component.ts's afterChange hook (the one syncing EDIT_STATUS and
* the "overwritten" comment) passes that raw visual row straight into
* updateEditStatusForRow/syncOverwrittenCommentForCell, both of which index
* dataSource directly - the same [visualRow] shape the beforeChange hook a
* few lines up in the same file already translates via
* hot.toPhysicalRow(changeRow) before doing the same kind of dataSource
* access.
*
* Mirrors the row extraction only (not the full hook), against a real
* Handsontable + multiColumnSorting instance, since proving visual/physical
* divergence requires an actual sort to have happened.
*/
describe('afterChange must translate the changed row to physical before indexing dataSource, on a sorted grid', () => {
const setup = (): { hot: Handsontable; dataSource: any[] } => {
// Physical row 0: PK=1. Physical row 1: PK=2.
const dataSource = [
{ PRIMARY_KEY_FIELD: 1, SOME_CHAR: 'b' },
{ PRIMARY_KEY_FIELD: 2, SOME_CHAR: 'a' }
]
const hot = new Handsontable(document.createElement('div'), {
data: dataSource,
columns: [{ data: 'PRIMARY_KEY_FIELD' }, { data: 'SOME_CHAR' }],
multiColumnSorting: true,
licenseKey: 'non-commercial-and-evaluation'
})
hot.render()
// Ascending by SOME_CHAR flips the order: physical row 1 (SOME_CHAR
// 'a') becomes visual row 0; physical row 0 (SOME_CHAR 'b') becomes
// visual row 1.
const sortPlugin: any = hot.getPlugin('multiColumnSorting')
sortPlugin.sort({ column: 1, sortOrder: 'asc' })
hot.render()
return { hot, dataSource }
}
it('demonstrates the failure mode: indexing dataSource with the raw visual row reads the wrong row', () => {
const { hot, dataSource } = setup()
// The user edits what they see as the FIRST row on screen - visual
// row 0, which after sorting is physical row 1 (PK=2).
const visualRow = 0
// Mirrors the current (buggy) afterChange hook: uses the visual row
// straight from `changes` to index dataSource.
const wronglyReadRow = dataSource[visualRow]
expect(wronglyReadRow.PRIMARY_KEY_FIELD).not.toEqual(2)
expect(wronglyReadRow.PRIMARY_KEY_FIELD).toEqual(1) // the OTHER row
// Mirrors the fix: translate visual -> physical first, matching
// beforeChange's own hot.toPhysicalRow(changeRow) pattern.
const physicalRow = hot.toPhysicalRow(visualRow)
const correctlyReadRow = dataSource[physicalRow as number]
expect(correctlyReadRow.PRIMARY_KEY_FIELD).toEqual(2)
hot.destroy()
})
})
/**
* updateEditStatusForRow/syncOverwrittenCommentForCell's own established
* contract (per their other existing callers - addRow/insertRowAtPosition,
* and syncOverwrittenComments()'s own `dataSource.forEach((_row, rowIndex)
* => ...)`) is a PHYSICAL row index, used to index dataSource. But both
* also call Handsontable APIs - hot.setDataAtRowProp/getDataAtRowProp
* (updateEditStatusForRow) and the comments plugin's setCommentAtCell/
* getCommentAtCell/removeCommentAtCell (syncOverwrittenCommentForCell) -
* which Handsontable's own JSDoc documents as expecting the VISUAL row.
* Passing the physical row straight through to those (the current code)
* only happens to work when visual and physical coincide - i.e. an
* unsorted grid. On a sorted one, translating the afterChange hook's own
* row (see the describe block above) is necessary but not sufficient -
* these two methods must also convert their own physical rowIndex
* parameter to visual before calling any Handsontable API, or the fix
* above just moves the bug rather than closing it.
*/
describe('updateEditStatusForRow resolves the correct visual cell on a sorted grid', () => {
const headerPks = ['PRIMARY_KEY_FIELD']
const setup = (): { hot: Handsontable; dataSource: any[] } => {
const dataSource = [
{
PRIMARY_KEY_FIELD: 1,
SOME_CHAR: 'b',
[EDIT_STATUS_COLUMN_NAME]: 'U'
},
{
PRIMARY_KEY_FIELD: 2,
SOME_CHAR: 'a',
[EDIT_STATUS_COLUMN_NAME]: 'U'
}
]
const hot = new Handsontable(document.createElement('div'), {
data: dataSource,
columns: [
{ data: 'PRIMARY_KEY_FIELD' },
{ data: 'SOME_CHAR' },
{ data: EDIT_STATUS_COLUMN_NAME }
],
multiColumnSorting: true,
licenseKey: 'non-commercial-and-evaluation'
})
hot.render()
// Ascending by SOME_CHAR: physical row 1 (PK=2) -> visual row 0;
// physical row 0 (PK=1) -> visual row 1.
const sortPlugin: any = hot.getPlugin('multiColumnSorting')
sortPlugin.sort({ column: 1, sortOrder: 'asc' })
hot.render()
return { hot, dataSource }
}
// Mirrors the CURRENT updateEditStatusForRow - uses the (correct,
// physical) rowIndex directly for the Handsontable write too.
const updateEditStatusForRowBuggy = (
hot: Handsontable,
dataSource: any[],
dataSourceUnchanged: any[],
rowIndex: number
): void => {
const dataRow = dataSource[rowIndex]
if (!dataRow) return
const status = classifyRow(dataRow, dataSourceUnchanged, headerPks)
hot.setDataAtRowProp(
rowIndex,
EDIT_STATUS_COLUMN_NAME,
status,
'editStatus'
)
}
// Mirrors the fix - dataSource access stays physical; the Handsontable
// write is translated to visual first.
const updateEditStatusForRowFixed = (
hot: Handsontable,
dataSource: any[],
dataSourceUnchanged: any[],
rowIndex: number
): void => {
const dataRow = dataSource[rowIndex]
if (!dataRow) return
const status = classifyRow(dataRow, dataSourceUnchanged, headerPks)
const visualRow = hot.toVisualRow(rowIndex)
if (visualRow === null) return
hot.setDataAtRowProp(
visualRow,
EDIT_STATUS_COLUMN_NAME,
status,
'editStatus'
)
}
it('demonstrates the failure mode: the buggy version writes the status to the wrong cell', () => {
const { hot, dataSource } = setup()
// Physical row 1 (PK=2) is the one that actually changed vs its
// unchanged baseline (SOME_CHAR 'a' vs 'ORIGINAL') - classifyRow
// should mark it 'M'. It's currently displayed at visual row 0.
const dataSourceUnchanged = [
{
PRIMARY_KEY_FIELD: 1,
SOME_CHAR: 'b',
[EDIT_STATUS_COLUMN_NAME]: 'U'
},
{
PRIMARY_KEY_FIELD: 2,
SOME_CHAR: 'ORIGINAL',
[EDIT_STATUS_COLUMN_NAME]: 'U'
}
]
updateEditStatusForRowBuggy(hot, dataSource, dataSourceUnchanged, 1)
// Buggy: wrote 'M' to visual row 1 (PK=1's cell, unaffected), not
// visual row 0 (PK=2's actual current position).
expect(hot.getDataAtRowProp(1, EDIT_STATUS_COLUMN_NAME)).toEqual('M')
expect(hot.getDataAtRowProp(0, EDIT_STATUS_COLUMN_NAME)).toEqual('U')
hot.destroy()
})
it('writes the status to the correct (visually current) cell once fixed', () => {
const { hot, dataSource } = setup()
const dataSourceUnchanged = [
{
PRIMARY_KEY_FIELD: 1,
SOME_CHAR: 'b',
[EDIT_STATUS_COLUMN_NAME]: 'U'
},
{
PRIMARY_KEY_FIELD: 2,
SOME_CHAR: 'ORIGINAL',
[EDIT_STATUS_COLUMN_NAME]: 'U'
}
]
updateEditStatusForRowFixed(hot, dataSource, dataSourceUnchanged, 1)
expect(hot.getDataAtRowProp(0, EDIT_STATUS_COLUMN_NAME)).toEqual('M')
expect(hot.getDataAtRowProp(1, EDIT_STATUS_COLUMN_NAME)).toEqual('U')
hot.destroy()
})
})
/**
* Same physical/visual split as updateEditStatusForRow above, for the
* comments plugin's own row-indexed API (setCommentAtCell/
* getCommentAtCell/removeCommentAtCell all document a VISUAL row -
* propToCol, unlike the row side, already returns a visual column, so
* only the row needs translating).
*/
describe('syncOverwrittenCommentForCell resolves the correct visual cell on a sorted grid', () => {
const setup = (): { hot: Handsontable } => {
const dataSource = [
{ PRIMARY_KEY_FIELD: 1, SOME_CHAR: 'b' },
{ PRIMARY_KEY_FIELD: 2, SOME_CHAR: 'a' }
]
const hot = new Handsontable(document.createElement('div'), {
data: dataSource,
columns: [{ data: 'PRIMARY_KEY_FIELD' }, { data: 'SOME_CHAR' }],
multiColumnSorting: true,
comments: true,
licenseKey: 'non-commercial-and-evaluation'
})
hot.render()
const sortPlugin: any = hot.getPlugin('multiColumnSorting')
sortPlugin.sort({ column: 1, sortOrder: 'asc' })
hot.render()
return { hot }
}
it('demonstrates the failure mode: setCommentAtCell(physicalRow, ...) lands on the wrong visual cell', () => {
const { hot } = setup()
const commentsPlugin: any = hot.getPlugin('comments')
// Mirrors the buggy call: the established-physical rowIndex (1) used
// directly against a Handsontable API that wants visual.
commentsPlugin.setCommentAtCell(1, 1, 'Original value: b')
// Landed on visual row 1 (PK=1's cell), not visual row 0 (PK=2's
// actual current position, physical row 1).
expect(commentsPlugin.getCommentAtCell(1, 1)).toEqual('Original value: b')
expect(commentsPlugin.getCommentAtCell(0, 1)).toBeUndefined()
hot.destroy()
})
it('lands on the correct visual cell once translated to visual first', () => {
const { hot } = setup()
const commentsPlugin: any = hot.getPlugin('comments')
const visualRow = hot.toVisualRow(1)
commentsPlugin.setCommentAtCell(visualRow, 1, 'Original value: a')
expect(commentsPlugin.getCommentAtCell(0, 1)).toEqual('Original value: a')
expect(commentsPlugin.getCommentAtCell(1, 1)).toBeUndefined()
hot.destroy()
})
})
/**
* A genuine Handsontable multiColumnSorting + formulas plugin bug (not
* specific to any of DC's own hooks): calling hot.updateSettings() - with
* ANY settings, even a bare {} - while a sort is active corrupts formula
* cell references, rendering '#REF!' instead of their computed value.
* Reproduced directly: a no-op {} settings object alone is enough to
* trigger it, independent of what it actually changes. editTable(),
* cancelEdit(), and every other place editor.component.ts calls
* updateSettings() after the grid could already be sorted (e.g. the user
* sorted while still read-only, then clicked Edit) hits this. The fix
* (updateSettingsSortSafe) clears the sort before the call and restores it
* immediately afterward.
*/
describe('updateSettings must not run while a sort is active - it corrupts formula cell references', () => {
const buildSortedGrid = (): Handsontable => {
const columnNames = [
'PRIMARY_KEY_FIELD',
'A_COL',
'B_COL',
'FORMULA_HARD_COL',
'PLAIN_TEXT_COL'
]
const data = Array.from({ length: 10 }, (_, i) => ({
PRIMARY_KEY_FIELD: i + 1,
A_COL: i + 1,
B_COL: 10,
FORMULA_HARD_COL: '',
PLAIN_TEXT_COL: `note-${i + 1}`
}))
data.forEach((row: any, i) => {
row.FORMULA_HARD_COL = parseFormulaRule('=A_COL * B_COL', {
columnNames,
rowIndex: i,
userName: 'test',
origValue: undefined
})
})
const hot = new Handsontable(document.createElement('div'), {
data,
columns: columnNames.map((c) => ({ data: c })),
formulas: { engine: HyperFormula, licenseKey: 'gpl-v3' },
multiColumnSorting: true,
licenseKey: 'non-commercial-and-evaluation'
})
hot.render()
const sortPlugin: any = hot.getPlugin('multiColumnSorting')
sortPlugin.sort({
column: columnNames.indexOf('PLAIN_TEXT_COL'),
sortOrder: 'desc'
})
hot.render()
return hot
}
const formulaHardColValues = (hot: Handsontable): any[] =>
Array.from({ length: 10 }, (_, r) =>
hot.getDataAtRowProp(r, 'FORMULA_HARD_COL')
)
it('demonstrates the failure mode: updateSettings while sorted corrupts formula cells', () => {
const hot = buildSortedGrid()
hot.updateSettings({}, false)
hot.render()
expect(formulaHardColValues(hot)).toContain('#REF!')
hot.destroy()
})
it('clearing the sort before updateSettings and restoring it after avoids the corruption', () => {
const hot = buildSortedGrid()
const sortPlugin: any = hot.getPlugin('multiColumnSorting')
const sortConfig = sortPlugin.getSortConfig()
const sortConfigs = Array.isArray(sortConfig)
? sortConfig
: sortConfig
? [sortConfig]
: []
sortPlugin.clearSort()
hot.updateSettings({}, false)
hot.render()
for (const sc of sortConfigs) sortPlugin.sort(sc)
hot.render()
expect(formulaHardColValues(hot)).not.toContain('#REF!')
hot.destroy()
})
})
@@ -116,4 +116,33 @@ describe('parseFormulaRule', () => {
it('does not insert a leading = when the rule value does not have one, so HOT treats it as plain text rather than a formula', () => {
expect(parseFormulaRule('PRICE * VOLUME', context())).toEqual('B1 * C1')
})
// String.prototype.replace interprets $&/$`/$'/$<digit> specially when
// the replacement is a string - DC.ORIG_VALUE/DC.USER_NAME substitute in
// arbitrary data (any character column's prior value, or a username),
// which can legitimately contain a literal '$'. These must round-trip
// untouched, not have HyperFormula's own pattern-matching corrupt them.
it('substitutes a DC.ORIG_VALUE containing a literal $& without corruption', () => {
expect(
parseFormulaRule('=DC.ORIG_VALUE', context({ origValue: 'a$&b' }))
).toEqual('="a$&b"')
})
it("substitutes a DC.ORIG_VALUE containing a literal $' without corruption", () => {
expect(
parseFormulaRule('=DC.ORIG_VALUE', context({ origValue: "a$'b" }))
).toEqual('="a$\'b"')
})
it('substitutes a DC.ORIG_VALUE containing a literal $` without corruption', () => {
expect(
parseFormulaRule('=DC.ORIG_VALUE', context({ origValue: 'a$`b' }))
).toEqual('="a$`b"')
})
it('substitutes a DC.USER_NAME containing a literal $1 without corruption', () => {
expect(
parseFormulaRule('=DC.USER_NAME', context({ userName: 'a$1b' }))
).toEqual('="a$1b"')
})
})
@@ -32,7 +32,11 @@ export const substituteBoundedToken = (
'g'
)
return text.replace(pattern, replacement)
// A function replacement's return value is used verbatim - a string
// replacement would otherwise have String.replace interpret $&/$`/$'/
// $<digit> specially, and `replacement` here can be arbitrary data (a
// cell's prior value, a username) that may legitimately contain '$'.
return text.replace(pattern, () => replacement)
}
const quoteLiteral = (value: string | number | undefined): string =>
@@ -54,4 +54,22 @@ describe('substituteColumnReferences', () => {
substituteColumnReferences('just a note about PRICE', columnNames, 0)
).toEqual('just a note about B1')
})
// This function's own replacement values are always system-generated
// cell refs (e.g. "B1") that can never contain '$', so it can't trigger
// substituteBoundedToken's $-pattern corruption itself - but it shares
// that function with parseFormulaRule.ts (which can), so confirm a
// literal '$' elsewhere in the input still round-trips correctly
// through the shared (now function-replacement-based) substitution.
it('leaves a literal $ in the surrounding text untouched by an unrelated column substitution', () => {
expect(
substituteColumnReferences('PRICE + $5 fee', columnNames, 0)
).toEqual('B1 + $5 fee')
})
it('leaves a literal $ inside a quoted span untouched', () => {
expect(
substituteColumnReferences('PRICE & " costs $5 "', columnNames, 0)
).toEqual('B1 & " costs $5 "')
})
})