/
Item.ts
361 lines (320 loc) · 9.17 KB
/
Item.ts
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import { types, flow } from 'mobx-state-tree';
import { XmlEntities } from 'html-entities';
import flattenDeep from 'lodash/flattenDeep';
import age from 'utils/age';
import promptLogin from 'utils/promptLogin';
import Metadata from './Metadata';
import Items from '../Items';
import Hackernews from '../services/Hackernews';
import { db } from 'utils/firebase';
import Account from '../Account';
const entities = new XmlEntities();
const MAX_LEVELS = 5;
const ITEMS_PER_LEVEL = 5;
/**
* Item model
*/
const Item = types.model('Item', {
// Base fields
id: types.identifier(types.string),
type: types.string,
by: types.maybe(types.string),
descendants: types.optional(types.number, 0),
kids: types.optional(types.array(types.number), []),
score: types.maybe(types.number),
time: types.number,
title: types.maybe(types.string),
text: types.maybe(types.string),
url: types.maybe(types.string),
parent: types.maybe(types.string),
// App specific fields
metadata: types.maybe(Metadata),
belongsTo: types.optional(types.array(types.string), []),
comments: types.optional(types.array(types.late(() => ItemReference)), []),
offset: types.optional(types.number, 0),
isPending: types.optional(types.boolean, false),
isError: types.optional(types.boolean, false),
})
.views(self => ({
get date() {
return new Date(self.time * 1000);
},
get level() {
return self.belongsTo.length;
},
get hackernewsUrl() {
return `https://news.ycombinator.com/item?id=${self.id}`;
},
get isOwn() {
return self.by === Account.userId;
},
get isVoted() {
return !!Account.voted.get(self.id);
},
get isFavorited() {
return !!Account.favorited.get(self.id);
},
get isHidden() {
return !!Account.hidden.get(self.id);
},
get isFlagged() {
return !!Account.flagged.get(self.id);
},
get isRead() {
return Account.read.get(self.id);
},
get unfetched() {
return Math.max(0, self.kids.length - self.offset);
},
get deepFetchedCount() {
return self.comments.map(item => item.deepFetchedCount).reduce((a, b) => a + b, 0) + self.comments.length;
},
get ago() {
return age(new Date(self.time * 1000));
},
get prettyText() {
return entities.decode(self.text);
},
/**
* Get recursive comments for this item in a flat array
* [[1,2],[3,[4,5]],6] => [1,2,3,4,5,6]
* @return {Array}
*/
get flatComments() {
return flattenDeep([
...self.comments.map((comment: any) => {
if (!comment) return [];
return [
comment,
...comment.flatComments,
];
}),
...((self as any).unfetched > 0 ? [{ comment: self, id: `More_${self.id}`, type: 'more' }] : []),
]);
},
}))
.actions(self => ({
/**
* Fetch a single comment by id
* @param id Item ID
*/
async fetchComment(id: string, opts = { force: undefined, index: 0, all: false }) {
try {
// Fetch comment from backend (or cache)
const comment = await Items.fetchItem(id, { force: opts.force }) as any;
if (!comment) {
return null;
}
// Update belongsTo list with parents
comment.setBelongsTo([self.id, ...self.belongsTo]);
// Fetch nested comments
if (opts.index < (MAX_LEVELS - 1 - self.level) || opts.all) {
await comment.fetchComments(opts);
}
return comment;
} catch (err) {}
return null;
},
/**
* Fetch kids as comments
*/
fetchComments({ force = true, offset = self.offset, all = false } = {}) {
return flow(function* () {
const end = offset > 0 ? 20 : (MAX_LEVELS - 1 - self.level) * ITEMS_PER_LEVEL;
const limit = Math.min(20, Math.max(1, end));
// Get list of comments to fetch
const commentIds = all ? self.kids.map(String) : self.kids.slice(offset, offset + limit).map(String);
// Fetch them
const comments = yield Promise.all(commentIds.map((id, index) =>
(self as any).fetchComment(id, { force, offset, index, all })));
const addIds = comments.filter(n => n && n.id).map(n => n.id);
// Push their id's
if (offset === 0) {
self.comments.replace(addIds);
} else {
self.comments.push(...addIds.filter(id => self.comments.indexOf(id) === -1));
}
self.offset = (offset + limit);
// Return comments
return self.comments;
})();
},
fetchParent() {
return flow(function* () {
if (self.parent) {
const parent = yield Items.fetchItem(self.parent);
return parent;
}
return null;
})();
},
refetch() {
return flow(function* () {
const ref = db.ref(`v0/item/${self.id}`);
ref.keepSynced(true);
const data = yield new Promise((resolve) => {
ref.once('value').then(s => resolve(s.val()));
setTimeout(() => ref.off('value') && resolve(null), 2500);
});
// Update model
if (data) {
self.by = data.by;
self.descendants = data.descendants;
self.kids = data.kids;
self.score = data.score;
self.time = data.time;
self.title = data.title;
self.text = data.text;
self.url = data.url;
}
})();
},
read() {
Account.toggle(self.id, 'read', true);
},
setMetadata(metadata: any) {
self.metadata = metadata;
},
setBelongsTo(belongsTo: any) {
self.belongsTo = belongsTo;
},
setIsError(flag: boolean) {
self.isError = flag;
},
incrementScore(value) {
self.score += value;
},
vote() {
if (!Account.isLoggedIn) {
return promptLogin();
}
const assumedFlag = !self.isVoted;
Account.toggle(self.id, 'voted');
(self as any).incrementScore((assumedFlag ? 1 : -1));
Hackernews.vote(self.id, assumedFlag).then((flag: boolean) => {
Account.toggle(self.id, 'voted', flag);
if (flag !== assumedFlag) {
(self as any).incrementScore((flag ? -1 : 1));
}
});
},
flag() {
if (!Account.isLoggedIn) {
return promptLogin();
}
const assumedFlag = !self.isFlagged;
Account.toggle(self.id, 'flagged');
Hackernews.flag(self.id, assumedFlag).then((flag: boolean) => {
Account.toggle(self.id, 'flagged', flag);
});
},
hide() {
if (!Account.isLoggedIn) {
return promptLogin();
}
const assumedFlag = !self.isHidden;
Account.toggle(self.id, 'hidden');
Hackernews.hide(self.id, assumedFlag).then((flag: boolean) => {
Account.toggle(self.id, 'hidden', flag);
});
},
favorite() {
if (!Account.isLoggedIn) {
return promptLogin();
}
const assumedFlag = !self.isFavorited;
Account.toggle(self.id, 'favorited');
Hackernews.favorite(self.id, assumedFlag).then((flag: boolean) => {
Account.toggle(self.id, 'favorited', flag);
});
},
delete() {
return new Promise((resolve, reject) => {
if (!Account.isLoggedIn) {
return reject(promptLogin());
}
const ref = db.ref(`v0/item/${self.id}`);
ref.on('value', async (s) => {
ref.off('value');
resolve(true);
});
try {
const isDeleted = Hackernews.delete(self.id);
if (!isDeleted) {
reject('Could not delete');
} else {
self.text = null;
self.by = null;
resolve(true);
}
} catch (err) {
reject(err.message);
}
});
},
/**
* Reply to a story or a comment.
* Will create a placeholder comment for display
* and update it when changes are available in the backend.
*
* @param text Text to reply
*/
reply(text: string) {
return flow(function* () {
if (!Account.isLoggedIn) {
return promptLogin();
}
// Create placeholder comment
const comment = Item.create({
text,
type: 'comment',
id: `Placeholder_${Date.now()}`,
by: Account.user.id,
time: Math.floor(Date.now() / 1000),
belongsTo: [self.id, ...self.belongsTo],
isPending: true,
isError: false,
});
// Add to bottom
self.comments.push(comment);
flow(function* () {
try {
// Make comment on Hacker News service
const itemId = yield Hackernews.reply(self.type, self.id, Account.user.id, text);
// Run function when item will be created in Firebase
const ref = db.ref(`v0/item/${itemId}`);
ref.keepSynced(true);
ref.on('value', (s) => {
if (s.val() !== null) {
const item = (self as any).fetchComment(itemId);
if (item) {
const index = self.comments.findIndex((item: any) => item.id === comment.id);
self.comments.splice(index, 1, itemId);
} else {
comment.setIsError(true);
ref.off('value');
}
}
});
} catch (err) {
comment.setIsError(true);
}
})();
return comment;
})();
},
}));
/**
* Getter and setter for item references
* @param {string} identifier item.id
* @return {Item}
*/
export const ItemReference = types.reference(Item, {
get(identifier: string, parent: any) {
return Items.items.get(identifier) || null;
},
set(value: any) {
return value;
},
});
export default Item;