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
use crate::formatting::RichText;
#[cfg(feature = "fp-bindgen")]
use fp_bindgen::prelude::Serializable;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use thiserror::Error;
use typed_builder::TypedBuilder;

const MIN_LENGTH: usize = 4;

/// Cell used for displaying tables in a notebook.
///
/// Tables have columns, which are tracked using [TableColumnDefinition]. The
/// column definition may specify a specific schema to be used for all values
/// in that column.
///
/// Tables also have [rows](TableRow), which are used for tracking all the data
/// in the table. Each row has multiple "row values" (we intentionally avoid the
/// term "cell" here, because it would be too confusing with the table cell
/// itself).
///
/// Row values have a specific data type, which should correspond to the type
/// specified in the [TableColumnDefinition].
///
/// Every row and every column inside a table has a unique ID. Those IDs can be
/// combined to create a [TableRowValueId]. [TableRowValueId] can be serialized
/// to be used inside the `field` of
/// [some operations](crate::notebooks::operations::ReplaceTextOperation::field)
/// as well as [focus types](crate::realtime::FocusPosition::field).
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::notebooks")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct TableCell {
    #[builder(setter(into))]
    pub id: String,

    #[builder(default, setter(strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub read_only: Option<bool>,

    /// Describes the types used for the columns and the order they should be
    /// rendered in.
    #[builder(default, setter(into))]
    pub column_defs: Vec<TableColumnDefinition>,

    /// Holds the table rows and their values.
    #[builder(default, setter(into))]
    pub rows: Vec<TableRow>,
}

impl TableCell {
    /// Returns a reference to a column definition by [TableColumnId].
    pub fn column_def(&self, id: &TableColumnId) -> Option<&TableColumnDefinition> {
        self.column_defs.iter().find(|def| &def.id == id)
    }

    /// Returns a reference to a row by [TableRowId].
    pub fn row(&self, id: &TableRowId) -> Option<&TableRow> {
        self.rows.iter().find(|row| &row.id == id)
    }

    /// Returns a reference to a row value.
    pub fn row_value(&self, id: &TableRowValueId) -> Option<&TableRowValue> {
        let row = self.row(id.row_id());
        let value_index = self
            .column_defs
            .iter()
            .position(|def| &def.id == id.column_id());
        match (row, value_index) {
            (Some(row), Some(value_index)) => row.values.get(value_index),
            _ => None,
        }
    }

    /// Returns the table cell with an updated row value for the given field.
    pub fn with_row_value(&self, field: &str, mut updated_value: TableRowValue) -> Self {
        let Ok(id) = TableRowValueId::from_str(field) else {
            return self.clone();
        };

        let Some(column_index) = self
            .column_defs
            .iter()
            .position(|column_def| &column_def.id == id.column_id())
        else {
            return self.clone();
        };

        let rows = self
            .rows
            .iter()
            .map(|row| match &row.id == id.row_id() {
                true => TableRow {
                    id: row.id.clone(),
                    values: row
                        .values
                        .iter()
                        .enumerate()
                        .map(|(i, value)| match i == column_index {
                            // We use `mem::replace()` to avoid cloning, because
                            // the borrow checker thinks we might move from
                            // `updated_value` multiple times, even though we
                            // know it'll happen only once since `field`
                            // identifies a unique table row value.
                            true => std::mem::replace(
                                &mut updated_value,
                                TableRowValue::Text(RichText::default()),
                            ),
                            false => value.clone(),
                        })
                        .collect(),
                },
                false => row.clone(),
            })
            .collect();

        Self {
            id: self.id.clone(),
            column_defs: self.column_defs.clone(),
            read_only: self.read_only,
            rows,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::notebooks")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct TableColumnDefinition {
    /// ID of the column.
    pub id: TableColumnId,

    /// Heading text to be displayed at the top of the column.
    #[builder(setter(into))]
    pub title: String,
}

/// This is an automatically generated ID that is added to every column in a
/// table cell.
///
/// Table column IDs are used to refer to column definitions in the table.
/// They can also be combined with a [TableRowId] to create a [TableRowItemId].
///
/// Column IDs may only contain alphanumeric characters and must be unique
/// within a table.
#[derive(Debug, Clone, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::notebooks")
)]
pub struct TableColumnId(String);

