logisheets_controller 1.9.0

the core of LogiSheets
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use logisheets_base::{BlockCellId, BlockFieldId, BlockId, ColId, RowId};

use crate::navigator::BlockPlace;

/// Position of a single block-cell within a schema. Used by the dependency
/// graph to know which virtual node to dirty when a cell value changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockCellRole {
    /// The cell holds a key value. Editing it must dirty the block's key
    /// virtual node (any BlockRef that filters by key value can be affected).
    Key,
    /// The cell holds a value for a specific field, identified by `field_id`.
    Field(BlockFieldId),
    /// The cell does not participate in the schema (e.g., outside the
    /// described columns/rows). No virtual-node update needed.
    None,
}

pub type RowSchema = FormSchema<ColId, RowId, true>;
pub type ColSchema = FormSchema<RowId, ColId, false>;
pub type RenderId = String;

/// Per-field schema entry. Stores everything the schema knows about a
/// single field: its axis id, its render id, and three optional formula
/// templates that materialize per-row at insert / bind time.
///
/// All three templates use the same placeholder substitution rules:
///   `#FIELD("name")` → reference to the same row's cell at field `name`
///   `#KEY`           → this row's key column value, quoted as a literal
///   `#PLACEHOLDER`   → reference to the cell itself (validation /
///                      editability only — value_formula doesn't use it)
///
/// Template wiring:
///   - `value_formula`        → written as the cell's main formula
///   - `validation_formula`   → installed as a `ShadowKind::Validation`
///                              shadow on the cell (advisory red marker)
///   - `editability_formula`  → installed as a `ShadowKind::UserEditable`
///                              shadow on the cell (host edit gate)
#[derive(Debug, Clone)]
pub struct FieldEntry<F> {
    pub field_axis_id: F,
    pub render_id: RenderId,
    pub value_formula: Option<String>,
    pub validation_formula: Option<String>,
    pub editability_formula: Option<String>,
}

impl<F> FieldEntry<F> {
    pub fn new(field_axis_id: F, render_id: RenderId) -> Self {
        Self {
            field_axis_id,
            render_id,
            value_formula: None,
            validation_formula: None,
            editability_formula: None,
        }
    }

    pub fn with_value_formula(mut self, f: Option<String>) -> Self {
        self.value_formula = f;
        self
    }

    pub fn with_validation_formula(mut self, f: Option<String>) -> Self {
        self.validation_formula = f;
        self
    }

    pub fn with_editability_formula(mut self, f: Option<String>) -> Self {
        self.editability_formula = f;
        self
    }
}

#[derive(Debug, Clone)]
pub struct FormSchema<F, K, const IS_ROW: bool> {
    /// Per-field entries; index alignment matches the original
    /// `BindFormSchema.fields` order.
    pub fields: Vec<(Field, FieldEntry<F>)>,
    pub name: String,
    pub key: K,
}

impl<F: Copy + PartialEq, K, const IS_ROW: bool> FormSchema<F, K, IS_ROW> {
    /// Lookup the value-formula template for the field whose field-axis id
    /// is `id`. Returns `None` if the field doesn't exist or has no
    /// template (free-form column).
    pub fn formula_for_field_axis(&self, id: F) -> Option<&str> {
        self.fields
            .iter()
            .find(|(_, e)| e.field_axis_id == id)
            .and_then(|(_, e)| e.value_formula.as_deref())
    }

    /// Lookup the validation-formula template for the field whose
    /// field-axis id is `id`. Returns `None` for fields with no rule.
    pub fn validation_for_field_axis(&self, id: F) -> Option<&str> {
        self.fields
            .iter()
            .find(|(_, e)| e.field_axis_id == id)
            .and_then(|(_, e)| e.validation_formula.as_deref())
    }

    /// Lookup the editability-formula template for the field whose
    /// field-axis id is `id`. Returns `None` for fields with no rule.
    pub fn editability_for_field_axis(&self, id: F) -> Option<&str> {
        self.fields
            .iter()
            .find(|(_, e)| e.field_axis_id == id)
            .and_then(|(_, e)| e.editability_formula.as_deref())
    }

