-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileIndex.js
88 lines (73 loc) · 2.15 KB
/
fileIndex.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
var EventEmitter = require('nanobus')
var inherits = require('inherits')
var def = require('./../definitions')
var File = require('./file')
var CRDTMap = require('./../crdt/CRDTMap')
inherits(FileIndex, EventEmitter)
function FileIndex (uuid) {
if (!(this instanceof FileIndex)) return new FileIndex(uuid)
EventEmitter.call(this)
this._uuid = uuid
this._counter = 0
this._map = new CRDTMap(uuid)
this._files = {}
this._map.on('set', this._onSet.bind(this))
this._map.on('remove', this._onRemove.bind(this))
this._map.on('operation', (op) => {
this.emit('operation', op)
})
}
FileIndex.prototype._onSet = function (event) {
var path = event.key
var fileId = event.value
var file = this._files[fileId]
if (file) {
this.emit('move', new def.FileMoveEvent(file.path, path, file))
file.path = path
} else {
file = new File(path, this._uuid, fileId)
this._files[fileId] = file
this.emit('create', new def.FileCreateEvent(path, file))
}
}
FileIndex.prototype._onRemove = function (event) {
var fileId = event.value
var file = this._files[fileId]
file.delete()
delete this._files[fileId]
this.emit('remove', new def.FileRemoveEvent(file.path, file))
}
FileIndex.prototype.createFile = function (path) {
var uuid = def.UUID()
var newFile = new File(path, this._uuid, uuid)
this._files[uuid] = newFile
this._map.set(path, uuid)
}
FileIndex.prototype.removeFile = function (path) {
var uuid = this._map.get(path)
this._map.remove(path)
this._files[uuid].delete()
delete this._files[uuid]
}
FileIndex.prototype.moveFile = function (oldPath, newPath) {
var uuid = this._map.get(oldPath)
this._map.set(newPath, uuid)
this._map.remove(oldPath)
}
FileIndex.prototype.getFile = function (path) {
var uuid = this._map.get(path)
return this._files[uuid]
}
FileIndex.prototype.getFiles = function () {
return this._map.values().map(function (uuid) {
return this._files[uuid]
})
}
FileIndex.prototype.applyOperation = function (operation) {
if (!operation.fileId) {
this._map.applyOperation(operation)
} else {
this._files[operation.fileId].applyOperation(operation)
}
}
module.exports = FileIndex