Skip to content

Undo and History

In this example, we will show you how to use the CreativeEditor SDK’s CreativeEngine to undo and redo steps in the editor API.

Functions

fun createHistory(): History
  • Brief: Create a history which consists of an undo/redo stack for editing operations.

There can be multiple. But only one can be active at a time.

  • Returns the handle to the created history.
fun destroyHistory(history: History)

Destroy the given history, returns an error if the handle doesn’t refer to a history.

  • history: the history to be destroyed.
fun setActiveHistory(history: History)

Mark the given history as active, returns an error if the handle doesn’t refer to a history.

All other histories get cleared from the active state. Undo/redo operations only apply to the active history.

  • history: the history to be marked as active.
fun getActiveHistory(): History

Get the handle to the currently active history. If there’s none it will be created.

  • Returns the handle to the active history.
fun addUndoStep()

Adds a new history state to the stack, if undoable changes were made.

fun undo()

Undo one step in the history if an undo step is available.

fun canUndo(): Boolean

If an undo step is available.

  • Returns true if an undo step is available.
fun redo()

Redo one step in the history if a redo step is available.

fun canRedo(): Boolean

If a redo step is available.

  • Returns true if a redo step is available.
fun onHistoryUpdated(): Flow<Unit>

Subscribe to changes to the undo/redo history.

  • Returns flow of history updates.

Full Code

Here’s the full code:

// Manage history stacks
val newHistory = engine.editor.createHistory()
val oldHistory = engine.editor.getActiveHistory()
engine.editor.setActiveHistory(newHistory)
engine.editor.destroyHistory(oldHistory)
engine.editor.onHistoryUpdated()
.onEach { println("Editor history updated") }
.launchIn(CoroutineScope(Dispatchers.Main))
// Push a new state to the undo stack
engine.editor.addUndoStep()
// Perform an undo, if possible.
if (engine.editor.canUndo()) {
engine.editor.undo()
}
// Perform a redo, if possible.
if (engine.editor.canRedo()) {
engine.editor.redo()
}