Line data Source code
1 : import type { ContentStore } from '#/content'
2 : import type { Document } from '#/document'
3 : import { Dirty } from '#/history'
4 : import type { Command, Direction } from '#/history'
5 : import type { ChannelData } from '#/node'
6 :
7 : export interface SelectionSnapshot {
8 : channel: ChannelData | null
9 : selectionId: string | undefined
10 : }
11 :
12 0 : export function snapshotSelection(doc: Document): SelectionSnapshot {
13 0 : const channel = doc.channels.find((ch) => ch.role === 'selection') ?? null
14 0 : return {
15 : channel: channel
16 : ? {
17 : ...channel,
18 : bounds: channel.bounds ? { ...channel.bounds } : undefined
19 : }
20 : : null,
21 : selectionId: channel ? channel.id : undefined
22 : }
23 : }
24 :
25 0 : function applySelectionSnapshot(doc: Document, s: SelectionSnapshot): void {
26 0 : doc.channels = doc.channels.filter((ch) => ch.role !== 'selection')
27 0 : if (s.channel) doc.channels.push({ ...s.channel })
28 0 : doc.selectionId = s.channel ? s.selectionId : undefined
29 : }
30 :
31 2 : export class SetSelectionCommand implements Command {
32 : readonly dirtyMask = Dirty.SELECTION
33 :
34 : constructor(
35 0 : readonly label: string,
36 0 : private readonly doc: Document,
37 0 : private readonly before: SelectionSnapshot,
38 0 : private readonly after: SelectionSnapshot,
39 0 : private readonly store: ContentStore
40 : ) {}
41 :
42 : apply(dir: Direction): void {
43 0 : applySelectionSnapshot(this.doc, dir === 'undo' ? this.before : this.after)
44 : }
45 :
46 : sizeBytes(): number {
47 0 : let n = 0
48 0 : for (const s of [this.before, this.after]) {
49 0 : const e = s.channel ? this.store.get(s.channel.contentId) : null
50 0 : if (e) n += e.width * e.height * 4
51 : }
52 0 : return n
53 : }
54 :
55 : contentRefs(): string[] {
56 0 : const refs: string[] = []
57 0 : if (this.before.channel) refs.push(this.before.channel.contentId)
58 0 : if (this.after.channel) refs.push(this.after.channel.contentId)
59 0 : return refs
60 : }
61 : }
|