    /// Resolve a `#FIELD("name")` reference back to the field-axis id
    /// of the referenced sibling field. Returns `None` if the name
    /// isn't a field in this schema.
    pub fn field_axis_by_name(&self, name: &str) -> Option<F> {
        self.fields
            .iter()
            .find(|(n, _)| n == name)
            .map(|(_, e)| e.field_axis_id)
    }
}

pub type Field = String;
pub type Key = String;

#[derive(Debug, Clone)]
pub struct RandomSchema {
    pub key_field: Vec<(Key, RowId, ColId, RenderId)>,
    pub name: String,
}

#[derive(Debug, Clone)]
pub enum Schema {
    RowSchema(RowSchema),
    ColSchema(ColSchema),
    RandomSchema(RandomSchema),
}

impl SchemaTrait for Schema {
    fn get_render_id(&self, row: RowId, col: ColId) -> Option<RenderId> {
        match self {
            Schema::RowSchema(schema) => schema.get_render_id(row, col),
            Schema::ColSchema(schema) => schema.get_render_id(row, col),
            Schema::RandomSchema(schema) => schema.get_render_id(row, col),
        }
    }

    fn get_ref_name(&self) -> String {
        match self {
            Schema::RowSchema(schema) => schema.get_ref_name(),
            Schema::ColSchema(schema) => schema.get_ref_name(),
            Schema::RandomSchema(schema) => schema.get_ref_name(),
        }
    }

    fn get_all_fields(&self) -> Vec<Field> {
        match self {
            Schema::RowSchema(schema) => schema.get_all_fields(),
            Schema::ColSchema(schema) => schema.get_all_fields(),
            Schema::RandomSchema(schema) => schema.get_all_fields(),
        }
    }

    fn get_all_field_ids(&self) -> Vec<(Field, BlockFieldId)> {
        match self {
            Schema::RowSchema(schema) => schema.get_all_field_ids(),
            Schema::ColSchema(schema) => schema.get_all_field_ids(),
            Schema::RandomSchema(schema) => schema.get_all_field_ids(),
        }
    }

    fn resolve_field_id(&self, field: &str) -> Option<BlockFieldId> {
        match self {
            Schema::RowSchema(schema) => schema.resolve_field_id(field),
            Schema::ColSchema(schema) => schema.resolve_field_id(field),
            Schema::RandomSchema(schema) => schema.resolve_field_id(field),
        }
    }

    fn fetch_field_name(&self, field_id: BlockFieldId) -> Option<String> {
        match self {
            Schema::RowSchema(schema) => schema.fetch_field_name(field_id),
            Schema::ColSchema(schema) => schema.fetch_field_name(field_id),
            Schema::RandomSchema(schema) => schema.fetch_field_name(field_id),
        }
    }

    fn get_all_key_cell_ids(&self, block_id: BlockId, bp: &BlockPlace) -> Vec<BlockCellId> {
        match self {
            Schema::RowSchema(form_schema) => form_schema.get_all_key_cell_ids(block_id, bp),
            Schema::ColSchema(form_schema) => form_schema.get_all_key_cell_ids(block_id, bp),
            Schema::RandomSchema(random_schema) => random_schema.get_all_key_cell_ids(block_id, bp),
        }
    }

    fn partially_resolve(&self, key: BlockCellId, field: &String) -> Option<BlockCellId> {
        match self {
            Schema::RowSchema(form_schema) => form_schema.partially_resolve(key, field),
            Schema::ColSchema(form_schema) => form_schema.partially_resolve(key, field),
            Schema::RandomSchema(random_schema) => random_schema.partially_resolve(key, field),
        }
    }

    fn partially_resolve_by_field_id(
        &self,
        key: BlockCellId,
        field_id: BlockFieldId,
    ) -> Option<BlockCellId> {
        match self {
            Schema::RowSchema(form_schema) => {
                form_schema.partially_resolve_by_field_id(key, field_id)
            }
            Schema::ColSchema(form_schema) => {
                form_schema.partially_resolve_by_field_id(key, field_id)
            }
            Schema::RandomSchema(random_schema) => {
                random_schema.partially_resolve_by_field_id(key, field_id)
            }
        }
    }

    fn cell_role(&self, cell: &BlockCellId) -> BlockCellRole {
        match self {
            Schema::RowSchema(s) => s.cell_role(cell),
            Schema::ColSchema(s) => s.cell_role(cell),
            Schema::RandomSchema(s) => s.cell_role(cell),
        }
    }
}

