-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[SDK-511] New methods in MapGL #18
[SDK-511] New methods in MapGL #18
Conversation
maxal9999
commented
Apr 8, 2021
•
edited
Loading
edited
- FloorPlan and Map.floorPlan
- Map.padding
- GeographicalBounds.extend
- Map.setStyleState and Map.patchStyleState
- isSupported, notSupportedReason
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Желательно поправить
Sources/MapGL/Model/FloorPlan.swift
Outdated
|
||
public class FloorPlan { | ||
private var _currentLevelIndex: Int = 0 | ||
private let onLevelChanged: (Int) -> Void |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
private желательно под public по уровню доступа
Sources/MapGL/Model/FloorPlan.swift
Outdated
return _currentLevelIndex | ||
} | ||
set { | ||
guard newValue >= 0 && newValue < levels.count else { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
self.levels тоже желательно тут и ниже, для единообразия
|
||
///Extend the bounds to include a given point. | ||
public func extend(point: CLLocationCoordinate2D) -> GeographicalBounds { | ||
return GeographicalBounds( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
return self.extend(points: [point])?
import Combine | ||
import Foundation | ||
|
||
public class FloorPlan { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
комбайн с 13 iOS а мы поддерживаем с 10, нужно обмазать @available(iOS 13.0, *) как минимум
никакой документации нет, нужно класс и пропрертя публичные обмазать документацией
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Комбайн не нужен тут - я его уберу.
return | ||
"{" + | ||
(self.map({ (key, value) -> String in | ||
return "\"\(key)\": \(value)"}) as Array).joined(separator: ",") + |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
очень тяжело читается,
давай так перепишем
let dictionary = self.map { (key, value) -> String in
"""
"\(key)": \(value)
"""
}.joined(separator: ",")
return "{" + dictionary + "}"
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Там ещё, выше по коду, есть IJSOptions
, в котором делается то же самое :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
не, там не экранируется ключ, а так, да очень похоже)
Sources/MapGL/Model/FloorPlan.swift
Outdated
self.id = id | ||
self.levels = levels | ||
self._currentLevelIndex = currentLevelIndex | ||
self.currentLevel = LiveData<String>(levels[currentLevelIndex]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
нет защиты от currentLevelIndex > levels.count
Sources/MapGL/Model/Padding.swift
Outdated
public var bottom: CGFloat = 0.0 | ||
public var left: CGFloat = 0.0 | ||
public var right: CGFloat = 0.0 | ||
public var top: CGFloat = 0.0 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно еще публичный init для удобства
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Сделал
Sources/MapGL/Model/LiveData.swift
Outdated
@@ -0,0 +1,21 @@ | |||
import Foundation | |||
|
|||
public class LiveData<T> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мимо проходил.
LiveData - стандартный класс из Android, в iOS он будет чуждым, лучше было бы использовать то что принято на платформе/в проекте.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, я сделал некий аналог класс-обертку. в iOS я нашел Observable, но он доступен только с iOS 13.
А моя реализация сделана на основе didSet, который стандартный iOS-сный.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Думаю тебе с Женей нужно решить, как быть - написание своего observable-типа - непустяковое дело.
Если возможности iOS 13 недоступны, то может обойтись тогда колбеками, как сделано с MapView.centerDidChange, MapView.zoomDidChange.
По сравнению с Android-овской у твоей LiveData есть недостатки, делающие использование неочевидным/опасным -
- value можно устанавливать снаружи, нарушая инкапсуляцию (в Android против этого есть разделение на LiveData/MutableLiveData)
- нет поддержки нескольких слушателей
- нельзя задать поток срабатывания callback-a (в Android тоже нельзя, но там срабатывание передается на UI-поток, что для простых случаев годится)
- установка значения непотокобезопасная
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Понял, спасибо, буду обсуждать тогда.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Сделаю все таки колбеками. Так лучше будет, действительно.
/// The amount of padding in pixels to add to the given bounds. | ||
public var padding: Padding? | ||
|
||
public init() {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
лучше убрать init и переписать
public init(considerRotation: Bool = false, padding: Padding? = nil) {
self.considerRotation = considerRotation
self.padding = padding
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Действительно, так и правда лучше
public var considerRotation: Bool = false | ||
|
||
/// The amount of padding in pixels to add to the given bounds. | ||
public var padding: Padding? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
кажется это лучше сделать через let,
public let considerRotation: Bool
public let padding: Padding?
так как выставление этих параметров ни на что не влияет и лучше эту структуру создавать только через конструктор
Sources/MapGL/Model/Padding.swift
Outdated
public var right: CGFloat = 0.0 | ||
public var top: CGFloat = 0.0 | ||
|
||
public init() {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тут тоже лучше удалить init и сделать один с defaultValues
@@ -16,6 +16,31 @@ public struct GeographicalBounds: Decodable { | |||
self.northEast = northEast | |||
self.southWest = southWest | |||
} | |||
|
|||
///Extend the bounds to include a given point. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
/// [пробел] Extend the bounds to include a given point.
без пробела это некорректная документация, которая не распарсится нашей утилитой
} | ||
|
||
///Extend the bounds to include given points. | ||
public func extend(points: [CLLocationCoordinate2D]) -> GeographicalBounds { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
пробел после ///
|
||
/// Tests whether the current browser supports MapGL and returns the reason if not | ||
public func notSupportedReason(options: MapSupportOptions? = nil) -> String? { | ||
if options?.failIfMajorPerformanceCaveat == true { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
я пытался понять логику, и не до конца понял, вот я хочу проверить совместимость, создам
MapView вызову этот метод до инициализации карты, и он мне вернет true,
я создаю карту, и она по итогу не создается кажется это не ожидаемое поведение
я точно не знаю как это работает, но кажется нужно возвращать этот статус как результат инициализации карты, кажется только в этот момент мы можем точно быть уверены что у нас все корректно отработает
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
этот вопрос так и остался без ответа
Example/HelloSDK/HelloVC.swift
Outdated
@@ -97,6 +104,17 @@ final class HelloVC: UIViewController { | |||
self?.mapPitchLabel.text = "Map pitch: \(pitch)" | |||
} | |||
|
|||
self.map.floorPlanChange = { [weak self] currentLevelIndex in | |||
if let currentLevelIndex = currentLevelIndex { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Думаю, по смыслу нужно объединить проверки у первого и второго if-а. Пишется через запятую.
Example/HelloSDK/HelloVC.swift
Outdated
self.map.floorPlanChange = { [weak self] currentLevelIndex in | ||
if let currentLevelIndex = currentLevelIndex { | ||
if self?.map.floorPlan?.currentLevelIndex == currentLevelIndex { | ||
self?.mapFloorPlanLabel.text = "Floor plan \(currentLevelIndex) shows." |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
self?.mapFloorPlanLabel.text = "Floor plan \(currentLevelIndex) shows." | |
self?.mapFloorPlanLabel.text = "Floor plan: \(currentLevelIndex)" |
Example/HelloSDK/HelloVC.swift
Outdated
} | ||
} | ||
else { | ||
self?.mapFloorPlanLabel.text = "Floor plan hides." |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
self?.mapFloorPlanLabel.text = "Floor plan hides." | |
self?.mapFloorPlanLabel.text = "Floor plan: hidden" |
@@ -93,3 +93,14 @@ extension CGSize: IJSValue { | |||
extension CGPoint: IJSValue { | |||
func jsValue() -> String { "[\(self.x),\(self.y)]" } | |||
} | |||
|
|||
extension Dictionary: IJSValue where Key: ExpressibleByStringLiteral, Value: IJSValue { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А зачем ExpressibleByStringLiteral
? Это же не используется в тексте функции.
Sources/MapGL/JSBridge.swift
Outdated
|
||
func setStyleState(styleState: [String: Bool]) { | ||
let js = """ | ||
window.setStyleState(\(styleState.mapValues { value in value.jsValue() }.jsValue())); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вытащи наружу выражение в \(...)
. Приходится вчитываться, чтобы рассмотреть суть.
|
||
/// Options for Map.isSupported method. | ||
public struct MapSupportOptions { | ||
/// Causes isSupported method to return false if the performance of MapGL would be |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
/// Causes isSupported method to return false if the performance of MapGL would be | |
/// Causes `isSupported` to return false if performance of MapGL would be |
Sources/MapGL/Model/Padding.swift
Outdated
@@ -0,0 +1,29 @@ | |||
import Foundation | |||
|
|||
/// Padding in density independent pixels from the different sides of the map canvas. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
То есть в логических точках?
/// Padding in density independent pixels from the different sides of the map canvas. | |
/// Padding in points from the different sides of the map canvas. |
Sources/MapGL/Model/Padding.swift
Outdated
public var right: CGFloat = 0.0 | ||
public var top: CGFloat = 0.0 | ||
|
||
public init() {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лишний конструктор. Нужно было сделать = 0
значениями по умолчанию в следующем.
Sources/MapGL/Model/Padding.swift
Outdated
|
||
/// Padding in density independent pixels from the different sides of the map canvas. | ||
public struct Padding { | ||
public var bottom: CGFloat = 0.0 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лишняя инициализация. Конструктор всё сделает сам.
|
||
extension Dictionary: IJSValue where Key: ExpressibleByStringLiteral, Value: IJSValue { | ||
func jsValue() -> String { | ||
let dictionary = self.map { (key, value) -> String in |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Имя не очень хорошее. По сути это не словарь, а ключи-значения через запятую. Переименуй в keyValues
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот со скобками уже словарь.
self.map.floorPlanDidChange = { [weak self] currentLevelIndex in | ||
if let currentLevelIndex = currentLevelIndex, | ||
self?.map.floorPlan?.currentLevelIndex == currentLevelIndex { | ||
self?.mapFloorPlanLabel.text = "Floor plan: \(currentLevelIndex)" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут лишний отступ. Не нужно стесняться, что строки сливаются. Если в общепринятом стиле есть проблемы, пусть все это видят. :)
self?.mapFloorPlanLabel.text = "Floor plan: \(currentLevelIndex)" | |
self?.mapFloorPlanLabel.text = "Floor plan: \(currentLevelIndex)" |
@@ -97,6 +104,16 @@ final class HelloVC: UIViewController { | |||
self?.mapPitchLabel.text = "Map pitch: \(pitch)" | |||
} | |||
|
|||
self.map.floorPlanDidChange = { [weak self] currentLevelIndex in | |||
if let currentLevelIndex = currentLevelIndex, | |||
self?.map.floorPlan?.currentLevelIndex == currentLevelIndex { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В новом икскоде стали странно выравнивать. Получается смесь пробелов и табов. Не буду просить это править.
Sources/MapGL/JSBridge.swift
Outdated
|
||
func patchStyleState(styleState: [String: Bool]) { | ||
let js = """ | ||
window.patchStyleState(\(styleState.mapValues { value in value.jsValue() }.jsValue())); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут тоже хотелось бы сделать читаемее. На твоё уже усмотрение.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, точно. По аналогии же нужно. Как я проглядел(
Sources/MapGL/JSBridge.swift
Outdated
|
||
func fitBounds(bounds: GeographicalBounds, options: FitBoundsOptions?) { | ||
let js = """ | ||
window.fitBounds(\(bounds.jsValue()), \((options != nil) ? options.jsValue() : "null")); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вынеси наружу и убери лишние скобки вокруг условия.
Sources/MapGL/JSBridge.swift
Outdated
|
||
func fitBounds(bounds: GeographicalBounds, options: FitBoundsOptions?) { | ||
let js = """ | ||
window.fitBounds(\(bounds.jsValue()), \((options != nil) ? options.jsValue() : "null")); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут интересно. Раз вызываешь options.jsValue
, значит Optional<FitBoundsOptions>
тоже реализует IJSValue
. Тогда он дожен сам превращаться в "null"
из nil
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А, уже есть
extension Optional: IJSValue where Wrapped: IJSValue {
Так что можно оставить просто options.jsValue()
Sources/MapGL/JSBridge.swift
Outdated
let data = body["value"] as? [String: String?] | ||
let notSupportedReason = data?["notSupportedReason"] as? String | ||
let notSupportedWithGoodPerformanceReason = data?["notSupportedWithGoodPerformanceReason"] as? String | ||
delegate.js(self, supportedReason: notSupportedReason, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В другом месте уже иначе переносишь:
self._support = MapSupport(
notSupportedReason: notSupportedReason,
notSupportedWithGoodPerformanceReason: notSupportedWithGoodPerformanceReason
)
Пусть тут будет так же.
@@ -21,6 +21,11 @@ public class MapView : UIView { | |||
static let mapDefaultCenter = CLLocationCoordinate2D(latitude: 55.750574, longitude: 37.618317) | |||
} | |||
|
|||
struct MapSupport { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
На практике могут оба поля быть ненулевыми? Enum бы тут подошёл?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, конечно могут. Даже больше - в основном одновременно и будут ненулевыми.
|
||
/// Tests whether the current browser supports MapGL. | ||
/// Use our raster map implementation https://api.2gis.ru/doc/maps/en/quickstart/ if not. | ||
public func isSupported(options: MapSupportOptions? = nil) -> Bool? { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не хватает документации на возвращаемое значение. Что означает nil
?
Sources/MapGL/MapView.swift
Outdated
@@ -75,6 +85,10 @@ public class MapView : UIView { | |||
public var pitchDidChange: ((Double) -> Void)? | |||
/// Notifies of the map click event. | |||
public var mapClick: ((CLLocationCoordinate2D) -> Void)? | |||
/// Notifies of the floor plan change. | |||
public var floorPlanDidChange: ((Int?) -> Void)? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А почему бы нам сразу всю структуру FloorPlan не отправить?
Sources/MapGL/Model/HTML.swift
Outdated
@@ -48,6 +48,9 @@ enum HTML { | |||
value: args | |||
}); | |||
}; | |||
|
|||
try { | |||
|
|||
var objects = new Map(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ага. Ещё хочу уточнить: а мы помельче try можем сделать? Интересная нам ошибка прямо откуда угодно вылетает?
c80a33e
to
0e4ccd1
Compare
} | ||
|
||
func setStyleState(styleState: [String: Bool]) { | ||
let styleState = styleState.mapValues { value in value.jsValue() }.jsValue() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно просто styleState.mapValues { $0.jsValue() }.jsValue()
} | ||
|
||
func patchStyleState(styleState: [String: Bool]) { | ||
let styleState = styleState.mapValues { value in value.jsValue() }.jsValue() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
можно просто styleState.mapValues { $0.jsValue() }.jsValue()
|
||
/// Tests whether the current browser supports MapGL and returns the reason if not | ||
public func notSupportedReason(options: MapSupportOptions? = nil) -> String? { | ||
if options?.failIfMajorPerformanceCaveat == true { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
этот вопрос так и остался без ответа