vimwiki-server 0.1.0

Daemon that supports parsing and modifying vimwiki files.
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
use crate::data::{
    Element, ElementQuery, FromVimwikiElement, GqlPageFilter,
    GraphqlDatabaseError, InlineElement, InlineElementQuery, Page, PageQuery,
    Region,
};
use entity::*;
use entity_async_graphql::*;
use serde::{Deserialize, Serialize};
use std::{cmp::Ordering, fmt};
use strum::{Display, EnumString};
use vimwiki::{self as v, Located};

/// Represents a single document table
#[gql_ent]
pub struct Table {
    /// The segment of the document this table covers
    #[ent(field(graphql(filter_untyped)))]
    region: Region,

    /// The cells contained in this table
    #[ent(edge(policy = "deep", wrap, graphql(filter_untyped)))]
    cells: Vec<Cell>,

    /// Whether or not the table is centered
    centered: bool,

    /// Page containing this table
    #[ent(edge)]
    page: Page,

    /// Parent element to this table
    #[ent(edge(policy = "shallow", wrap, graphql(filter_untyped)))]
    parent: Option<Element>,
}

impl<'a> FromVimwikiElement<'a> for Table {
    type Element = Located<v::Table<'a>>;

    fn from_vimwiki_element(
        page_id: Id,
        parent_id: Option<Id>,
        element: Self::Element,
    ) -> Result<Self, GraphqlDatabaseError> {
        let region = Region::from(element.region());
        let centered = element.as_inner().centered;

        let mut ent = GraphqlDatabaseError::wrap(
            Self::build()
                .region(region)
                .centered(centered)
                .cells(Vec::new())
                .page(page_id)
                .parent(parent_id)
                .finish_and_commit(),
        )?;

        let mut cells = Vec::new();
        for (pos, cell) in element.into_inner().into_cells().zip_with_position()
        {
            cells.push(
                Cell::from_vimwiki_element_at_pos(
                    page_id,
                    Some(ent.id()),
                    pos,
                    cell,
                )?
                .id(),
            );
        }

        ent.set_cells_ids(cells);
        ent.commit().map_err(GraphqlDatabaseError::Database)?;

        Ok(ent)
    }
}

/// Represents a cell within a table
#[gql_ent]
#[derive(Debug)]
pub enum Cell {
    Content(ContentCell),
    Span(SpanCell),
    Align(AlignCell),
}

impl Cell {
    pub fn region(&self) -> Region {
        match self {
            Self::Content(x) => *x.region(),
            Self::Span(x) => *x.region(),
            Self::Align(x) => *x.region(),
        }
    }

    pub fn position(&self) -> CellPos {
        match self {
            Self::Content(x) => *x.position(),
            Self::Span(x) => *x.position(),
            Self::Align(x) => *x.position(),
        }
    }

    pub fn page_id(&self) -> Id {
        match self {
            Self::Content(x) => x.page_id(),
            Self::Span(x) => x.page_id(),
            Self::Align(x) => x.page_id(),
        }
    }

    pub fn parent_id(&self) -> Option<Id> {
        match self {
            Self::Content(x) => x.parent_id(),
            Self::Span(x) => x.parent_id(),
            Self::Align(x) => x.parent_id(),
        }
    }
}

impl Cell {
    fn from_vimwiki_element_at_pos(
        page_id: Id,
        parent_id: Option<Id>,
        pos: v::CellPos,
        le: Located<v::Cell>,
    ) -> Result<Self, GraphqlDatabaseError> {
        let region = Region::from(le.region());
        Ok(match le.into_inner() {
            v::Cell::Content(x) => {
                let mut ent = GraphqlDatabaseError::wrap(
                    ContentCell::build()
                        .region(region)
                        .position(CellPos::from(pos))
                        .contents(Vec::new())
                        .page(page_id)
                        .parent(parent_id)
                        .finish_and_commit(),
                )?;

                let mut contents = Vec::new();
                for content in x {
                    contents.push(
                        InlineElement::from_vimwiki_element(
                            page_id,
                            Some(ent.id()),
                            content,
                        )?
                        .id(),
                    );
                }

                ent.set_contents_ids(contents);
                ent.commit().map_err(GraphqlDatabaseError::Database)?;
                Self::from(ent)
            }
            v::Cell::Span(x) => Self::from(GraphqlDatabaseError::wrap(
                SpanCell::build()
                    .region(region)
                    .position(CellPos::from(pos))
                    .span(CellSpan::from(x))
                    .page(page_id)
                    .parent(parent_id)
                    .finish_and_commit(),
            )?),
            v::Cell::Align(x) => Self::from(GraphqlDatabaseError::wrap(
                AlignCell::build()
                    .region(region)
                    .position(CellPos::from(pos))
                    .alignment(ColumnAlign::from(x))
                    .page(page_id)
                    .parent(parent_id)
                    .finish_and_commit(),
            )?),
        })
    }
}

