Skip to content
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

Closed

Conversation

maxal9999
Copy link

@maxal9999 maxal9999 commented Apr 8, 2021

  • FloorPlan and Map.floorPlan
  • Map.padding
  • GeographicalBounds.extend
  • Map.setStyleState and Map.patchStyleState
  • isSupported, notSupportedReason

@maxal9999 maxal9999 changed the title [WIP][SDK-511] New method in MapGL [SDK-511] New method in MapGL Apr 9, 2021
@maxal9999 maxal9999 changed the title [SDK-511] New method in MapGL [SDK-511] New methods in MapGL Apr 9, 2021
@ktoto ktoto requested review from teanet and aapng April 12, 2021 06:24
Copy link
Contributor

@teanet teanet left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Желательно поправить


public class FloorPlan {
private var _currentLevelIndex: Int = 0
private let onLevelChanged: (Int) -> Void
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

private желательно под public по уровню доступа

return _currentLevelIndex
}
set {
guard newValue >= 0 && newValue < levels.count else {
Copy link
Contributor

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(
Copy link
Contributor

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 {
Copy link
Contributor

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, *) как минимум

никакой документации нет, нужно класс и пропрертя публичные обмазать документацией

Copy link
Author

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: ",") +
Copy link
Contributor

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 + "}"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Там ещё, выше по коду, есть IJSOptions, в котором делается то же самое :)

Copy link
Contributor

@teanet teanet Apr 12, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не, там не экранируется ключ, а так, да очень похоже)

self.id = id
self.levels = levels
self._currentLevelIndex = currentLevelIndex
self.currentLevel = LiveData<String>(levels[currentLevelIndex])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет защиты от currentLevelIndex > levels.count

public var bottom: CGFloat = 0.0
public var left: CGFloat = 0.0
public var right: CGFloat = 0.0
public var top: CGFloat = 0.0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

можно еще публичный init для удобства

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сделал

@@ -0,0 +1,21 @@
import Foundation

public class LiveData<T> {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мимо проходил.
LiveData - стандартный класс из Android, в iOS он будет чуждым, лучше было бы использовать то что принято на платформе/в проекте.

Copy link
Author

@maxal9999 maxal9999 Apr 12, 2021

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-сный.

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-поток, что для простых случаев годится)
  • установка значения непотокобезопасная

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Понял, спасибо, буду обсуждать тогда.

Copy link
Author

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() {}
Copy link
Contributor

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
 	}

Copy link
Author

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?
Copy link
Contributor

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?
так как выставление этих параметров ни на что не влияет и лучше эту структуру создавать только через конструктор

public var right: CGFloat = 0.0
public var top: CGFloat = 0.0

public init() {}
Copy link
Contributor

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.
Copy link
Contributor

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 {
Copy link
Contributor

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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я пытался понять логику, и не до конца понял, вот я хочу проверить совместимость, создам
MapView вызову этот метод до инициализации карты, и он мне вернет true,
я создаю карту, и она по итогу не создается кажется это не ожидаемое поведение

я точно не знаю как это работает, но кажется нужно возвращать этот статус как результат инициализации карты, кажется только в этот момент мы можем точно быть уверены что у нас все корректно отработает

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

этот вопрос так и остался без ответа

@@ -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 {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Думаю, по смыслу нужно объединить проверки у первого и второго if-а. Пишется через запятую.

self.map.floorPlanChange = { [weak self] currentLevelIndex in
if let currentLevelIndex = currentLevelIndex {
if self?.map.floorPlan?.currentLevelIndex == currentLevelIndex {
self?.mapFloorPlanLabel.text = "Floor plan \(currentLevelIndex) shows."
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self?.mapFloorPlanLabel.text = "Floor plan \(currentLevelIndex) shows."
self?.mapFloorPlanLabel.text = "Floor plan: \(currentLevelIndex)"

}
}
else {
self?.mapFloorPlanLabel.text = "Floor plan hides."
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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 {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем ExpressibleByStringLiteral? Это же не используется в тексте функции.


func setStyleState(styleState: [String: Bool]) {
let js = """
window.setStyleState(\(styleState.mapValues { value in value.jsValue() }.jsValue()));
Copy link

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
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Causes isSupported method to return false if the performance of MapGL would be
/// Causes `isSupported` to return false if performance of MapGL would be

@@ -0,0 +1,29 @@
import Foundation

/// Padding in density independent pixels from the different sides of the map canvas.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То есть в логических точках?

Suggested change
/// Padding in density independent pixels from the different sides of the map canvas.
/// Padding in points from the different sides of the map canvas.

public var right: CGFloat = 0.0
public var top: CGFloat = 0.0

public init() {}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лишний конструктор. Нужно было сделать = 0 значениями по умолчанию в следующем.


/// Padding in density independent pixels from the different sides of the map canvas.
public struct Padding {
public var bottom: CGFloat = 0.0
Copy link

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
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Имя не очень хорошее. По сути это не словарь, а ключи-значения через запятую. Переименуй в keyValues.

Copy link

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)"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут лишний отступ. Не нужно стесняться, что строки сливаются. Если в общепринятом стиле есть проблемы, пусть все это видят. :)

Suggested change
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 {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В новом икскоде стали странно выравнивать. Получается смесь пробелов и табов. Не буду просить это править.


func patchStyleState(styleState: [String: Bool]) {
let js = """
window.patchStyleState(\(styleState.mapValues { value in value.jsValue() }.jsValue()));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут тоже хотелось бы сделать читаемее. На твоё уже усмотрение.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, точно. По аналогии же нужно. Как я проглядел(


func fitBounds(bounds: GeographicalBounds, options: FitBoundsOptions?) {
let js = """
window.fitBounds(\(bounds.jsValue()), \((options != nil) ? options.jsValue() : "null"));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вынеси наружу и убери лишние скобки вокруг условия.


func fitBounds(bounds: GeographicalBounds, options: FitBoundsOptions?) {
let js = """
window.fitBounds(\(bounds.jsValue()), \((options != nil) ? options.jsValue() : "null"));
Copy link

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.

Copy link
Author

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()

let data = body["value"] as? [String: String?]
let notSupportedReason = data?["notSupportedReason"] as? String
let notSupportedWithGoodPerformanceReason = data?["notSupportedWithGoodPerformanceReason"] as? String
delegate.js(self, supportedReason: notSupportedReason,
Copy link

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 {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

На практике могут оба поля быть ненулевыми? Enum бы тут подошёл?

Copy link
Author

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? {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не хватает документации на возвращаемое значение. Что означает nil?

@@ -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)?
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему бы нам сразу всю структуру FloorPlan не отправить?

@@ -48,6 +48,9 @@ enum HTML {
value: args
});
};

try {

var objects = new Map();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ага. Ещё хочу уточнить: а мы помельче try можем сделать? Интересная нам ошибка прямо откуда угодно вылетает?

@maxal9999 maxal9999 force-pushed the feature-SDK-511-floor-plan-padding-lng-lat-bounds branch from c80a33e to 0e4ccd1 Compare April 15, 2021 22:24
}

func setStyleState(styleState: [String: Bool]) {
let styleState = styleState.mapValues { value in value.jsValue() }.jsValue()
Copy link
Contributor

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()
Copy link
Contributor

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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

этот вопрос так и остался без ответа

@maxal9999 maxal9999 closed this Apr 16, 2021
@maxal9999 maxal9999 deleted the feature-SDK-511-floor-plan-padding-lng-lat-bounds branch April 16, 2021 11:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants