How 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 introducingredux-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).
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 {}
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 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 } }
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
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 对象,那么给应用添上「撤销重做」功能的大致代码如下:
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) }
第五步:合并 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中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

Detailed explanation of the functions and functions of GDM under Linux In the Linux operating system, GDM (GNOMEDisplayManager) is a graphical login manager that provides an interface for users to log in and log out of the system. GDM is usually part of the GNOME desktop environment, but can be used by other desktop environments as well. The role of GDM is not only to provide a login interface, but also includes user session management, screen saver, automatic login and other functions. The functions of GDM mainly include the following aspects:

PHP is a server-side scripting language widely used in web development. Its main function is to generate dynamic web content. When combined with HTML, it can create rich and colorful web pages. PHP is powerful. It can perform various database operations, file operations, form processing and other tasks, providing powerful interactivity and functionality for websites. In the following articles, we will further explore the role and functions of PHP, with detailed code examples. First, let’s take a look at a common use of PHP: dynamic web page generation: P
