/
BookmarksModel.swift
379 lines (313 loc) · 11.7 KB
/
BookmarksModel.swift
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Deferred
import Foundation
import Shared
private let log = Logger.syncLogger
/**
* The kinda-immutable base interface for bookmarks and folders.
*/
open class BookmarkNode {
open var id: Int?
open let guid: GUID
open let title: String
open let isEditable: Bool
open var favicon: Favicon?
init(guid: GUID, title: String, isEditable: Bool=false) {
self.guid = guid
self.title = title
self.isEditable = isEditable
}
open var canDelete: Bool {
return self.isEditable
}
}
open class BookmarkSeparator: BookmarkNode {
init(guid: GUID) {
super.init(guid: guid, title: "—")
}
}
/**
* An immutable item representing a bookmark.
*
* To modify this, issue changes against the backing store and get an updated model.
*/
open class BookmarkItem: BookmarkNode {
open let url: String!
public init(guid: String, title: String, url: String, isEditable: Bool=false) {
self.url = url
super.init(guid: guid, title: title, isEditable: isEditable)
}
}
/**
* A folder is an immutable abstraction over a named
* thing that can return its child nodes by index.
*/
open class BookmarkFolder: BookmarkNode {
open var count: Int { return 0 }
open subscript(index: Int) -> BookmarkNode? { return nil }
open func itemIsEditableAtIndex(_ index: Int) -> Bool {
return self[index]?.canDelete ?? false
}
override open var canDelete: Bool {
return false
}
open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? {
return nil
}
}
/**
* A model is a snapshot of the bookmarks store, suitable for backing a table view.
*
* Navigation through the folder hierarchy produces a sequence of models.
*
* Changes to the backing store implicitly invalidates a subset of models.
*
* 'Refresh' means requesting a new model from the store.
*/
open class BookmarksModel: BookmarksModelFactorySource {
fileprivate let factory: BookmarksModelFactory
open let modelFactory: Deferred<Maybe<BookmarksModelFactory>>
open let current: BookmarkFolder
public init(modelFactory: BookmarksModelFactory, root: BookmarkFolder) {
self.factory = modelFactory
self.modelFactory = deferMaybe(modelFactory)
self.current = root
}
/**
* Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist.
*/
open func selectFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> {
return self.factory.modelForFolder(folder)
}
/**
* Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist.
*/
open func selectFolder(_ guid: String) -> Deferred<Maybe<BookmarksModel>> {
return self.factory.modelForFolder(guid)
}
/**
* Produce a new model rooted at the base of the hierarchy. Should never fail.
*/
open func selectRoot() -> Deferred<Maybe<BookmarksModel>> {
return self.factory.modelForRoot()
}
/**
* Produce a new model with a memory-backed root with the given GUID removed from the current folder
*/
open func removeGUIDFromCurrent(_ guid: GUID) -> BookmarksModel {
if let removedRoot = self.current.removeItemWithGUID(guid) {
return BookmarksModel(modelFactory: self.factory, root: removedRoot)
}
log.warning("BookmarksModel.removeGUIDFromCurrent did not remove anything. Check to make sure you're not using the abstract BookmarkFolder class.")
return self
}
/**
* Produce a new model rooted at the same place as this model. Can fail if
* the folder has been deleted from the backing store.
*/
open func reloadData() -> Deferred<Maybe<BookmarksModel>> {
return self.factory.modelForFolder(current)
}
open var canDelete: Bool {
return false
}
}
public protocol BookmarksModelFactorySource {
var modelFactory: Deferred<Maybe<BookmarksModelFactory>> { get }
}
public protocol BookmarksModelFactory {
func modelForFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>>
func modelForFolder(_ guid: GUID) -> Deferred<Maybe<BookmarksModel>>
func modelForFolder(_ guid: GUID, title: String) -> Deferred<Maybe<BookmarksModel>>
func modelForRoot() -> Deferred<Maybe<BookmarksModel>>
// Whenever async construction is necessary, we fall into a pattern of needing
// a placeholder that behaves correctly for the period between kickoff and set.
var nullModel: BookmarksModel { get }
func isBookmarked(_ url: String) -> Deferred<Maybe<Bool>>
func removeByGUID(_ guid: GUID) -> Success
@discardableResult func removeByURL(_ url: String) -> Success
}
/*
* A folder that contains an array of children.
*/
open class MemoryBookmarkFolder: BookmarkFolder, Sequence {
let children: [BookmarkNode]
public init(guid: GUID, title: String, children: [BookmarkNode]) {
self.children = children
super.init(guid: guid, title: title)
}
public struct BookmarkNodeGenerator: IteratorProtocol {
public typealias Element = BookmarkNode
let children: [BookmarkNode]
var index: Int = 0
init(children: [BookmarkNode]) {
self.children = children
}
public mutating func next() -> BookmarkNode? {
if index < children.count {
defer { index += 1 }
return children[index]
}
return nil
}
}
override open var favicon: Favicon? {
get {
if let path = Bundle.main.path(forResource: "bookmarkFolder", ofType: "png") {
let url = URL(fileURLWithPath: path)
return Favicon(url: url.absoluteString, date: Date(), type: IconType.local)
}
return nil
}
set {
}
}
override open var count: Int {
return children.count
}
override open subscript(index: Int) -> BookmarkNode {
get {
return children[index]
}
}
override open func itemIsEditableAtIndex(_ index: Int) -> Bool {
return true
}
override open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? {
let without = children.filter { $0.guid != guid }
return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: without)
}
open func makeIterator() -> BookmarkNodeGenerator {
return BookmarkNodeGenerator(children: self.children)
}
/**
* Return a new immutable folder that's just like this one,
* but also contains the new items.
*/
func append(_ items: [BookmarkNode]) -> MemoryBookmarkFolder {
if items.isEmpty {
return self
}
return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: self.children + items)
}
}
open class MemoryBookmarksSink: ShareToDestination {
var queue: [BookmarkNode] = []
public init() { }
open func shareItem(_ item: ShareItem) -> Success {
let title = item.title == nil ? "Untitled" : item.title!
func exists(_ e: BookmarkNode) -> Bool {
if let bookmark = e as? BookmarkItem {
return bookmark.url == item.url
}
return false
}
// Don't create duplicates.
if !queue.contains(where: exists) {
queue.append(BookmarkItem(guid: Bytes.generateGUID(), title: title, url: item.url))
}
return succeed()
}
}
private extension SuggestedSite {
func asBookmark() -> BookmarkNode {
let b = BookmarkItem(guid: self.guid ?? Bytes.generateGUID(), title: self.title, url: self.url)
b.favicon = self.icon
return b
}
}
open class PrependedBookmarkFolder: BookmarkFolder {
fileprivate let main: BookmarkFolder
fileprivate let prepend: BookmarkNode
init(main: BookmarkFolder, prepend: BookmarkNode) {
self.main = main
self.prepend = prepend
super.init(guid: main.guid, title: main.guid)
}
override open var count: Int {
return self.main.count + 1
}
override open subscript(index: Int) -> BookmarkNode? {
if index == 0 {
return self.prepend
}
return self.main[index - 1]
}
override open func itemIsEditableAtIndex(_ index: Int) -> Bool {
return index > 0 && self.main.itemIsEditableAtIndex(index - 1)
}
override open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? {
guard let removedFolder = main.removeItemWithGUID(guid) else {
log.warning("Failed to remove child item from prepended folder. Check that main folder overrides removeItemWithGUID.")
return nil
}
return PrependedBookmarkFolder(main: removedFolder, prepend: prepend)
}
}
/**
* A trivial offline model factory that represents a simple hierarchy.
*/
open class MockMemoryBookmarksStore: BookmarksModelFactory, ShareToDestination {
let mobile: MemoryBookmarkFolder
let root: MemoryBookmarkFolder
var unsorted: MemoryBookmarkFolder
let sink: MemoryBookmarksSink
public init() {
let res = [BookmarkItem]()
mobile = MemoryBookmarkFolder(guid: BookmarkRoots.MobileFolderGUID, title: "Mobile Bookmarks", children: res)
unsorted = MemoryBookmarkFolder(guid: BookmarkRoots.UnfiledFolderGUID, title: "Unsorted Bookmarks", children: [])
sink = MemoryBookmarksSink()
root = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [mobile, unsorted])
}
open func modelForFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> {
return self.modelForFolder(folder.guid, title: folder.title)
}
open func modelForFolder(_ guid: GUID) -> Deferred<Maybe<BookmarksModel>> {
return self.modelForFolder(guid, title: "")
}
open func modelForFolder(_ guid: GUID, title: String) -> Deferred<Maybe<BookmarksModel>> {
var m: BookmarkFolder
switch guid {
case BookmarkRoots.MobileFolderGUID:
// Transparently merges in any queued items.
m = self.mobile.append(self.sink.queue)
break
case BookmarkRoots.RootGUID:
m = self.root
break
case BookmarkRoots.UnfiledFolderGUID:
m = self.unsorted
break
default:
return deferMaybe(DatabaseError(description: "No such folder \(guid)."))
}
return deferMaybe(BookmarksModel(modelFactory: self, root: m))
}
open func modelForRoot() -> Deferred<Maybe<BookmarksModel>> {
return deferMaybe(BookmarksModel(modelFactory: self, root: self.root))
}
/**
* This class could return the full data immediately. We don't, because real DB-backed code won't.
*/
open var nullModel: BookmarksModel {
let f = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [])
return BookmarksModel(modelFactory: self, root: f)
}
open func shareItem(_ item: ShareItem) -> Success {
return self.sink.shareItem(item)
}
open func isBookmarked(_ url: String) -> Deferred<Maybe<Bool>> {
return deferMaybe(DatabaseError(description: "Not implemented"))
}
open func removeByGUID(_ guid: GUID) -> Success {
return deferMaybe(DatabaseError(description: "Not implemented"))
}
open func removeByURL(_ url: String) -> Success {
return deferMaybe(DatabaseError(description: "Not implemented"))
}
open func clearBookmarks() -> Success {
return succeed()
}
}