forked from josephg/ShareJS
/
text-tp2-api.coffee
89 lines (70 loc) · 2.16 KB
/
text-tp2-api.coffee
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
# Text document API for text-tp2
if WEB?
type = exports.types['text-tp2']
else
type = require './text-tp2'
{_takeDoc:takeDoc, _append:append} = type
appendSkipChars = (op, doc, pos, maxlength) ->
while (maxlength == undefined || maxlength > 0) and pos.index < doc.data.length
part = takeDoc doc, pos, maxlength, true
maxlength -= part.length if maxlength != undefined and typeof part is 'string'
append op, (part.length || part)
type['api'] =
'provides': {'text':true}
# The number of characters in the string
'getLength': -> @snapshot.charLength
# Flatten a document into a string
'getText': ->
strings = (elem for elem in @snapshot.data when typeof elem is 'string')
strings.join ''
'insert': (text, pos, callback) ->
pos = 0 if pos == undefined
op = []
docPos = {index:0, offset:0}
appendSkipChars op, @snapshot, docPos, pos
append op, {'i':text}
appendSkipChars op, @snapshot, docPos
@submitOp op, callback
op
'del': (length, pos, callback) ->
op = []
docPos = {index:0, offset:0}
appendSkipChars op, @snapshot, docPos, pos
while length > 0
part = takeDoc @snapshot, docPos, length, true
if typeof part is 'string'
append op, {'d':part.length}
length -= part.length
else
append op, part
appendSkipChars op, @snapshot, docPos
@submitOp op, callback
op
'_register': ->
# Interpret recieved ops + generate more detailed events for them
@on 'remoteop', (op, snapshot) ->
textPos = 0
docPos = {index:0, offset:0}
for component in op
if typeof component is 'number'
# Skip
remainder = component
while remainder > 0
part = takeDoc snapshot, docPos, remainder
if typeof part is 'string'
textPos += part.length
remainder -= part.length || part
else if component.i != undefined
# Insert
if typeof component.i is 'string'
@emit 'insert', component.i, textPos
textPos += component.i.length
else
# Delete
remainder = component.d
while remainder > 0
part = takeDoc snapshot, docPos, remainder
if typeof part is 'string'
@emit 'delete', part, textPos
remainder -= part.length || part
return