-
Notifications
You must be signed in to change notification settings - Fork 895
/
Copy pathBusinessLocationController.swift
411 lines (304 loc) · 13.1 KB
/
BusinessLocationController.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//
// BusinessLocationController.swift
// Telegram
//
// Created by Mikhail Filimonov on 12.02.2024.
// Copyright © 2024 Telegram. All rights reserved.
//
import Foundation
import TelegramCore
import Postbox
import Cocoa
import TGUIKit
import SwiftSignalKit
import MapKit
private final class AnnotationView : MKAnnotationView {
private let locationPin = ImageView()
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
self.wantsLayer = true
layer?.masksToBounds = false
locationPin.image = darkAppearance.icons.locationMapPin
locationPin.sizeToFit()
frame = CGRect(x: 0, y: 0, width: 60, height: 60)
wantsLayer = true
addSubview(locationPin)
update()
}
override var annotation: MKAnnotation? {
didSet {
update()
}
}
override func layout() {
super.layout()
locationPin.center()
locationPin.setFrameOrigin(NSMakePoint(locationPin.frame.minX, locationPin.frame.minY - locationPin.frame.height / 2))
}
private func update() {
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static var reuseIdentifier: String {
return "peer"
}
}
private class MapRowItem: GeneralRowItem {
let context: AccountContext
fileprivate let location: State.Location
init(_ initialSize: NSSize, height: CGFloat, stableId: AnyHashable, context: AccountContext, location: State.Location, viewType: GeneralViewType, action: @escaping()->Void) {
self.context = context
self.location = location
super.init(initialSize, height: height, stableId: stableId, viewType: viewType, action: action)
}
deinit {
}
override func viewClass() -> AnyClass {
return MapRowItemView.self
}
}
private final class MapRowItemView : GeneralContainableRowView, MKMapViewDelegate {
private let mapView: MKMapView = MKMapView()
private let overlay = Control()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(mapView)
mapView.register(AnnotationView.self, forAnnotationViewWithReuseIdentifier: AnnotationView.reuseIdentifier)
mapView.delegate = self
mapView.showsZoomControls = false
mapView.showsUserLocation = false
mapView.isZoomEnabled = false
mapView.isScrollEnabled = false
mapView.showsBuildings = false
addSubview(overlay)
overlay.set(handler: { [weak self] _ in
if let item = self?.item as? GeneralRowItem {
item.action()
}
}, for: .Click)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
mapView.delegate = nil
}
override func layout() {
super.layout()
mapView.frame = containerView.bounds
overlay.frame = containerView.bounds
}
func focusVenue() {
guard let item = item as? MapRowItem else {
return
}
let userLocation = item.location.coordinate
var region = MKCoordinateRegion()
var span = MKCoordinateSpan()
span.latitudeDelta = CLLocationDegrees(0.005)
span.longitudeDelta = CLLocationDegrees(0.005)
var location = CLLocationCoordinate2D()
location.latitude = userLocation.latitude
location.longitude = userLocation.longitude
region.span = span
region.center = location
mapView.setRegion(region, animated: false)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
switch annotation {
case is State.Location:
return mapView.dequeueReusableAnnotationView(withIdentifier: AnnotationView.reuseIdentifier, for: annotation)
default:
return nil
}
}
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
}
func mapViewDidStopLocatingUser(_ mapView: MKMapView) {
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
}
private var location: NSPoint? = nil
override func mouseUp(with event: NSEvent) {
super.mouseUp(with: event)
location = nil
}
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
location = event.locationInWindow
}
override func set(item: TableRowItem, animated: Bool = false) {
let previousItem = self.item
super.set(item: item, animated: animated)
layout()
guard let item = item as? MapRowItem else {
return
}
mapView.appearance = theme.appearance
mapView.addAnnotation(item.location)
focusVenue()
}
}
private final class Arguments {
let context: AccountContext
let setLocation:()->Void
let openMap:()->Void
let remove:()->Void
init(context: AccountContext, setLocation:@escaping()->Void, openMap:@escaping()->Void, remove:@escaping()->Void) {
self.context = context
self.setLocation = setLocation
self.openMap = openMap
self.remove = remove
}
}
private struct State : Equatable {
class Location : NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var venue: MapVenue?
init(coordinate: CLLocationCoordinate2D, venue: MapVenue?) {
self.coordinate = coordinate
self.venue = venue
}
}
var address: String?
var location: Location?
var initial: TelegramBusinessLocation?
var mapped: TelegramBusinessLocation? {
if let address = address, !address.isEmpty {
return .init(address: address, coordinates: location.map { .init(latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude) })
}
return nil
}
}
private let _id_header = InputDataIdentifier("_id_header")
private let _id_input = InputDataIdentifier("_id_enabled")
private let _id_map_enabled = InputDataIdentifier("_id_map_enabled")
private let _id_map_map = InputDataIdentifier("_id_map_enabled")
private let _id_remove = InputDataIdentifier("_id_remove")
private func entries(_ state: State, arguments: Arguments) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
var sectionId:Int32 = 0
var index: Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.custom(sectionId: sectionId, index: 0, value: .none, identifier: _id_header, equatable: nil, comparable: nil, item: { initialSize, stableId in
return AnimatedStickerHeaderItem(initialSize, stableId: stableId, context: arguments.context, sticker: LocalAnimatedSticker.business_location, text: .initialize(string: strings().businessLocationHeader, color: theme.colors.listGrayText, font: .normal(.text)))
}))
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.input(sectionId: sectionId, index: 0, value: .string(state.address), error: nil, identifier: _id_input, mode: .plain, data: .init(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().businessLocationEnterAddress, filter: { $0 }, limit: 96))
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.general(sectionId: sectionId, index: 0, value: .none, error: nil, identifier: _id_map_enabled, data: .init(name: strings().businessLocationSetOnMap, color: theme.colors.text, type: .switchable(state.location != nil), viewType: state.location != nil ? .firstItem : .singleItem, action: arguments.setLocation, autoswitch: false)))
if let location = state.location {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_map_map, equatable: .init(state.location), comparable: nil, item: { initialSize, stableId in
return MapRowItem(initialSize, height: 200, stableId: stableId, context: arguments.context, location: location, viewType: .lastItem, action: arguments.openMap)
}))
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.general(sectionId: sectionId, index: 0, value: .none, error: nil, identifier: _id_remove, data: .init(name: strings().businessLocationRemove, color: theme.colors.redUI, type: .none, viewType: .singleItem, action: arguments.setLocation, autoswitch: false)))
}
// entries
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func BusinessLocationController(context: AccountContext) -> InputDataController {
let actionsDisposable = DisposableSet()
let initialState = State()
let statePromise = ValuePromise<State>(ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((State) -> State) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
let chatInteraction = ChatInteraction(chatLocation: .peer(context.peerId), context: context)
let businessLocation = context.engine.data.get(TelegramEngine.EngineData.Item.Peer.BusinessLocation(id: context.peerId)) |> deliverOnMainQueue
actionsDisposable.add(businessLocation.start(next: { location in
updateState { current in
var current = current
current.address = location?.address
current.initial = location
if let coordinates = location?.coordinates {
current.location = .init(coordinate: .init(latitude: coordinates.latitude, longitude: coordinates.longitude), venue: nil)
}
return current
}
}))
chatInteraction.sendLocation = { location, venue in
let signal = reverseGeocodeLocation(latitude: location.latitude, longitude: location.longitude) |> deliverOnMainQueue
if stateValue.with({ $0.address == nil || $0.address!.isEmpty }) {
_ = signal.startStandalone(next: { value in
updateState { current in
var current = current
current.address = value?.fullAddress
return current
}
})
}
updateState { current in
var current = current
current.location = .init(coordinate: location, venue: venue)
return current
}
}
let arguments = Arguments(context: context, setLocation: {
let value = stateValue.with { $0.location }
if value != nil {
updateState { current in
var current = current
current.location = nil
return current
}
} else {
showModal(with: LocationModalController(chatInteraction, destination: .business(value?.coordinate)), for: context.window)
}
}, openMap: {
showModal(with: LocationModalController(chatInteraction, destination: .business(stateValue.with { $0.location?.coordinate })), for: context.window)
}, remove: {
updateState { current in
var current = current
current.location = nil
current.address = nil
return current
}
})
let signal = statePromise.get() |> deliverOnPrepareQueue |> map { state in
return InputDataSignalValue(entries: entries(state, arguments: arguments))
}
let controller = InputDataController(dataSignal: signal, title: strings().businessLocationTitle, removeAfterDisappear: false, hasDone: true, identifier: "business_location")
controller.updateDatas = { datas in
updateState { current in
var current = current
current.address = datas[_id_input]?.stringValue
return current
}
return .none
}
controller.validateData = { data in
let state = stateValue.with { $0 }
if state.address == nil || state.address?.isEmpty == true, state.location != nil {
return .fail(.fields([_id_input : .shake]))
}
if state.initial != state.mapped {
_ = context.engine.accountData.updateAccountBusinessLocation(businessLocation: state.mapped).start()
showModalText(for: context.window, text: strings().businessUpdated)
return .success(.navigationBack)
}
return .none
}
controller.updateDoneValue = { data in
return { f in
let isEnabled = stateValue.with { $0.initial != $0.mapped }
if isEnabled {
f(.enabled(strings().navigationDone))
} else {
f(.disabled(strings().navigationDone))
}
}
}
controller.onDeinit = {
actionsDisposable.dispose()
}
return controller
}