search
HomeWeb Front-endJS TutorialHow to create undo and redo function in js

This time I will show you how to make the undo and redo function in js. What are the precautions for making the undo and redo function in js? The following is a practical case, let’s take a look.

The functions of browsers are becoming more and more powerful. Many functions originally provided by other clients have gradually been transferred to the front end, and front-end applications are becoming more and more complex. Many front-end applications, especially some online editing software, need to continuously process user interactions during operation, and provide an undo and redo function to ensure smooth interaction. However, implementing the undo and redo function for an application is not an easy task. The official Redux documentation introduces how to implement the undo and redo function in redux applications. The undo function based on redux is a top-down solution: after introducing

redux-undo , all operations become "undoable", and then we continue to modify its configuration to make the undo function more and more convenient. The better (this is also redux-undo The reason why there are so many configuration items).

This article will adopt a bottom-up approach, taking a simple online drawing tool as an example, and using TypeScript and Immutable.js to implement a practical "undo and redo" function. The general effect is shown in the figure below:

Step 1: Determine which states require historical records and create a custom State class

Not all states require history records. Many states are very trivial, especially those related to mouse or keyboard interaction. For example, when dragging a graphic in the drawing tool, we need to set a "drag-in-progress" mark, and the page will display the corresponding Drag prompt, obviously the drag mark should not appear in the history; and other states cannot be revoked or do not need to be revoked, such as the web page window size, the list of requests sent to the background, etc.

Excluding those states that do not require history records, we encapsulate the remaining states with Immutable Record and define the State class:

// State.ts
import { Record, List, Set } from 'immutable'
const StateRecord = Record({
 items: List<item>
 transform: d3.ZoomTransform
 selection: number
})
// 用类封装,便于书写 TypeScript,注意这里最好使用Immutable 4.0 以上的版本
export default class State extends StateRecord {}</item>
Our example here is a simple online drawing tool , so the above State class contains three fields, items is used to record the drawn graphics, transform is used to record the panning and zooming status of the artboard, and selection represents the ID of the currently selected graphics. Other states in the drawing tool, such as graphic drawing preview, automatic alignment configuration, operation prompt text, etc., are not placed in the State class.

Step 2: Define the Action base class and create corresponding Action subclasses for each different operation

The difference from redux-undo is that we still Adopt

Command mode: Define the base class Action, and all operations on State are encapsulated as an instance of Action; define several subclasses of Action, corresponding to different types of operations.

In TypeScript, it is more convenient to define the Action base class with Abstract Class.

// actions/index.ts
export default abstract class Action {
 abstract next(state: State): State
 abstract prev(state: State): State
 prepare(appHistory: AppHistory): AppHistory { return appHistory }
 getMessage() { return this.constructor.name }
}
The next method of the Action object is used to calculate the "next state", and the prev method is used to calculate the "previous state". The getMessage method is used to obtain a brief description of the Action object. Through the getMessage method, we can display the user's operation records on the page, making it easier for users to understand what happened recently. The prepare method is used to "prepare" the Action before it is applied for the first time. The definition of AppHistory will be given later in this article.

Action subclass example

The following AddItemAction is a typical Action subclass, used to express "add a new graphic".

// actions/AddItemAction.ts
export default class AddItemAction extends Action {
 newItem: Item
 prevSelection: number
 constructor(newItem: Item) {
 super()
 this.newItem = newItem
 }
 prepare(history: AppHistory) {
 // 创建新的图形后会自动选中该图形,为了使得撤销该操作时 state.selection 变为原来的值
 // prepare 方法中读取了「添加图形之前 selection 的值」并保存到 this.prevSelection
 this.prevSelection = history.state.selection
 return history
 }
 next(state: State) {
 return state
  .setIn(['items', this.newItem.id], this.newItem)
  .set('selection', this.newItemId)
 }
 prev(state: State) {
 return state
  .deleteIn(['items', this.newItem.id])
  .set('selection', this.prevSelection)
 }
 getMessage() { return `Add item ${this.newItem.id}` }
}