pub trait SchemaTrait {
    fn get_render_id(&self, row: RowId, col: ColId) -> Option<RenderId>;
    fn get_ref_name(&self) -> String;
    fn get_all_fields(&self) -> Vec<Field>;
    fn get_all_field_ids(&self) -> Vec<(Field, BlockFieldId)>;
    fn resolve_field_id(&self, field: &str) -> Option<BlockFieldId>;
    fn fetch_field_name(&self, field_id: BlockFieldId) -> Option<String>;
    fn get_all_key_cell_ids(&self, block_id: BlockId, bp: &BlockPlace) -> Vec<BlockCellId>;
    fn partially_resolve(&self, key: BlockCellId, field: &String) -> Option<BlockCellId>;
    fn partially_resolve_by_field_id(
        &self,
        key: BlockCellId,
        field_id: BlockFieldId,
    ) -> Option<BlockCellId>;
    fn cell_role(&self, cell: &BlockCellId) -> BlockCellRole;
}

impl SchemaTrait for RowSchema {
    fn get_render_id(&self, _row: RowId, col: ColId) -> Option<RenderId> {
        self.fields
            .iter()
            .find(|(_, e)| e.field_axis_id == col)
            .map(|(_, e)| e.render_id.clone())
    }

    fn get_ref_name(&self) -> String {
        self.name.clone()
    }

    fn get_all_fields(&self) -> Vec<Field> {
        self.fields.iter().map(|(f, _)| f.clone()).collect()
    }

    fn get_all_field_ids(&self) -> Vec<(Field, BlockFieldId)> {
        self.fields
            .iter()
            .map(|(name, e)| (name.clone(), e.field_axis_id as BlockFieldId))
            .collect()
    }

    fn resolve_field_id(&self, field: &str) -> Option<BlockFieldId> {
        self.fields
            .iter()
            .find(|(name, _)| name == field)
            .map(|(_, e)| e.field_axis_id as BlockFieldId)
    }

    fn fetch_field_name(&self, field_id: BlockFieldId) -> Option<String> {
        self.fields
            .iter()
            .find(|(_, e)| e.field_axis_id as BlockFieldId == field_id)
            .map(|(name, _)| name.clone())
    }

    fn get_all_key_cell_ids(&self, block_id: BlockId, bp: &BlockPlace) -> Vec<BlockCellId> {
        let key = self.key;
        bp.rows
            .iter()
            .map(|r| BlockCellId {
                block_id,
                row: *r,
                col: key,
            })
            .collect()
    }

    fn partially_resolve(&self, key: BlockCellId, field: &String) -> Option<BlockCellId> {
        let row = key.row;
        let col = self
            .fields
            .iter()
            .find(|(f, _)| f == field)
            .map(|(_, e)| e.field_axis_id);
        col.map(|col| BlockCellId {
            row,
            col,
            block_id: key.block_id,
        })
    }

    fn partially_resolve_by_field_id(
        &self,
        key: BlockCellId,
        field_id: BlockFieldId,
    ) -> Option<BlockCellId> {
        // For RowSchema, fields run along columns and the field id is the
        // ColId. Verify the id is actually one of this schema's fields before
        // returning, so callers don't synthesize cells from arbitrary ids.
        if self
            .fields
            .iter()
            .any(|(_, e)| e.field_axis_id as BlockFieldId == field_id)
        {
            Some(BlockCellId {
                block_id: key.block_id,
                row: key.row,
                col: field_id as ColId,
            })
        } else {
            None
        }
    }

    fn cell_role(&self, cell: &BlockCellId) -> BlockCellRole {
        if cell.col == self.key {
            BlockCellRole::Key
        } else if self.fields.iter().any(|(_, e)| e.field_axis_id == cell.col) {
            BlockCellRole::Field(cell.col as BlockFieldId)
        } else {
            BlockCellRole::None
        }
    }
}

impl SchemaTrait for ColSchema {
    fn get_render_id(&self, row: RowId, _col: ColId) -> Option<RenderId> {
        self.fields
            .iter()
            .find(|(_, e)| e.field_axis_id == row)
            .map(|(_, e)| e.render_id.clone())
    }

    fn get_ref_name(&self) -> String {
        self.name.clone()
    }

