-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileViewerData.js
119 lines (99 loc) · 3.06 KB
/
FileViewerData.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
import {assertDefined} from "./util.js";
import {FileData} from "./FileData.js";
export class FileViewerData {
constructor(db, files, active) {
this.db_ = db;
this.files_ = files; // map of db keys -> FileData
this.active_ = active; // file currently being displayed, null -> nothing
}
static new(db) {
return new FileViewerData(assertDefined(db), new Map(), null);
}
get db() {
return this.db_;
}
get activeKey() {
if (this.active_ != null && this.files_.has(this.active_)) {
return this.active_;
} else {
return null
}
}
get activeFile() {
if (this.active_ != null && this.files_.has(this.active_)) {
return this.files_.get(this.active_);
} else {
return null;
}
}
isSynced(dbFiles) {
for (let [key, _] of dbFiles) {
if (!this.files_.has(key)) {
return false;
}
}
for (let [key, _] of this.files_) {
if (!dbFiles.has(key)) {
return false;
}
}
return true;
}
// doesn't mutate, returns new FileViewerData
sync(dbFiles) {
let newFiles = new Map();
// only copy FileData for files that are in db
for (let [key, fileData] of this.files_) {
if (dbFiles.has(key)) {
newFiles.set(key, fileData);
}
}
// next open files that aren't yet opened
for (let [key, file] of dbFiles) {
if (!this.files_.has(key)) {
newFiles.set(key, FileData.new(file.data));
}
}
let activeKey = this.active_;
if (!newFiles.has(activeKey)) {
activeKey = null;
}
return new FileViewerData(this.db_, newFiles, activeKey);
}
// returns map of files
getFiles(callback) {
this.db_.getFiles().then((dbFiles) => {
// now we must open all the files
if (!this.isSynced(dbFiles)) {
callback(this.sync(dbFiles));
}
});
return this.files_;
}
// doesn't mutate, returns new FileViewerData
setActive(key) {
if (this.files_.has(key)) {
return new FileViewerData(this.db_, this.files_, key);
} else {
return new FileViewerData(this.db_, this.files_, null);
}
}
// doesn't mutate, returns new FileViewerData
setActiveFileData(fileData) {
if (this.active_ == null) {
return this;
} else {
let newFiles = new Map();
for (let [key, _] of this.files_) {
newFiles.set(key, this.files_.get(key));
}
newFiles.set(this.active_, fileData);
return new FileViewerData(this.db_, newFiles, this.active_);
}
}
updateActive(fn) {
if (this.active_ != null && this.files_.has(this.active_)) {
return this.setActiveFileData(fn(this.files_.get(this.active_)));
}
}
}