simian 0.2.0

A command-line tool for exploring and implementing Machine Learning algorithms in Rust.
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
import { nanoid } from 'nanoid'
import { Editor, Element, Node, Point, Range, Transforms } from 'slate'

import { isInsideElement } from '@/ui/editor/utils'
import { elementAddon } from '../base'
import { LatexInline } from './element'
import { LatexInlineAddon } from './types'
import { isInsideMark } from '../text/utils'

/**
 * The render function.
 */
const render: LatexInlineAddon['render'] = ({ element, ...props }) => {
  if (element.type == 'latex-inline') {
    return <LatexInline {...props} element={element} />
  }

  return null
}

/**
 * Handle deletion.
 */
const deleteBackward: LatexInlineAddon['deleteBackward'] = ({
  editor,
  selection,
}) => {
  if (selection?.isCollapsed) {
    const { anchor } = selection

    // 1. Strict adjacency check
    // We only want to intercept if the cursor is at the very start of
    // the current text node. If offset > 0, the user is deleting a char
    // in the current text (e.g., "abc|"), so we should let the default
    // behavior happen.
    if (anchor.offset === 0) {
      // 2. Find the immediate previous node
      // Important: Do NOT pass a `match` property here.
      // We want to know exactly what is right next door.
      const previous = Editor.previous(editor, {
        at: anchor,
      })

      if (previous) {
        // The previous is actually the text node hold by the latex-inline.
        // So in order to get the latex-inline we need to get the parent of
        // the node.
        const [, previousPath] = previous
        const [node, path] = Editor.parent(editor, previousPath)

        if (
          Element.isElement(node) &&
          node.type === 'latex-inline' &&
          node.mode === 'read'
        ) {
          // Switch to edit mode.
          Transforms.setNodes(editor, { mode: 'write' }, { at: path })

          // Move the cursor to the end of the text inside the now editable
          // node.
          const endPoint = Editor.end(editor, path)
          Transforms.select(editor, endPoint)

          // Prevent default delete behaviour.
          return true
        }
      }
    }
  }

  return false
}

/**
 * Handle insert text to detect keyboard shortcut.
 */
const insertText: LatexInlineAddon['insertText'] = (
  { editor, selection },
  text,
) => {
  if (text == '$' && selection?.isCollapsed) {
    // Skip detection if we are inside some special elements.
    if (
      isInsideElement(editor, ['code-block', 'latex-block', 'latex-inline']) ||
      isInsideMark(editor, 'code')
    ) {
      return false
    }

    const { anchor } = selection

    // Get the text immediately before the cursor in the current block.
    const blockStart = Editor.start(editor, anchor.path)
    const rangeBefore: Range = { anchor, focus: blockStart }
    const beforeText = Editor.string(editor, rangeBefore)

    // --- SCENARIO 1: User types "$$" (Edit Mode) ---
    // Check if the character immediately before is $.
    if (beforeText.endsWith('$')) {
      if (beforeText === '$') {
        // We are at the begining of the block so we let
        // $$ to be inserted so we can check for $$$ to
        // insert the latex-block element.
        return false
      }

      // 1. Delete the existing $.
      Transforms.delete(editor, {
        at: {
          anchor: Editor.before(editor, anchor)!,
          focus: anchor,
        },
      })

      // 2. Insert the LatexInline node in "write" mode.
      Transforms.insertNodes(
        editor,
        {
          id: nanoid(),
          type: 'latex-inline',
          mode: 'write',
          children: [{ text: '' }],
        },
        { select: true },
      )

      // 3. Collapse the selection to a cursor (ensures it's not highlighting the empty text)
      Transforms.collapse(editor, { edge: 'end' })

      // 4. Prevent the second $ from being inserted.
      return true
    }

    // --- SCENARIO 2: User types "$content$" (View Mode) ---
    const match = beforeText.match(/\$([^$]+)$/)

    if (match) {
      const [fullMatch, content] = match
      const matchLength = fullMatch.length
      const startPoint = Editor.before(editor, anchor, {
        distance: matchLength,
      })

      if (startPoint) {
        // 1. Select the whole range "$content" excluding the $ we just typed.
        const rangeToReplace = { anchor: startPoint, focus: anchor }

        // 2. Delete the raw text.
        Transforms.delete(editor, { at: rangeToReplace })

        // 3. Insert the LatexInline in "read" mode.
        Transforms.insertNodes(editor, {
          id: nanoid(),
          type: 'latex-inline',
          mode: 'read',
          children: [{ text: content }],
        })

        // 4. Move the cursor *after* the new node so user can keep typing.
        Transforms.move(editor, { distance: 1, unit: 'offset' })

        // 5. Prevent the closing $ character from being inserted.
        return true
      }
    }
  }

  return false
}

/**
 * Identify this element as an inline element.
 */
const isInline: LatexInlineAddon['isInline'] = (ctx, element) => {
  return element.type === 'latex-inline' ? 'yes' : 'no'
}

/**
 * Handle onChange event.
 */
