kommitters / editorjs-undo

Undo/Redo feature for Editor.js
https://www.npmjs.com/package/editorjs-undo
MIT License
172 stars 51 forks source link

Save function contains a bug where index is used instead of indexInState #113

Closed trevrdspcdev closed 2 years ago

trevrdspcdev commented 2 years ago

Precheck

Description

There is a bug in the save function where index is incorrectly being used in place of indexInState.

Environment

Current behavior

When determining the caretIndex, index is incorrectly used in the state[index].type === 'header' comparison

/**
 * Adds the saved data in the history stack and updates current position.
 */
save(state) {
  if (this.position >= this.maxLength) {
    this.truncate(this.stack, this.maxLength);
  }
  this.position = Math.min(this.position, this.stack.length - 1);

  this.stack = this.stack.slice(0, this.position + 1);

  const index = this.blocks.getCurrentBlockIndex();
  const blockCount = this.blocks.getBlocksCount();
  let indexInState = index;

  if (!state[index]) indexInState -= (blockCount - state.length);
  const caretIndex = state[indexInState].type === 'paragraph' || state[index].type === 'header'
    ? this.getCaretIndex(index) : null;
  this.stack.push({ index: indexInState, state, caretIndex });
  this.position += 1;
  this.onUpdate();
}

Expected behavior

When determining the caretIndex, indexInState should be used in both comparisons

/**
 * Adds the saved data in the history stack and updates current position.
 */
save(state) {
  if (this.position >= this.maxLength) {
    this.truncate(this.stack, this.maxLength);
  }
  this.position = Math.min(this.position, this.stack.length - 1);

  this.stack = this.stack.slice(0, this.position + 1);

  const index = this.blocks.getCurrentBlockIndex();
  const blockCount = this.blocks.getBlocksCount();
  let indexInState = index;

  if (!state[index]) indexInState -= (blockCount - state.length);
  const caretIndex = state[indexInState].type === 'paragraph' || state[indexInState].type === 'header'
    ? this.getCaretIndex(index) : null;
  this.stack.push({ index: indexInState, state, caretIndex });
  this.position += 1;
  this.onUpdate();
}
MarioRodriguezS commented 2 years ago

This issue was solved in the pull request #114.