text-document-common 1.4.0

Shared entities, database, events, and undo/redo infrastructure for text-document
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Generated by Qleany v1.5.0 from common_entity_repository.tera

use std::fmt::Display;

use crate::{
    database::transactions::Transaction,
    direct_access::repository_factory,
    entities::InlineElement,
    event::{DirectAccessEntity, EntityEvent, Event, EventBuffer, Origin},
    snapshot::EntityTreeSnapshot,
    types::EntityId,
};

use crate::direct_access::block::BlockRelationshipField;
use crate::error::RepositoryError;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum InlineElementRelationshipField {}

impl Display for InlineElementRelationshipField {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

pub trait InlineElementTable {
    fn create(&mut self, entity: &InlineElement) -> Result<InlineElement, RepositoryError>;
    fn create_multi(
        &mut self,
        entities: &[InlineElement],
    ) -> Result<Vec<InlineElement>, RepositoryError>;
    fn get(&self, id: &EntityId) -> Result<Option<InlineElement>, RepositoryError>;
    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<InlineElement>>, RepositoryError>;
    fn get_all(&self) -> Result<Vec<InlineElement>, RepositoryError>;
    fn update(&mut self, entity: &InlineElement) -> Result<InlineElement, RepositoryError>;
    fn update_multi(
        &mut self,
        entities: &[InlineElement],
    ) -> Result<Vec<InlineElement>, RepositoryError>;
    fn update_with_relationships(
        &mut self,
        entity: &InlineElement,
    ) -> Result<InlineElement, RepositoryError>;
    fn update_with_relationships_multi(
        &mut self,
        entities: &[InlineElement],
    ) -> Result<Vec<InlineElement>, RepositoryError>;
    fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError>;
    fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError>;
}

pub trait InlineElementTableRO {
    fn get(&self, id: &EntityId) -> Result<Option<InlineElement>, RepositoryError>;
    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<InlineElement>>, RepositoryError>;
    fn get_all(&self) -> Result<Vec<InlineElement>, RepositoryError>;
}

pub struct InlineElementRepository<'a> {
    redb_table: Box<dyn InlineElementTable + 'a>,
    transaction: &'a Transaction,
}

impl<'a> InlineElementRepository<'a> {
    pub fn new(redb_table: Box<dyn InlineElementTable + 'a>, transaction: &'a Transaction) -> Self {
        InlineElementRepository {
            redb_table,
            transaction,
        }
    }