const onChange: LatexInlineAddon['onChange'] = ({ editor, selection }) => {
  const resnapPoint = (point: Point, isFocusPoint: boolean) => {
    if (!selection) {
      return null
    }

    // 1. Check if this point is inside a view-mode node.
    const [match] = Editor.nodes(editor, {
      at: point,
      match: (n) =>
        Element.isElement(n) && n.type === 'latex-inline' && n.mode === 'read',
    })

    if (match) {
      const [node, path] = match
      const start = Editor.start(editor, path)
      const end = Editor.end(editor, path)

      // Case A: Logic for the "Focus" (the moving end of a selection)
      // If we are selecting text (range is not collapsed), we want "Momentum".
      if (isFocusPoint && !Range.isCollapsed(selection)) {
        const { anchor } = selection

        // Check direction relative to the node.
        // If anchor is before the node, we are selecting forwards (Down/Right) => Snap to the end.
        if (Point.compare(anchor, start) < 0) {
          return end
        }
        // If anchor is after the node, we are selecting backwards (Up/Left) => Snap to the start.
        else if (Point.compare(anchor, end) > 0) {
          return start
        }
      }
      // Case B: Logic for Clicks or simple cursor movement.
      // Use "Proximity" - snap to the phisically closest edge.
      const text = Node.string(node)
      if (point.offset <= text.length / 2) {
        return start
      } else {
        return end
      }
    }

    return null
  }

  // We must check both anchor (start) and focus (end) of the selection.
  if (selection) {
    const newAnchor = resnapPoint(selection.anchor, false)
    const newFocus = resnapPoint(selection.focus, true) // Pass true to enable momentum logic.

    if (newAnchor || newFocus) {
      Transforms.setSelection(editor, {
        anchor: newAnchor ?? selection.anchor,
        focus: newFocus ?? selection.focus,
      })
    }
  }

  return false
}

/**
 * Handle arrow based navigation through the inline latex element.
 * By default we consider a view mode inline latex as an "inline block"
 * and therefore navigation should "jump" through it as a whole block.
 * Maybe in the future we can consider a UX similar to the Bear editor
 * where navigation go "through" the latex expression by automatically
 * switching the element mode to view/edit.
 */
const onKeyDown: LatexInlineAddon['onKeyDown'] = (
  { editor, selection },
  evt,
) => {
  if (!selection) {
    return false
  }

  const { anchor, focus } = selection

  const entry = Editor.above(editor, {
    match: (n) => Element.isElement(n) && n.type === 'latex-inline',
  })

  switch (evt.key) {
    case 'Enter': {
      if (entry) {
        evt.preventDefault()
        return true
      }

      break
    }

    case 'ArrowLeft': {
      if (entry) {
        // Check if we are moving away from the element from the
        // start of it.
        const [, path] = entry

        const start = Editor.start(editor, path)

        if (Point.equals(anchor, start)) {
          evt.preventDefault()

          // 1. Switch the node to view mode.
          Transforms.setNodes(editor, { mode: 'read' }, { at: path })

          // 2. Get the cursor out from the node.
          const pointBefore = Editor.before(editor, path)
          if (pointBefore) {
            Transforms.select(editor, pointBefore)
          }

          return true
        }
      } else {
        // Check if we are moving towards the element.
        if (focus.offset === 0) {
          // Get the immediate previous node (Do NOT use match here!)
          const previous = Editor.previous(editor, { at: focus })

          if (previous) {
            // Get the parent of the previous node.
            const [, previousPath] = previous
            const [node, path] = Editor.parent(editor, previousPath)

            if (
              Element.isElement(node) &&
              node.type == 'latex-inline' &&
              node.mode === 'read'
            ) {
              evt.preventDefault()

              // Move backward over the node.
              const pointBefore = Editor.before(editor, path)

              if (pointBefore) {
                // If shift is held, we extend the selection (update focus only).
                // If not, we move the whole cursor (update anchor and focus).
                if (evt.shiftKey) {
                  Transforms.setSelection(editor, { focus: pointBefore })
                } else {
                  Transforms.select(editor, pointBefore)
                }
              }

              return true
            }
          }
        }
      }

      break
    }

    case 'ArrowRight': {
      if (entry) {
        // Check if are moving away from the element.
        const [, path] = entry
        const end = Editor.end(editor, path)

        if (Point.equals(anchor, end)) {
          evt.preventDefault()

          // 1. Switch node to view mode.
          Transforms.setNodes(editor, { mode: 'read' }, { at: path })

          // 2. Get the cursor out of node.
          const pointAfter = Editor.after(editor, path)
          if (pointAfter) {
            Transforms.select(editor, pointAfter)
          }

          return true
        }
      } else {
        // Check if we are moving towards the element.
        const pointAfter = Editor.after(editor, focus)

        // Check if we are at the boundary of the current node.
        if (pointAfter && !Point.equals(pointAfter, focus)) {
          const next = Editor.next(editor, { at: focus })

          if (next) {
            const [, nextPath] = next
            const [node, path] = Editor.parent(editor, nextPath)

            if (Element.isElement(node) && node.type === 'latex-inline') {
              // Check if we are truly at the end of the text node before latex inline.
              //const isAtEndOfText = Point.equals(focus, Editor.end(editor, focus.path));

              //if (isAtEndOfText && node.mode === "read") {
              if (node.mode === 'read') {
                evt.preventDefault()

                const pointAfterNode = Editor.after(editor, path)

                if (pointAfterNode) {
                  if (evt.shiftKey) {
                    Transforms.setSelection(editor, { focus: pointAfterNode })
                  } else {
                    Transforms.select(editor, pointAfterNode)
                  }
                }

                return true
              }
            }
          }
        }
      }

      break
    }
  }

  return false
}

/**
 * The addon builder.
 *
 * @param params - Initial set of params.
 */
export function latexInline(): LatexInlineAddon {
  return elementAddon({
    id: 'latex-inline',
    render,
    deleteBackward,
    insertText,
    isInline,
    onChange,
    onKeyDown,
  })
}

export * from './schema'
export * from './types'