/// Represents a cell with content
#[gql_ent]
pub struct ContentCell {
    /// The segment of the document this cell covers
    #[ent(field(graphql(filter_untyped)))]
    region: Region,

    /// The position of this cell in a table
    #[ent(field(graphql(filter_untyped)))]
    position: CellPos,

    /// Contents within the cell
    #[ent(edge(policy = "deep", wrap, graphql(filter_untyped)))]
    contents: Vec<InlineElement>,

    /// The content within the cell as it would be read by humans
    /// without frills
    #[ent(field(computed = "self.to_string()"))]
    text: String,

    /// Page containing this cell
    #[ent(edge)]
    page: Page,

    /// Parent element to this cell
    #[ent(edge(policy = "shallow", wrap, graphql(filter_untyped)))]
    parent: Option<Element>,
}

impl fmt::Display for ContentCell {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.load_contents() {
            Ok(contents) => {
                for content in contents {
                    write!(f, "{}", content.to_string())?;
                }
                Ok(())
            }
            Err(x) => {
                write!(f, "{}", x)?;
                Ok(())
            }
        }
    }
}

/// Represents a cell with no content that spans from another cell
#[gql_ent]
pub struct SpanCell {
    /// The segment of the document this cell covers
    #[ent(field(graphql(filter_untyped)))]
    region: Region,

    /// The position of this cell in a table
    #[ent(field(graphql(filter_untyped)))]
    position: CellPos,

    /// The span direction
    #[ent(field(graphql(filter_untyped)))]
    span: CellSpan,

    /// Page containing this cell
    #[ent(edge)]
    page: Page,

    /// Parent element to this cell
    #[ent(edge(policy = "shallow", wrap, graphql(filter_untyped)))]
    parent: Option<Element>,
}

/// Represents a cell with no content that describes future column alignment
#[gql_ent]
pub struct AlignCell {
    /// The segment of the document this cell covers
    #[ent(field(graphql(filter_untyped)))]
    region: Region,

    /// The position of this cell in a table
    #[ent(field(graphql(filter_untyped)))]
    position: CellPos,

    /// The alignment direction
    #[ent(field(graphql(filter_untyped)))]
    alignment: ColumnAlign,

    /// Page containing this cell
    #[ent(edge)]
    page: Page,

    /// Parent element to this cell
    #[ent(edge(policy = "shallow", wrap, graphql(filter_untyped)))]
    parent: Option<Element>,
}

#[derive(
    Copy,
    Clone,
    Debug,
    Eq,
    PartialEq,
    derive_more::Display,
    Serialize,
    Deserialize,
    ValueLike,
)]
#[display(fmt = "({},{})", row, col)]
pub struct CellPos {
    row: usize,
    col: usize,
}

impl PartialOrd for CellPos {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for CellPos {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self.row.cmp(&other.row), self.col.cmp(&other.col)) {
            (Ordering::Equal, x) => x,
            (x, _) => x,
        }
    }
}

impl From<v::CellPos> for CellPos {
    fn from(pos: v::CellPos) -> Self {
        Self {
            row: pos.row,
            col: pos.col,
        }
    }
}

async_graphql::scalar!(CellPos);