    pub fn create_orphan(
        &mut self,
        event_buffer: &mut EventBuffer,
        entity: &InlineElement,
    ) -> Result<InlineElement, RepositoryError> {
        let new = self.redb_table.create(entity)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Created)),
            ids: vec![new.id],
            data: None,
        });
        Ok(new)
    }

    pub fn create_orphan_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        entities: &[InlineElement],
    ) -> Result<Vec<InlineElement>, RepositoryError> {
        let new_entities = self.redb_table.create_multi(entities)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Created)),
            ids: new_entities.iter().map(|e| e.id).collect(),
            data: None,
        });
        Ok(new_entities)
    }
    pub fn create(
        &mut self,
        event_buffer: &mut EventBuffer,
        entity: &InlineElement,
        owner_id: EntityId,
        index: i32,
    ) -> Result<InlineElement, RepositoryError> {
        let new = self.redb_table.create(entity)?;
        let created_id = new.id;

        let mut relationship_ids = self.get_relationships_from_owner(&owner_id)?;
        // Insert at index
        if index >= 0 && (index as usize) < relationship_ids.len() {
            relationship_ids.insert(index as usize, created_id);
        } else {
            relationship_ids.push(created_id);
        }

        self.set_relationships_in_owner(event_buffer, &owner_id, &relationship_ids)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Created)),
            ids: vec![created_id],
            data: None,
        });
        Ok(new)
    }

    pub fn create_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        entities: &[InlineElement],
        owner_id: EntityId,
        index: i32,
    ) -> Result<Vec<InlineElement>, RepositoryError> {
        let new_entities = self.redb_table.create_multi(entities)?;
        let created_ids: Vec<EntityId> = new_entities.iter().map(|e| e.id).collect();

        let mut relationship_ids = self.get_relationships_from_owner(&owner_id)?;
        if index >= 0 && (index as usize) < relationship_ids.len() {
            for (i, id) in created_ids.iter().enumerate() {
                relationship_ids.insert(index as usize + i, *id);
            }
        } else {
            relationship_ids.extend(created_ids.iter());
        }

        self.set_relationships_in_owner(event_buffer, &owner_id, &relationship_ids)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Created)),
            ids: created_ids,
            data: None,
        });
        Ok(new_entities)
    }

    pub fn get(&self, id: &EntityId) -> Result<Option<InlineElement>, RepositoryError> {
        self.redb_table.get(id)
    }
    pub fn get_multi(
        &self,
        ids: &[EntityId],
    ) -> Result<Vec<Option<InlineElement>>, RepositoryError> {
        self.redb_table.get_multi(ids)
    }
    pub fn get_all(&self) -> Result<Vec<InlineElement>, RepositoryError> {
        self.redb_table.get_all()
    }

    pub fn update(
        &mut self,
        event_buffer: &mut EventBuffer,
        entity: &InlineElement,
    ) -> Result<InlineElement, RepositoryError> {
        let updated = self.redb_table.update(entity)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Updated)),
            ids: vec![updated.id],
            data: None,
        });
        Ok(updated)
    }

    pub fn update_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        entities: &[InlineElement],
    ) -> Result<Vec<InlineElement>, RepositoryError> {
        let updated = self.redb_table.update_multi(entities)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Updated)),
            ids: updated.iter().map(|e| e.id).collect(),
            data: None,
        });
        Ok(updated)
    }

    pub fn update_with_relationships(
        &mut self,
        event_buffer: &mut EventBuffer,
        entity: &InlineElement,
    ) -> Result<InlineElement, RepositoryError> {
        let updated = self.redb_table.update_with_relationships(entity)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Updated)),
            ids: vec![updated.id],
            data: None,
        });
        Ok(updated)
    }

    pub fn update_with_relationships_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        entities: &[InlineElement],
    ) -> Result<Vec<InlineElement>, RepositoryError> {
        let updated = self.redb_table.update_with_relationships_multi(entities)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Updated)),
            ids: updated.iter().map(|e| e.id).collect(),
            data: None,
        });
        Ok(updated)
    }

    pub fn remove(
        &mut self,
        event_buffer: &mut EventBuffer,
        id: &EntityId,
    ) -> Result<(), RepositoryError> {
        let _entity = match self.redb_table.get(id)? {
            Some(e) => e,
            None => return Ok(()),
        };
        // get all strong forward relationship fields

        // remove all strong relationships, initiating a cascade remove

        // Before removal, find which owner(s) reference this entity
        let affected_owner_ids: Vec<EntityId> = {
            let owner_repo = repository_factory::write::create_block_repository(self.transaction);
            owner_repo
                .get_relationships_from_right_ids(&BlockRelationshipField::Elements, &[*id])?
                .into_iter()
                .map(|(owner_id, _)| owner_id)
                .collect()
        };
        // Save each owner's current relationship IDs (properly ordered via get_relationships_from_owner)
        let mut owner_rel_before: std::collections::HashMap<EntityId, Vec<EntityId>> =
            std::collections::HashMap::new();
        for owner_id in &affected_owner_ids {
            owner_rel_before.insert(*owner_id, self.get_relationships_from_owner(owner_id)?);
        }

        // remove entity
        self.redb_table.remove(id)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Removed)),
            ids: vec![*id],
            data: None,
        });
        // Update each affected owner's relationship to exclude removed ID (emits Updated event)
        for owner_id in &affected_owner_ids {
            if let Some(rel_ids) = owner_rel_before.get(owner_id) {
                let updated: Vec<EntityId> =
                    rel_ids.iter().copied().filter(|rid| *rid != *id).collect();
                self.set_relationships_in_owner(event_buffer, owner_id, &updated)?;
            }
        }

        Ok(())
    }

    pub fn remove_multi(
        &mut self,
        event_buffer: &mut EventBuffer,
        ids: &[EntityId],
    ) -> Result<(), RepositoryError> {
        let entities = self.redb_table.get_multi(ids)?;
        if entities.is_empty() || entities.iter().all(|e| e.is_none()) {
            return Ok(());
        }

        // get all strong forward relationship fields

        // remove all strong relationships, initiating a cascade remove

        // Before removal, find which owner(s) reference these entities
        let affected_owner_ids: Vec<EntityId> = {
            let owner_repo = repository_factory::write::create_block_repository(self.transaction);
            owner_repo
                .get_relationships_from_right_ids(&BlockRelationshipField::Elements, ids)?
                .into_iter()
                .map(|(owner_id, _)| owner_id)
                .collect()
        };
        // Save each owner's current relationship IDs (properly ordered via get_relationships_from_owner)
        let mut owner_rel_before: std::collections::HashMap<EntityId, Vec<EntityId>> =
            std::collections::HashMap::new();
        for owner_id in &affected_owner_ids {
            owner_rel_before.insert(*owner_id, self.get_relationships_from_owner(owner_id)?);
        }

        self.redb_table.remove_multi(ids)?;
        event_buffer.push(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(EntityEvent::Removed)),
            ids: ids.into(),
            data: None,
        });
        // Update each affected owner's relationship to exclude removed IDs (emits Updated event)
        {
            let removed_set: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
            for owner_id in &affected_owner_ids {
                if let Some(rel_ids) = owner_rel_before.get(owner_id) {
                    let updated: Vec<EntityId> = rel_ids
                        .iter()
                        .copied()
                        .filter(|rid| !removed_set.contains(rid))
                        .collect();
                    self.set_relationships_in_owner(event_buffer, owner_id, &updated)?;
                }
            }
        }

        Ok(())
    }
    pub fn get_relationships_from_owner(
        &self,
        owner_id: &EntityId,
    ) -> Result<Vec<EntityId>, RepositoryError> {
        let repo = repository_factory::write::create_block_repository(self.transaction);
        repo.get_relationship(owner_id, &BlockRelationshipField::Elements)
    }

    pub fn set_relationships_in_owner(
        &mut self,
        event_buffer: &mut EventBuffer,
        owner_id: &EntityId,
        ids: &[EntityId],
    ) -> Result<(), RepositoryError> {
        let mut repo = repository_factory::write::create_block_repository(self.transaction);
        repo.set_relationship(
            event_buffer,
            owner_id,
            &BlockRelationshipField::Elements,
            ids,
        )
    }

    pub fn snapshot(&self, _ids: &[EntityId]) -> Result<EntityTreeSnapshot, RepositoryError> {
        let store_snap = self.transaction.snapshot_store();
        Ok(EntityTreeSnapshot {
            store_snapshot: Some(store_snap),
        })
    }

    pub fn restore(
        &mut self,
        event_buffer: &mut EventBuffer,
        snap: &EntityTreeSnapshot,
    ) -> Result<(), RepositoryError> {
        let store_snap = snap
            .store_snapshot
            .as_ref()
            .ok_or_else(|| RepositoryError::Serialization("missing store snapshot".into()))?;
        self.transaction.restore_store(store_snap);

        let store = self.transaction.get_store();

        // InlineElement: Created only (leaf, no relationships, no children)
        let elem_ids: Vec<_> = store
            .inline_elements
            .read()
            .unwrap()
            .keys()
            .copied()
            .collect();
        if !elem_ids.is_empty() {
            event_buffer.push(Event {
                origin: Origin::DirectAccess(DirectAccessEntity::InlineElement(
                    EntityEvent::Created,
                )),
                ids: elem_ids,
                data: None,
            });
        }

        Ok(())
    }
}

pub struct InlineElementRepositoryRO<'a> {
    redb_table: Box<dyn InlineElementTableRO + 'a>,
}
impl<'a> InlineElementRepositoryRO<'a> {
    pub fn new(redb_table: Box<dyn InlineElementTableRO + 'a>) -> Self {
        InlineElementRepositoryRO { redb_table }
    }
    pub fn get(&self, id: &EntityId) -> Result<Option<InlineElement>, RepositoryError> {
        self.redb_table.get(id)
    }
    pub fn get_multi(
        &self,
        ids: &[EntityId],
    ) -> Result<Vec<Option<InlineElement>>, RepositoryError> {
        self.redb_table.get_multi(ids)
    }
    pub fn get_all(&self) -> Result<Vec<InlineElement>, RepositoryError> {
        self.redb_table.get_all()
    }
}