-
Notifications
You must be signed in to change notification settings - Fork 16
/
ydoc.py
196 lines (162 loc) · 6.37 KB
/
ydoc.py
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
import copy
from typing import Any, Dict
from uuid import uuid4
import y_py as Y
from .utils import cast_all
class YBaseDoc:
def __init__(self, ydoc: Y.YDoc):
self._ydoc = ydoc
self._ystate = self._ydoc.get_map("state")
self._subscriptions = {}
@property
def ystate(self):
return self._ystate
@property
def ydoc(self):
return self._ydoc
@property
def source(self):
return self.get()
@source.setter
def source(self, value):
return self.set(value)
@property
def dirty(self) -> None:
return self._ystate["dirty"]
@dirty.setter
def dirty(self, value: bool) -> None:
with self._ydoc.begin_transaction() as t:
self._ystate.set(t, "dirty", value)
def get(self):
raise RuntimeError("Y document get not implemented")
def set(self, value):
raise RuntimeError("Y document set not implemented")
def observe(self, callback):
raise RuntimeError("Y document observe not implemented")
def unobserve(self):
for k, v in self._subscriptions.items():
k.unobserve(v)
self._subscriptions = {}
class YFile(YBaseDoc):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._ysource = self._ydoc.get_text("source")
def get(self):
return str(self._ysource)
def set(self, value):
with self._ydoc.begin_transaction() as t:
# clear document
source_len = len(self._ysource)
if source_len:
self._ysource.delete_range(t, 0, source_len)
# initialize document
if value:
self._ysource.extend(t, value)
def observe(self, callback):
self.unobserve()
self._subscriptions[self._ystate] = self._ystate.observe(callback)
self._subscriptions[self._ysource] = self._ysource.observe(callback)
class YNotebook(YBaseDoc):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._ymeta = self._ydoc.get_map("meta")
self._ycells = self._ydoc.get_array("cells")
def get_cell(self, index: int) -> Dict[str, Any]:
meta = self._ymeta.to_json()
cell = self._ycells[index].to_json()
cast_all(cell, float, int) # cells coming from Yjs have e.g. execution_count as float
if "id" in cell and meta["nbformat"] == 4 and meta["nbformat_minor"] <= 4:
# strip cell IDs if we have notebook format 4.0-4.4
del cell["id"]
if (
"attachments" in cell
and cell["cell_type"] in ["raw", "markdown"]
and not cell["attachments"]
):
del cell["attachments"]
return cell
def append_cell(self, value: Dict[str, Any], txn=None) -> None:
ycell = self.create_ycell(value)
if txn is None:
with self._ydoc.begin_transaction() as txn:
self._ycells.append(txn, ycell)
else:
self._ycells.append(txn, ycell)
def set_cell(self, index: int, value: Dict[str, Any], txn=None) -> None:
ycell = self.create_ycell(value)
self.set_ycell(index, ycell, txn)
def create_ycell(self, value: Dict[str, Any]) -> None:
cell = copy.deepcopy(value)
if "id" not in cell:
cell["id"] = str(uuid4())
cell_type = cell["cell_type"]
cell["source"] = Y.YText(cell["source"])
cell["metadata"] = Y.YMap(cell.get("metadata", {}))
if cell_type in ("raw", "markdown"):
cell["attachments"] = Y.YMap(cell.get("attachments", {}))
elif cell_type == "code":
cell["outputs"] = Y.YArray(cell.get("outputs", []))
return Y.YMap(cell)
def set_ycell(self, index: int, ycell: Y.YMap, txn=None):
if txn is None:
with self._ydoc.begin_transaction() as txn:
self._ycells.delete(txn, index)
self._ycells.insert(txn, index, ycell)
else:
self._ycells.delete(txn, index)
self._ycells.insert(txn, index, ycell)
def get(self):
meta = self._ymeta.to_json()
cast_all(meta, float, int) # notebook coming from Yjs has e.g. nbformat as float
cells = []
for i in range(len(self._ycells)):
cell = self.get_cell(i)
if "id" in cell and meta["nbformat"] == 4 and meta["nbformat_minor"] <= 4:
# strip cell IDs if we have notebook format 4.0-4.4
del cell["id"]
if (
"attachments" in cell
and cell["cell_type"] in ["raw", "markdown"]
and not cell["attachments"]
):
del cell["attachments"]
cells.append(cell)
return dict(
cells=cells,
metadata=meta["metadata"],
nbformat=int(meta["nbformat"]),
nbformat_minor=int(meta["nbformat_minor"]),
)
def set(self, value):
nb_without_cells = {key: value[key] for key in value.keys() if key != "cells"}
nb = copy.deepcopy(nb_without_cells)
cast_all(nb, int, float) # Yjs expects numbers to be floating numbers
cells = value["cells"] or [
{
"cell_type": "code",
"execution_count": None,
"metadata": {},
"outputs": [],
"source": "",
"id": str(uuid4()),
}
]
with self._ydoc.begin_transaction() as t:
# clear document
cells_len = len(self._ycells)
for key in self._ymeta:
self._ymeta.pop(t, key)
if cells_len:
self._ycells.delete_range(t, 0, cells_len)
for key in [k for k in self._ystate if k != "dirty"]:
self._ystate.pop(t, key)
# initialize document
self._ycells.extend(t, [self.create_ycell(cell) for cell in cells])
self._ymeta.set(t, "metadata", nb["metadata"])
self._ymeta.set(t, "nbformat", nb["nbformat"])
self._ymeta.set(t, "nbformat_minor", nb["nbformat_minor"])
def observe(self, callback):
self.unobserve()
self._subscriptions[self._ystate] = self._ystate.observe(callback)
self._subscriptions[self._ymeta] = self._ymeta.observe(callback)
self._subscriptions[self._ycells] = self._ycells.observe_deep(callback)