Undoing a removed block works after a new block was added (#59)

This commit is contained in:
makiolaj committed 2026-11-27 15:28:00 +01:00
1 parent c583f087a2
commit ee419a2b97
2 files changed
+33 -7

No files matched your search

@@ -14,16 +14,18 @@ import java.time.temporal.TemporalAdjusters
/** Whether a block of [type] can be added to these blocks: a second task list can't. */
fun List<Block>.canAdd(type: BlockType): Boolean = type != BlockType.TASK_LIST || none { it.type == BlockType.TASK_LIST }
/** An id no block here has. */
fun List<Block>.nextBlockId(): Long = (maxOfOrNull { it.id } ?: 0L) + 1
/** An id no block here has, nor any of [reserved] (a removed block its undo may bring back). */
fun List<Block>.nextBlockId(reserved: Set<Long> = emptySet()): Long =
(maxOf(maxOfOrNull { it.id } ?: 0L, reserved.maxOrNull() ?: 0L)) + 1
/**
* These blocks with a new [type] block reading [source], at the end but before
* a task list; unchanged when [canAdd] says no or [source] doesn't suit the type.
* Its id is none of [reserved] either.
*/
fun List<Block>.withBlock(type: BlockType, source: BlockSource? = null): List<Block> {
fun List<Block>.withBlock(type: BlockType, source: BlockSource? = null, reserved: Set<Long> = emptySet()): List<Block> {
if (!canAdd(type) || (source != null) != type.takesSource) return this
val block = Block(nextBlockId(), type, source)
val block = Block(nextBlockId(reserved), type, source)
val taskList = indexOfFirst { it.type == BlockType.TASK_LIST }
return if (taskList < 0) this + block else toMutableList().apply { add(taskList, block) }
}
@@ -33,11 +35,13 @@ fun List<Block>.without(id: Long): List<Block> = filterNot { it.id == id }
/**
* [block] put back at [index], e.g. undoing its removal; a task list still goes
* last. Unchanged when a block with its id is here already.
* last. Unchanged when it is here already, or is a task list and one is; given a
* new id when another block took its own meanwhile.
*/
fun List<Block>.restored(block: Block, index: Int): List<Block> {
if (any { it.id == block.id }) return this
return toMutableList().apply { add(index.coerceIn(0, size), block) }.normalized()
if (any { it == block } || !canAdd(block.type)) return this
val back = if (any { it.id == block.id }) block.copy(id = nextBlockId()) else block
return toMutableList().apply { add(index.coerceIn(0, size), back) }.normalized()
}
/** These blocks in the order of [ids]; blocks [ids] leaves out keep their place after them. A task list stays last. */