impl std::fmt::Display for TableColumnId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for TableColumnId {
    type Err = InvalidTableId;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        validate_id(s).map(|_| Self(s.to_owned()))
    }
}

#[derive(Debug, Clone, Deserialize, Eq, PartialEq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::notebooks")
)]
#[non_exhaustive]
pub struct TableRow {
    /// ID of the row.
    pub id: TableRowId,

    /// The values inside this row.
    ///
    /// The types, order, and amount of the values should match the table's
    /// [column definitions](TableCell::column_defs).
    #[builder(setter(into))]
    pub values: Vec<TableRowValue>,
}

/// This is an automatically generated ID that is added to every row in a table
/// cell.
///
/// Table row IDs are used to refer to rows in the table. They can also be
/// combined with a [TableColumnId] to create a [TableRowValueId].
///
/// Row IDs may only contain alphanumeric characters and must be unique within a
/// table.
#[derive(Debug, Clone, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::notebooks")
)]
pub struct TableRowId(String);

impl std::fmt::Display for TableRowId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for TableRowId {
    type Err = InvalidTableId;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        validate_id(s).map(|_| Self(s.to_owned()))
    }
}

/// One of the values stored in a [TableRow].
///
/// We intentionally avoid the term "cell" here, because it would be too
/// confusing with the table cell itself.
///
/// Row values can be looked up by [ID](TableRowValueId), although the ID is not
/// stored in the row value itself. Instead, it can be created from the row ID
/// and column ID.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::notebooks")
)]
#[non_exhaustive]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TableRowValue {
    Text(RichText),
}

/// This is a compound ID based on the row ID and column ID that together
/// identify a row value.
///
/// Table row value IDs are used to refer to [row values](TableRowValue). They
/// are not stored in the [TableCell] data structure, but are used in serialized
/// form to refer to row values inside the `field` of
/// [some operations](crate::notebooks::operations::ReplaceTextOperation::field)
/// as well as [focus types](crate::realtime::FocusPosition::field).
#[derive(Debug, Clone, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::notebooks")
)]
pub struct TableRowValueId(TableRowId, TableColumnId);

impl TableRowValueId {
    /// Creates a new value ID from a [TableRowId] and [TableColumnId].
    pub fn new(row_id: TableRowId, column_id: TableColumnId) -> Self {
        Self(row_id, column_id)
    }

    pub fn row_id(&self) -> &TableRowId {
        &self.0
    }

    pub fn column_id(&self) -> &TableColumnId {
        &self.1
    }
}

impl std::fmt::Display for TableRowValueId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{};{}", self.0, self.1)
    }
}

impl FromStr for TableRowValueId {
    type Err = InvalidTableId;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.split_once(';') {
            Some((before, after)) => Ok(Self::new(
                TableRowId::from_str(before)?,
                TableColumnId::from_str(after)?,
            )),
            None => Err(InvalidTableId::MissingSeparator),
        }
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::notebooks")
)]
#[non_exhaustive]
pub enum InvalidTableId {
    #[error("table IDs must be at least 6 characters in length")]
    TooShort,
    #[error("table IDs may only contain alpha-numeric characters")]
    InvalidCharacters,
    #[error("row ID and column ID must be separated by a semicolon")]
    MissingSeparator,
}

fn validate_id(id: &str) -> Result<(), InvalidTableId> {
    if id.len() < MIN_LENGTH {
        return Err(InvalidTableId::TooShort);
    }

    if id.chars().any(|c| !c.is_ascii_alphanumeric()) {
        return Err(InvalidTableId::InvalidCharacters);
    }

    Ok(())
}