    fn get_all_fields(&self) -> Vec<Field> {
        self.fields.iter().map(|(f, _)| f.clone()).collect()
    }

    fn get_all_field_ids(&self) -> Vec<(Field, BlockFieldId)> {
        self.fields
            .iter()
            .map(|(name, e)| (name.clone(), e.field_axis_id as BlockFieldId))
            .collect()
    }

    fn resolve_field_id(&self, field: &str) -> Option<BlockFieldId> {
        self.fields
            .iter()
            .find(|(name, _)| name == field)
            .map(|(_, e)| e.field_axis_id as BlockFieldId)
    }

    fn fetch_field_name(&self, field_id: BlockFieldId) -> Option<String> {
        self.fields
            .iter()
            .find(|(_, e)| e.field_axis_id as BlockFieldId == field_id)
            .map(|(name, _)| name.clone())
    }

    fn get_all_key_cell_ids(&self, block_id: BlockId, bp: &BlockPlace) -> Vec<BlockCellId> {
        let key = self.key;
        bp.cols
            .iter()
            .map(|c| BlockCellId {
                block_id,
                row: key,
                col: *c,
            })
            .collect()
    }

    fn partially_resolve(&self, key: BlockCellId, field: &String) -> Option<BlockCellId> {
        self.fields
            .iter()
            .find(|(f, _)| f == field)
            .map(|(_, e)| BlockCellId {
                block_id: key.block_id,
                row: e.field_axis_id,
                col: key.col,
            })
    }

    fn partially_resolve_by_field_id(
        &self,
        key: BlockCellId,
        field_id: BlockFieldId,
    ) -> Option<BlockCellId> {
        if self
            .fields
            .iter()
            .any(|(_, e)| e.field_axis_id as BlockFieldId == field_id)
        {
            Some(BlockCellId {
                block_id: key.block_id,
                row: field_id as RowId,
                col: key.col,
            })
        } else {
            None
        }
    }

    fn cell_role(&self, cell: &BlockCellId) -> BlockCellRole {
        if cell.row == self.key {
            BlockCellRole::Key
        } else if self.fields.iter().any(|(_, e)| e.field_axis_id == cell.row) {
            BlockCellRole::Field(cell.row as BlockFieldId)
        } else {
            BlockCellRole::None
        }
    }
}

impl SchemaTrait for RandomSchema {
    fn get_render_id(&self, row: RowId, col: ColId) -> Option<RenderId> {
        self.key_field
            .iter()
            .find(|(_, r, c, _)| r == &row && c == &col)
            .map(|(_, _, _, id)| id.clone())
    }

    fn get_ref_name(&self) -> String {
        self.name.clone()
    }

    fn get_all_fields(&self) -> Vec<Field> {
        self.key_field
            .iter()
            .map(|(f, _, _, _)| f.clone())
            .collect()
    }

    // RandomSchema has no separate field axis — every entry is a (key, value)
    // pair. The id-keyed dependency vertex is intentionally coarse: any cell
    // change inside a RandomSchema block goes through `BlockAll`, so these id
    // helpers stay no-ops.
    fn get_all_field_ids(&self) -> Vec<(Field, BlockFieldId)> {
        Vec::new()
    }

    fn resolve_field_id(&self, _field: &str) -> Option<BlockFieldId> {
        None
    }

    fn fetch_field_name(&self, _field_id: BlockFieldId) -> Option<String> {
        None
    }

    fn get_all_key_cell_ids(&self, block_id: BlockId, _bp: &BlockPlace) -> Vec<BlockCellId> {
        self.key_field
            .iter()
            .map(|(_, r, c, _)| BlockCellId {
                block_id,
                row: *r,
                col: *c,
            })
            .collect()
    }

    fn partially_resolve(&self, key: BlockCellId, _field: &String) -> Option<BlockCellId> {
        Some(key)
    }

    fn partially_resolve_by_field_id(
        &self,
        key: BlockCellId,
        _field_id: BlockFieldId,
    ) -> Option<BlockCellId> {
        Some(key)
    }

    fn cell_role(&self, _cell: &BlockCellId) -> BlockCellRole {
        // Conservative: never claim a cell is a Key/Field for random schemas
        // because dirty propagation falls back to BlockAll for them.
        BlockCellRole::None
    }
}