Runtime behavior

When the application is running, user interaction generates an Action stream. Each time an Action object is generated, we call the object The next method is used to calculate the next state, and then the action is saved to a list for later use; when the user performs an undo operation, we take out the latest Action from the action list and call its prev method. When the application is running, the next/prev method is called as follows:

// initState 是一开始就给定的应用初始状态
// 某一时刻,用户交互产生了 action1 ...
state1 = action1.next(initState)
// 又一个时刻,用户交互产生了 action2 ...
state2 = action2.next(state1)
// 同样的,action3也出现了 ...
state3 = action3.next(state2)
// 用户进行撤销,此时我们需要调用最近一个action的prev方法
state4 = action3.prev(state3)
// 如果再次进行撤销,我们从action列表中取出对应的action,调用其prev方法
state5 = action2.prev(state4)
// 重做的时候,取出最近一个被撤销的action,调用其next方法
state6 = action2.next(state5)
Applied-Action
In order to facilitate the following explanation, we make a simple definition of Applied-Action: Applied-Action refers to those operation results that have been reflected in The action in the current application state; when the next method of the action is executed, the action becomes applied; when the prev method is executed, the action becomes unapplied.

Step 3: Create a history container AppHistory

前面的 State 类用于表示某个时刻应用的状态,接下来我们定义 AppHistory 类用来表示应用的历史记录。同样的,我们仍然使用 Immutable Record 来定义历史记录。其中 state 字段用来表达当前的应用状态,list 字段用来存放所有的 action,而 index 字段用来记录最近的 applied-action 的下标。应用的历史状态可以通过 undo/redo 方法计算得到。apply 方法用来向 AppHistory 中添加并执行具体的 Action。具体代码如下:

// AppHistory.ts
const emptyAction = Symbol('empty-action')
export const undo = Symbol('undo')
export type undo = typeof undo // TypeScript2.7之后对symbol的支持大大增强
export const redo = Symbol('redo')
export type redo = typeof redo
const AppHistoryRecord = Record({
 // 当前应用状态
 state: new State(),
 // action 列表
 list: List<action>(),
 // index 表示最后一个applied-action在list中的下标。-1 表示没有任何applied-action
 index: -1,
})
export default class AppHistory extends AppHistoryRecord {
 pop() { // 移除最后一项操作记录
 return this
  .update('list', list => list.splice(this.index, 1))
  .update('index', x => x - 1)
 }
 getLastAction() { return this.index === -1 ? emptyAction : this.list.get(this.index) }
 getNextAction() { return this.list.get(this.index + 1, emptyAction) }
 apply(action: Action) {
 if (action === emptyAction) return this
 return this.merge({
  list: this.list.setSize(this.index + 1).push(action),
  index: this.index + 1,
  state: action.next(this.state),
 })
 }
 redo() {
 const action = this.getNextAction()
 if (action === emptyAction) return this
 return this.merge({
  list: this.list,
  index: this.index + 1,
  state: action.next(this.state),
 })
 }
 undo() {
 const action = this.getLastAction()
 if (action === emptyAction) return this
 return this.merge({
  list: this.list,
  index: this.index - 1,
  state: action.prev(this.state),
 })
 }
}</action>

第四步:添加「撤销重做」功能

假设应用中的其他代码已经将网页上的交互转换为了一系列的 Action 对象,那么给应用添上「撤销重做」功能的大致代码如下:

