-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslice.go
55 lines (45 loc) · 1.37 KB
/
slice.go
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
package prosemirror
import "fmt"
type Slice struct {
Content Fragment `json:"content,omitempty"`
OpenStart int `json:"openStart,omitempty"`
OpenEnd int `json:"openEnd,omitempty"`
}
func (s Slice) String() string {
return fmt.Sprintf("Slice{Content: %v, OpenStart: %d, OpenEnd: %d}", s.Content, s.OpenStart, s.OpenEnd)
}
// insertAt(pos: number, fragment: Fragment) {
// let content = insertInto(this.content, pos + this.openStart, fragment)
// return content && new Slice(content, this.openStart, this.openEnd)
// }
func (s Slice) InsertAt(pos int, frag Fragment) *Slice {
content := insertInto(s.Content, pos+s.OpenStart, frag, nil)
if content == nil {
return nil
}
return &Slice{
Content: *content,
OpenStart: s.OpenStart,
OpenEnd: s.OpenEnd,
}
}
func insertInto(content Fragment, dist int, insert Fragment, parent *Node) *Fragment {
index, offset := content.findIndex(dist)
child := content.maybeChild(index)
if offset == dist || (child != nil && child.IsText()) {
if parent != nil && !parent.canReplace(index, index, insert, -1, -1) {
return nil
}
c := content.cut(0, dist)
c = c.append(insert)
subc := content.cut(dist, -1)
c = c.append(subc)
return &c
}
inner := insertInto(child.Content, dist-offset-1, insert, nil)
if inner != nil {
r := content.replaceChild(index, child.copy(*inner))
return &r
}
return nil
}