#[derive(
    async_graphql::Enum,
    Copy,
    Clone,
    Debug,
    Eq,
    PartialEq,
    Display,
    EnumString,
    Serialize,
    Deserialize,
)]
#[graphql(remote = "vimwiki::ColumnAlign")]
#[strum(serialize_all = "snake_case")]
pub enum ColumnAlign {
    /// Align columns left
    Left,

    /// Align columns centered
    Center,

    /// Align columns right
    Right,
}

impl ValueLike for ColumnAlign {
    fn into_value(self) -> Value {
        Value::from(self.to_string())
    }

    fn try_from_value(value: Value) -> Result<Self, Value> {
        match value {
            Value::Text(x) => x.as_str().parse().map_err(|_| Value::Text(x)),
            x => Err(x),
        }
    }
}

#[derive(
    async_graphql::Enum,
    Copy,
    Clone,
    Debug,
    Eq,
    PartialEq,
    Display,
    EnumString,
    Serialize,
    Deserialize,
)]
#[graphql(remote = "vimwiki::CellSpan")]
#[strum(serialize_all = "snake_case")]
pub enum CellSpan {
    /// Spanning from left cell
    FromLeft,

    /// Spanning from above cell
    FromAbove,
}

impl ValueLike for CellSpan {
    fn into_value(self) -> Value {
        Value::from(self.to_string())
    }

    fn try_from_value(value: Value) -> Result<Self, Value> {
        match value {
            Value::Text(x) => x.as_str().parse().map_err(|_| Value::Text(x)),
            x => Err(x),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use entity_inmemory::InmemoryDatabase;
    use vimwiki::macros::*;

    #[test]
    fn should_fully_populate_from_vimwiki_element() {
        global::with_db(InmemoryDatabase::default(), || {
            let element = vimwiki_table! {r#"
                |value1|value2|value3|value4|
                |------|:-----|-----:|:----:|
                |abc   |>     |\/    |def   |
            "#};
            let region = Region::from(element.region());
            let ent = Table::from_vimwiki_element(999, Some(123), element)
                .expect("Failed to convert from element");

            assert_eq!(ent.region(), &region);
            assert_eq!(ent.centered(), &false);
            assert_eq!(ent.page_id(), 999);
            assert_eq!(ent.parent_id(), Some(123));

            // NOTE: We sort our cells to make it easier to test
            let mut cells = ent.load_cells().expect("Failed to load cells");
            cells.sort_unstable_by_key(|cell| cell.position());

            for (i, cell) in cells.into_iter().enumerate() {
                assert_eq!(cell.page_id(), 999);
                assert_eq!(cell.parent_id(), Some(ent.id()));

                match (i, cell) {
                    (0, Cell::Content(cell)) => {
                        assert_eq!(cell.to_string(), "value1")
                    }
                    (1, Cell::Content(cell)) => {
                        assert_eq!(cell.to_string(), "value2")
                    }
                    (2, Cell::Content(cell)) => {
                        assert_eq!(cell.to_string(), "value3")
                    }
                    (3, Cell::Content(cell)) => {
                        assert_eq!(cell.to_string(), "value4")
                    }
                    (4, Cell::Align(cell)) => {
                        assert_eq!(cell.alignment, ColumnAlign::Left);
                    }
                    (5, Cell::Align(cell)) => {
                        assert_eq!(cell.alignment, ColumnAlign::Left);
                    }
                    (6, Cell::Align(cell)) => {
                        assert_eq!(cell.alignment, ColumnAlign::Right);
                    }
                    (7, Cell::Align(cell)) => {
                        assert_eq!(cell.alignment, ColumnAlign::Center);
                    }
                    (8, Cell::Content(cell)) => {
                        assert_eq!(cell.to_string(), "abc");
                    }
                    (9, Cell::Span(cell)) => {
                        assert_eq!(cell.span, CellSpan::FromLeft);
                    }
                    (10, Cell::Span(cell)) => {
                        assert_eq!(cell.span, CellSpan::FromAbove);
                    }
                    (11, Cell::Content(cell)) => {
                        assert_eq!(cell.to_string(), "def");
                    }
                    (idx, cell) => {
                        panic!("Unexpected cell at {}: {:?}", idx, cell);
                    }
                }
            }
        });
    }
}