forked from galaxian85/CRDT-folder-poc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagic.js
332 lines (301 loc) · 9.51 KB
/
magic.js
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
import * as Y from 'yjs'
import { nanoid } from 'nanoid'
import { SocketIOProvider } from './client.js'
const ydoc = new Y.Doc();
const yArray = ydoc.getArray('magic')
const provider = new SocketIOProvider(
window.serverUrl || 'ws://localhost:4444',
'crdt-folder',
ydoc,
);
// const provider = new WebrtcProvider(
// 'crdt-folder',
// ydoc,
// { signaling: [window.serverUrl || 'ws://localhost:4444'] },
// )
let rootFolder
let currentViewFolder
let detailViewFolder
let selectedItems = new Set()
ydoc.on('update', update => {
initRootFolder()
if (!currentViewFolder) {
currentViewFolder = rootFolder
}
render(document.querySelector('.overview'), currentViewFolder)
if (detailViewFolder) {
render(document.querySelector('.detail'), detailViewFolder)
}
})
yArray.observeDeep(() => {
// delete duplicated items
const latestTimestamps = new Map()
traverseBackward((item) => {
const timestamp = Math.max(latestTimestamps.get(item.id) ?? 0, item.timestamp)
latestTimestamps.set(item.id, timestamp)
})
ydoc.transact(() => {
traverseBackward((item, folder, idx) => {
if (item.timestamp < latestTimestamps.get(item.id)) {
folder.delete(idx)
}
})
})
})
function traverseBackward (cb) {
for (let i = yArray.length - 1; i >= 0; i--) {
const folder = yArray.get(i)
for (let j = folder.length - 1; j >= 0; j--) {
cb(folder.get(j), folder, j)
}
}
}
provider.on('status', () => {
updateConnectButtonState()
})
function initRootFolder () {
if (yArray.length === 0) {
rootFolder = new Y.Array()
rootFolder.push([{ id: '_ROOT_', parent: null, name: '_ROOT_', timestamp: Date.now() }])
yArray.push([rootFolder])
} else {
rootFolder = yArray.get(0)
}
}
function render (rootEl, folderArray) {
rootEl.innerHTML = ''
const folderMeta = folderArray.get(0)
if (!folderMeta) {
currentViewFolder = rootFolder
render(document.querySelector('.overview'), rootFolder)
return
}
yArray.forEach(folder => {
const _folderMeta = folder.get(0)
if (_folderMeta.parent === folderMeta.id) {
const folderEl = createFolderEl(_folderMeta)
folderEl.dataset.parentFolderId = folderMeta.id
rootEl.appendChild(folderEl)
}
})
for (let i = 1; i < folderArray.length; i++) {
const item = folderArray.get(i)
const itemEl = createItemEl(item)
itemEl.dataset.parentFolderId = folderMeta.id
rootEl.appendChild(itemEl)
}
updateBackButtonState()
updatePathState()
}
function createFolderEl (folderMeta) {
const { id, name } = folderMeta
const checked = selectedItems.has(id) ? 'checked' : ''
const folderEl = document.createElement('div')
folderEl.classList.add('folder-icon')
folderEl.classList.add('item')
folderEl.innerHTML = `
<div>
<input class="cb" type="checkbox" ${checked} />
<button class="view-folder">View</button>
<button class="open-in-detail">Open in detail</button>
<button class="move-into">Move selected item into here</button>
<button class="delete-item">Delete</button>
<button class="rename">Rename</button>
</div>
<div>${id}</div>
<div class="name">${name}</div>
`
folderEl.dataset.id = id
folderEl.addEventListener('click', checkboxHandler)
folderEl.querySelector('.view-folder').addEventListener('click', viewFolderHandler)
folderEl.querySelector('.open-in-detail').addEventListener('click', openInDetailViewHandler)
folderEl.querySelector('.move-into').addEventListener('click', movoIntoHandler)
folderEl.querySelector('.delete-item').addEventListener('click', deleteItemHandler)
folderEl.querySelector('.rename').addEventListener('click', renameHandler)
return folderEl
}
function viewFolderHandler (event) {
const id = event.target.closest('.item').dataset.id
const folder = findFolder(id)
currentViewFolder = folder
render(document.querySelector('.overview'), folder)
}
function openInDetailViewHandler (event) {
const id = event.target.closest('.item').dataset.id
const folder = findFolder(id)
detailViewFolder = folder
render(document.querySelector('.detail'), folder)
}
function movoIntoHandler (event) {
const timestamp = Date.now()
const id = event.target.closest('.item').dataset.id
const targetFolder = findFolder(id)
const foldersToMove = []
const itemsToMove = []
for (const folder of yArray) {
const folderMeta = folder.get(0)
if (selectedItems.has(folderMeta.id)) {
foldersToMove.push(folder)
}
for (let i = 1; i < folder.length; i++) {
const item = folder.get(i)
if (selectedItems.has(item.id)) {
itemsToMove.push({ ...item, timestamp })
}
}
}
ydoc.transact(() => {
deleteItems(selectedItems, false)
for (const folder of foldersToMove) {
const folderMeta = folder.get(0)
folder.delete(0)
folder.insert(0, [{ ...folderMeta, parent: id, timestamp }])
}
targetFolder.push(itemsToMove)
})
}
function updateBackButtonState () {
const backButton = document.querySelector('.go-back')
backButton.toggleAttribute('disabled', currentViewFolder.get(0).id === rootFolder.get(0).id)
}
function updatePathState () {
const pathEl = document.querySelector('.path')
const path = []
let folder = currentViewFolder
while (folder) {
const { name, parent} = folder.get(0)
path.unshift(name)
folder = findFolder(parent)
}
pathEl.textContent = `Path: ${path.join(' > ')}`
}
function updateConnectButtonState () {
const connectButton = document.querySelector('.connect-switch')
connectButton.textContent = provider.socket.connected ? 'disconnect' : 'connect'
connectButton.classList.toggle('connected', provider.socket.connected)
}
function findFolder (id) {
let folder
yArray.forEach(f => {
if (f.get(0).id === id) {
folder = f
}
})
return folder
}
function createItemEl (itemMeta) {
const { id, name } = itemMeta
const checked = selectedItems.has(id) ? 'checked' : ''
const itemEl = document.createElement('div')
itemEl.classList.add('item-icon')
itemEl.classList.add('item')
itemEl.innerHTML = `
<div>
<input class="cb" type="checkbox" ${checked} />
<button class="delete-item">Delete</button>
<button class="rename">Rename</button>
</div>
<div>${id}</div>
<div class="name">${name}</div>
`
itemEl.dataset.id = id
itemEl.addEventListener('click', checkboxHandler)
itemEl.querySelector('.delete-item').addEventListener('click', deleteItemHandler)
itemEl.querySelector('.rename').addEventListener('click', renameHandler)
return itemEl
}
document.querySelector('.go-back').addEventListener('click', () => {
const parentId = currentViewFolder.get(0).parent
const folder = findFolder(parentId)
currentViewFolder = folder
render(document.querySelector('.overview'), folder)
})
document.querySelector('.add-folder').addEventListener('click', () => {
initRootFolder()
const newFolder = new Y.Array()
const parentId = currentViewFolder.get(0).id
newFolder.push([{ id: nanoid(), parent: parentId, name: 'New Folder', timestamp: Date.now() }])
yArray.push([newFolder])
})
document.querySelector('.add-item').addEventListener('click', () => {
initRootFolder()
currentViewFolder.push([{ id: nanoid(), name: 'New Item', timestamp: Date.now() }])
})
document.querySelector('.delete').addEventListener('click', () => {
deleteItems(selectedItems)
selectedItems.clear()
})
document.querySelector('.connect-switch').addEventListener('click', () => {
if (provider.socket.connected) {
provider.disconnect()
} else {
provider.connect()
}
})
function checkboxHandler (event) {
const itemEl = event.target.closest('.item')
const id = itemEl.dataset.id
if (event.target.tagName === 'BUTTON') return
const checkbox = itemEl.querySelector('.cb')
if (selectedItems.has(id)) {
selectedItems.delete(id)
checkbox.checked = false
} else {
selectedItems.add(id)
checkbox.checked = true
}
}
function deleteItemHandler (event) {
const id = event.target.closest('.item').dataset.id
deleteItems(new Set([id]))
}
function deleteItems (idSet, transaction = true) {
const _delete = () => {
for (let i = yArray.length - 1; i >= 0; i--) {
const folder = yArray.get(i)
for (let j = folder.length - 1; j > 0; j--) {
const id = folder.get(j).id
if (idSet.has(id)) {
folder.delete(j)
idSet.delete(id)
selectedItems.delete(id)
}
}
const id = folder.get(0).id
if (idSet.has(id)) {
yArray.delete(i)
idSet.delete(id)
selectedItems.delete(id)
}
}
}
if (transaction) {
ydoc.transact(_delete)
} else {
_delete()
}
}
function renameHandler (event) {
const targetEl = event.target.closest('.item')
const id = targetEl.dataset.id
const isFolder = targetEl.classList.contains('folder-icon')
if (isFolder) {
const folder = findFolder(id)
const folderMeta = folder.get(0)
const newName = prompt('Enter new folder name', folderMeta.name)
ydoc.transact(() => {
folder.delete(0)
folder.insert(0, [{ ...folderMeta, name: newName, timestamp: Date.now() }])
})
} else {
const parentFolderId = targetEl.dataset.parentFolderId
const parentFolder = findFolder(parentFolderId)
const itemIdx = parentFolder.toArray().findIndex(item => item.id === id)
const itemMeta = parentFolder.get(itemIdx)
const newName = prompt('Enter new item name', itemMeta.name)
ydoc.transact(() => {
parentFolder.delete(itemIdx)
parentFolder.insert(itemIdx, [{ ...itemMeta, name: newName, timestamp: Date.now() }])
})
}
}