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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// @ts-nocheck
import { isHotkey } from 'is-hotkey'
import { nanoid } from 'nanoid'
import { Editor, Element, Node, Range } from 'slate'

import {
  AddonBase,
  AddonHandlerArgs,
  AddonHandlerReturn,
  AddonOriginalHandler,
} from './addon/types'
import { EditorAddon } from './addon'

//////////////////////////////////////////////////
// Utilitary Types
//////////////////////////////////////////////////
interface ExtensionProps {
  id: string
  mode: Editor['mode']
  addons: EditorAddon[]
}

//////////////////////////////////////////////////
// Utilitary Functions
//////////////////////////////////////////////////
/**
 * Base extend function.
 */
const extend =
  <TKey extends keyof Editor>(
    key: TKey,
    fn: (editor: Editor, before: Editor[TKey]) => Editor[TKey],
  ) =>
  (editor: Editor) => {
    const before = editor[key]
    const after = fn(editor, before)
    editor[key] = after
  }

export const runAddonHandler = <K extends keyof AddonBase>(
  opts: {
    editor: Editor
    parseResponse?: (response: AddonHandlerReturn<K>) => {
      break?: boolean
      result: AddonHandlerReturn<K> | undefined
    }
  },
  handlerName: K,
  original: AddonOriginalHandler<K>,
  ...args: AddonHandlerArgs<K>
): {
  break?: boolean
  result?: AddonHandlerReturn<K> | undefined
} => {
  const { editor } = opts
  const { addons } = editor

  const ctx = {
    editor,
    selection: editor.selection
      ? {
          ...editor.selection,
          isCollapsed:
            !!editor.selection && Range.isCollapsed(editor.selection),
        }
      : undefined,
    [handlerName]: original,
  }

  const parseResponse =
    opts.parseResponse ??
    ((rawResponse) => {
      const response =
        typeof rawResponse === 'boolean'
          ? { break: rawResponse }
          : (rawResponse as {
              break?: boolean
              result: AddonHandlerReturn<K> | undefined
            })

      return response
    })

  for (const addon of addons) {
    const handler = addon[handlerName] as any

    if (typeof handler === 'function') {
      const rawResponse = handler(
        {
          addon,
          ...ctx,
        },
        ...args,
      )

      // We have two options here:
      // (1) Response is a simple boolean indicating if we should break following execution;
      // (2) Response if of type {break?: boolean; result: any}.
      const response = parseResponse(rawResponse)

      // First responder strategy: the first addon able to
      // handle the data wins.
      if (response.break) {
        return response
      }
    }
  }

  return { break: false }
}

//////////////////////////////////////////////////
// Extended Editor Functions
//////////////////////////////////////////////////
/**
 * Extended the apply function.
 * @param apply
 * @returns
 */
const apply = extend('apply', (editor, apply) => (operation) => {
  if (operation.type === 'insert_node') {
    const { node } = operation

    // If it's an Element (not a text node) and missing an ID
    if (Element.isElement(node) && !node.id) {
      // We create a copy with the ID
      const nodeWithId = { ...node, id: nanoid() }

      // Replace the original operation node
      operation.node = nodeWithId
    }
  }

  if (operation.type === 'split_node') {
    const { path, properties } = operation

    // Get the node that is being split
    const node = Node.get(editor, path)

    // We only care if we are splitting an Element (Paragraph, Heading, etc.)
    // Slate also splits Text nodes, which we want to ignore here.
    if (Element.isElement(node)) {
      // Force a new ID into the properties of the NEW node being created
      operation.properties = {
        ...properties,
        id: nanoid(),
      }
    }
  }

  apply(operation)
})

/**
 * Extend the deleteBackward function.
 */
const deleteBackward = extend(
  'deleteBackward',
  (editor, deleteBackward) => (unit) => {
    if (editor.mode == 'read') {
      return
    }

    if (
      runAddonHandler({ editor }, 'deleteBackward', deleteBackward, unit).break
    ) {
      return
    }

    deleteBackward(unit)
  },
)

/**
 * Extend the deleteForward function.
 */
const deleteForward = extend(
  'deleteForward',
  (editor, deleteForward) => (unit) => {
    if (editor.mode == 'read') {
      return
    }

    if (
      runAddonHandler({ editor }, 'deleteForward', deleteForward, unit).break
    ) {
      return
    }

    deleteForward(unit)
  },
)

/**
 * Extend the insertBreak function.
 */
const insertBreak = extend('insertBreak', (editor, insertBreak) => () => {
  if (editor.mode == 'read') {
    return
  }

  if (runAddonHandler({ editor }, 'insertBreak', insertBreak).break) {
    return
  }

  insertBreak()
})

/**
 * Extend the insertData function.
 */
const insertData = extend('insertData', (editor, insertData) => (data) => {
  if (editor.mode == 'read') {
    return
  }

  if (runAddonHandler({ editor }, 'insertData', insertData, data).break) {
    return
  }

  insertData(data)
})