type HybridAction = undo | redo | Action
// 如果用Redux来管理状态,那么使用下面的reudcer来管理那些「需要历史记录的状态」
// 然后将该reducer放在应用状态树中合适的位置
function reducer(history: AppHistory, action: HybridAction): AppHistory {
 if (action === undo) {
 return history.undo()
 } else if (action === redo) {
 return history.redo()
 } else { // 常规的 Action
 // 注意这里需要调用prepare方法,好让该action「准备好」
 return action.prepare(history).apply(action)
 }
}
// 如果是在 Stream/Observable 的环境下,那么像下面这样使用 reducer
const action$: Stream<hybridaction> = generatedFromUserInteraction
const appHistory$: Stream<apphistory> = action$.fold(reducer, new AppHistory())
const state$ = appHistory$.map(h => h.state)
// 如果是用回调函数的话,大概像这样使用reducer
onActionHappen = function (action: HybridAction) {
 const nextHistory = reducer(getLastHistory(), action)
 updateAppHistory(nextHistory)
 updateState(nextHistory.state)
}</apphistory></hybridaction>

第五步:合并 Action,完善用户交互体验

通过上面这四个步骤,画图工具拥有了撤消重做功能,但是该功能用户体验并不好。在画图工具中拖动一个图形时,MoveItemAction 的产生频率和 mousemove 事件的发生频率相同,如果我们不对该情况进行处理,MoveItemAction 马上会污染整个历史记录。我们需要合并那些频率过高的 action,使得每个被记录下来的 action 有合理的撤销粒度。

每个 Action 在被应用之前,其 prepare 方法都会被调用,我们可以在 prepare 方法中对历史记录进行修改。例如,对于 MoveItemAction,我们判断上一个 action 是否和当前 action 属于同一次移动操作,然后来决定在应用当前 action 之前是否移除上一个 action。代码如下:

// actions/MoveItemAction.ts
export default class MoveItemAction extends Action {
 prevItem: Item
 // 一次图形拖动操作可以由以下三个变量来进行描述:
 // 拖动开始时鼠标的位置(startPos),拖动过程中鼠标的位置(movingPos),以及拖动的图形的 ID
 constructor(readonly startPos: Point, readonly movingPos: Point, readonly itemId: number) {
 // 上一行中 readonly startPos: Point 相当于下面两步:
 // 1. 在MoveItemAction中定义startPos只读字段
 // 2. 在构造函数中执行 this.startPos = startPos
 super()
 }
 prepare(history: AppHistory) {
 const lastAction = history.getLastAction()
 if (lastAction instanceof MoveItemAction && lastAction.startPos == this.startPos) {
  // 如果上一个action也是MoveItemAction,且拖动操作的鼠标起点和当前action相同
  // 则我们认为这两个action在同一次移动操作中
  this.prevItem = lastAction.prevItem
  return history.pop() // 调用pop方法来移除最近一个action
 } else {
  // 记录图形被移动之前的状态,用于撤销
  this.prevItem = history.state.items.get(this.itemId)
  return history
 }
 }
 next(state: State): State {
 const dx = this.movingPos.x - this.startPos.x
 const dy = this.movingPos.y - this.startPos.y
 const moved = this.prevItem.move(dx, dy)
 return state.setIn(['items', this.itemId], moved)
 }
 prev(state: State) {
 // 撤销的时候我们直接使用已经保存的prevItem即可
 return state.setIn(['items', this.itemId], this.prevItem)
 }
 getMessage() { /* ... */ }
}

从上面的代码中可以看到,prepare 方法除了使 action 自身准备好之外,它还可以让历史记录准备好。不同的 Action 类型有不同的合并规则,为每种 Action 实现合理的 prepare 函数之后,撤消重做功能的用户体验能够大大提升。

一些其他需要注意的地方

撤销重做功能是非常依赖于不可变性的,一个 Action 对象在放入 AppHistory.list 之后,其所引用的对象都应该是不可变的。如果 action 所引用的对象发生了变化,那么在后续撤销时可能发生错误。本方案中,为了方便记录操作发生时的一些必要信息,Action 对象的 prepare 方法中允许出现原地修改操作,但是 prepare 方法只会在 action 被放入历史记录之前调用一次,action 一旦进入纪录列表就是不可变的了。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

上传图片时本地先预览如何实现

JS实现todolist详解

The above is the detailed content of How to create undo and redo function in js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.