/**
 * Extend the insertText function.
 */
const insertText = extend('insertText', (editor, insertText) => (text) => {
  if (editor.mode == 'read') {
    return
  }

  if (runAddonHandler({ editor }, 'insertText', insertText, text).break) {
    return
  }

  insertText(text)
})

/**
 * Extend the isBlock function.
 */
const isBlock = extend('isBlock', (editor, isBlock) => (element) => {
  // Check if any addon identifies this element as a block
  const { result } = runAddonHandler(
    {
      editor,
      parseResponse: (rawResponse) => ({
        break: rawResponse === 'yes',
        result: rawResponse,
      }),
    },
    'isBlock',
    isBlock,
    element,
  )

  // If an addon says "yes", it's a block.
  // Otherwise, fallback to slate's default isBlock.
  return result === 'yes' || isBlock(element)
})

/**
 * Extend the isInline function.
 */
const isInline = extend('isInline', (editor, isInline) => (element) => {
  const { result } = runAddonHandler(
    {
      editor,
      parseResponse: (rawResponse) => ({
        break: rawResponse == 'yes',
        result: rawResponse,
      }),
    },
    'isInline',
    isInline,
    element,
  )

  return result == 'yes' || isInline(element)
})

/**
 * Extend the normalizeNode function.
 */
const normalizeNode = extend(
  'normalizeNode',
  (editor, normalizeNode) => (entry) => {
    if (editor.mode == 'read') {
      return
    }

    if (
      runAddonHandler({ editor }, 'normalizeNode', normalizeNode, entry).break
    ) {
      return
    }

    normalizeNode(entry)
  },
)

/**
 * Extend the onKeyDown function.
 */
const onKeyDown = extend('onKeyDown', (editor, onKeyDown) => (evt) => {
  if (editor.mode == 'read') {
    return
  }

  if (runAddonHandler({ editor }, 'onKeyDown', onKeyDown, evt).break) {
    return
  }

  // Undo & Redo
  if (isHotkey('mod+z')(evt)) {
    evt.preventDefault()
    editor.undo()
  } else if (isHotkey(['mod+y', 'mod+shift+z'])(evt)) {
    evt.preventDefault()
    editor.redo()
  }
})

/**
 * Extend the onChange function.
 */
const onChange = extend('onChange', (editor, onChange) => (...rest) => {
  if (
    editor.mode == 'write' &&
    runAddonHandler({ editor }, 'onChange', onChange, ...rest).break
  ) {
    return
  }

  onChange(...rest)
})

//////////////////////////////////////////////////
// Entrypoint to Extend the Editor
//////////////////////////////////////////////////
/**
 * Extend the editor with the extended functions defined above and
 * with custom props passed in.
 *
 * @param editor -
 * @param props -
 */
export function withAddons(
  editor: Editor,
  props: {
    id: string
    mode: Editor['mode']
    addons: EditorAddon[]
  },
) {
  editor.addons = props.addons
  editor.mode = props.mode

  // Define the getAddon utility function.
  editor.getAddon = (id) => {
    // We cast to EditorAddon[] to allow the .find logic to work smoothly

    return (editor.addons as EditorAddon[]).find((a) => a.id === id) as any
  }

  // Define the hasAddon utility function.
  editor.hasAddon = (id) => {
    return Boolean(editor.getAddon(id))
  }

  // Extend editor functions.
  apply(editor)
  deleteBackward(editor)
  deleteForward(editor)
  insertBreak(editor)
  insertData(editor)
  insertText(editor)
  isBlock(editor)
  isInline(editor)
  normalizeNode(editor)
  onChange(editor)
  onKeyDown(editor)

  // Return the extended editor.
  return editor
}

/**
 * Set editor props.
 */
export function setExtensionProps(
  editor: Editor,
  props: Partial<ExtensionProps>,
) {
  editor.id = props.id ?? editor.id
  editor.addons = props.addons ?? editor.addons
  editor.mode = props.mode ?? editor.mode
}

/**
 * Extend the editor with the extended functions defined above and
 * with custom props passed in.
 *
 * @param editor -
 * @param props -
 */
export function withExtensions(editor: Editor, props: ExtensionProps) {
  setExtensionProps(editor, props)

  // Define the getAddon utility function.
  editor.getAddon = (id) => {
    // We cast to EditorAddon[] to allow the .find logic to work smoothly

    return (editor.addons as EditorAddon[]).find((a) => a.id === id) as any
  }

  // Define the hasAddon utility function.
  editor.hasAddon = (id) => {
    return Boolean(editor.getAddon(id))
  }

  // Extend editor functions.
  apply(editor)
  deleteBackward(editor)
  deleteForward(editor)
  insertBreak(editor)
  insertData(editor)
  insertText(editor)
  isInline(editor)
  normalizeNode(editor)
  onChange(editor)
  onKeyDown(editor)

  // Return the extended editor.
  return editor
}