Files
divkit/client/ios/DivKit/Variables/DivVariablesStorage.swift
T
divkit-github f1563c9890 chore(html-reporter): up version
Initial commit

Add notification for divkit

Allow overwrite for migration

[migration] browser/bitbucket/personal/booster/divkit

Note: mandatory check (NEED_CHECK) was skipped

DivKit files moved

dIVKIT-0: Fix ts builder build

update div-gallery visibility screenshots

update div-gallery visibility screens

a.yaml cleanup

updated codegen scripts

change gallery alignment

change internal types in expressions

removed copyrights

remove permissions

TemplatesSupportTests refactoring

Ничего не поменялось. Отрефакторил и почистил тесты.

Split package.json

send all public

removed yandex-team links

URL added type as ArgumentType

added camera permission description

safe area insets for errors count view

`EdgeInsets` for debug view with errors count. Needed for fullscreen divs. Naming corresponds to mapping `EdgeInsets` to div-variables.

Will be used here: https://nda.ya.ru/t/Lhr5Lxgb5KN6nX

fixed compiler warnings

fix DivKitComponents variables setup, add update func

fix DivKitComponents variables setup, add update func

authors clean up

Удалил коллег из инфраструктуры, тестирования и мессенджера. Половину людей я вообще тут не знаю. Список какой-то косячный, в нём, например, @booster и @askvortsov нет. Предлагаю заново вручную составить и записать туда тех, кто точно дивкитом занимался, а не просто мимо проходил.

Fix DivKit pods compilability

Fix DivKit pods compilability

use only english in demo app

translate divKit demo app russian text

Scroll when keyboard opened

Scroll when keyboard opened

Fix gallery scroll in a11y

Это копия пр-а, который я делал в репо алискита:

https://bitbucket.browser.yandex-team.ru/projects/ML/repos/mobile-alice-library-android/pull-requests/18808/overview

authors clean up2

SwiftGenerator

flake8 errors fix & ya.make edit

swift generation tests

swift references

swift generator implementation

init swift generator

code refactoring
1) rename to modeling
2) rename kind to PropertyType
3) delete apply_pluralization_rules
4) description default value is empty string
5) remove entity_type_field_alias, typename_alias, client_optional, profileEntities, ignore_properties, generate_plain_constructor
6) remove client prefix

Add XcodeBuild in ignore

Add XcodeBuild in ignore

introduce new global variable api

introduce new global variable api

Revert commit bdcbc0081395ebe44ed7fe24bf5f4b25569c6df0

LayoutKitSnapshotTests

Fix sandboxRelease dependencies.

support zero value for width and height

remove unused css variables

"CONTRIBUTING.md"

README draft

updated gitignore/arcignore

introduce color type in expressions

introduce color type in expressions

added xcconfig files

fixed swift formatting

fail tests if updating references

Чтобы уж точно не забыть вернуть False.

Layout changes

Fix expression parsing

don't change clickable state in a11y

don't change clickable state in a11y

Update items checks

Parse description references to translations

add licence file link

fixed expression properties generation

add ability to track requests to global variables

Добавляем в GlobalVariableController возможность подписаться на запросы к глобальным переменным.
Нужно дляОткрыт Накопительная палитра , а так же в целом полезная функциональность, через которую можно делать ленивый прогрев глобальных переменных

Changelog

Minor fixes

bump divkit version up to 3.0.0

fixed snapshot tests depdendencies

Иногда не запускалась сборка SnapshotTestsHostApp перед стартом тестов.

used new api-generator

deserialization refactoring

removed gitignore

samples text fixes

fixed samples text

remove theme button

remove theme button

demo activity redesign

demo activity redesign

habr sample app

change deleted images in screenshot tests

change deleted images in screenshot tests

new ic_launcher

new ic_launcher

more readme

Binding variable for div input

Biding variable for div input

Implement documentation generator

Rename max_lines to max_visible_lines

Rename max_lines to max_visible_lines

add habr and medium

fix div-functions doc

Fix link in description

Text selecting for demo app enabled

Text selecting for demo app enabled

KotlinGenerator

kotlin code generation

kotlin generation tests

kotlin generation references

add gradle wrapper to kotlin json builder

add gradle wrapper to kotlin json builder

DemoApp redesign

fixed codegen scripts

debugView safeAreaInsets

DebugView safe area insets

TypeScript Generator

ya.make changes

TypeScript generator

TypeScript tests

TypeScript test references

fix enumeration aliases

debugInfoParams fix compile

Fix black box flicker in video-custom

Fixed stub image showing by moving it away from PlayerView.
Increased stub loading speed by adding VideoViewModel warmup.
Fixed redundant redraws by combining stub visibility and
bitmap data.
PlayerView background was set to transparent.

DivExpression fix

DivExpression fix

Implement translations

Save & share

bind globalVariableController to divContext

bind variableController to divContext

used new TypeScript generator

Подключил генератор на питоне. Изменения в сгенерированных файлах связаны в основном с переводом описаний на английский язык.

moved LivePreview

Перенёс LivePreview из отдельного модуля в DivKitDemoApp. Добавил сканер кодов в UrlInputView. Удалил часть дублирующегося кода.

remove sms and phone_state permission

fix links interception

fix links interception

Fix link in documentation

remove site from "config.stable.json"

Support highlight_color and keyboardType in div input

Support highlight_color in div input

Action animation fix for iOS
2022-08-25 21:21:49 +03:00

327 lines
8.5 KiB
Swift

import Foundation
import CommonCore
public enum DivVariableNameTag {}
public typealias DivVariableName = Tagged<DivVariableNameTag, String>
public enum DivVariableValue: Equatable {
case string(String)
case number(Double)
case integer(Int)
case bool(Bool)
case color(Color)
case url(URL)
}
extension DivVariableValue: ExpressionResolverValueProvider {
public func typedValue<T>() -> T? {
switch self {
case let .string(value):
return value as? T
case let .number(value):
return value as? T
case let .integer(value):
return value as? T
case let .bool(value):
return value as? T
case let .color(value):
return value as? T
case let .url(value):
return value as? T
}
}
}
extension DivVariableValue {
fileprivate var typeName: String {
switch self {
case .string:
return "string"
case .number:
return "number"
case .integer:
return "integer"
case .bool:
return "bool"
case .color:
return "color"
case .url:
return "url"
}
}
}
public typealias DivVariables = [DivVariableName: DivVariableValue]
public final class DivVariablesStorage {
public struct Variables {
var global: DivVariables = [:]
var local: [DivCardID: DivVariables] = [:]
func makeVariables(for cardId: DivCardID) -> DivVariables {
global + (local[cardId] ?? [:])
}
}
public struct ChangeEvent {
public enum Kind: Equatable {
case local(DivCardID, Set<DivVariableName>)
case global(Set<DivVariableName>)
}
public struct VariablesValues {
public let old: Variables
public let new: Variables
init(
old: Variables,
new: Variables
) {
self.old = old
self.new = new
}
}
public let kind: Kind
public let variables: VariablesValues
init(kind: Kind, variables: VariablesValues) {
self.kind = kind
self.variables = variables
}
}
private let changeEventsPipe = SignalPipe<ChangeEvent>()
public var changeEvents: Signal<ChangeEvent> {
changeEventsPipe.signal
}
private var storage = Variables()
public init() {}
public func set(
cardId: DivCardID,
variables: DivVariables
) {
let oldVariables = storage
storage.local[cardId] = variables
let changedVariables = makeChangedVariables(
old: oldVariables.local[cardId] ?? [:],
new: variables
)
if changedVariables.isEmpty { return }
update(with: ChangeEvent(
kind: .local(cardId, changedVariables),
variables: ChangeEvent.VariablesValues(old: oldVariables, new: storage)
))
}
public func append(
variables newVariables: DivVariables,
for cardId: DivCardID,
replaceExisting: Bool
) {
let oldVariables = storage.local[cardId] ?? [:]
let resultVariables = replaceExisting ?
oldVariables + newVariables :
newVariables + oldVariables
set(cardId: cardId, variables: resultVariables)
}
public func set(
variables: DivVariables,
triggerUpdate: Bool
) {
let oldVariables = storage
storage.global = variables
if triggerUpdate {
let changedVariables = makeChangedVariables(old: oldVariables.global, new: variables)
if changedVariables.isEmpty { return }
update(with: ChangeEvent(
kind: .global(changedVariables),
variables: ChangeEvent.VariablesValues(old: oldVariables, new: storage)
))
}
}
public func append(
variables: DivVariables,
triggerUpdate: Bool
) {
set(variables: storage.global + variables, triggerUpdate: triggerUpdate)
}
public func makeVariables(for cardId: DivCardID) -> DivVariables {
storage.makeVariables(for: cardId)
}
private func update(with event: ChangeEvent) {
changeEventsPipe.send(event)
}
}
private func makeChangedVariables(
old: DivVariables,
new: DivVariables
) -> Set<DivVariableName> {
var result = Set<DivVariableName>()
for (name, value) in old {
if new[name] != value {
result.insert(name)
}
}
return result.union(Set(new.keys).subtracting(Set(old.keys)))
}
extension DivVariablesStorage: DivVariableUpdater {
public func update(
cardId: DivCardID,
name: DivVariableName,
value: String
) {
if let localValue = storage.local[cardId]?[name] {
let oldVariables = storage
let isUpdated = storage.local[cardId]?
.update(name: name, oldValue: localValue, value: value) ?? false
if isUpdated {
update(with: ChangeEvent(
kind: .local(cardId, [name]),
variables: ChangeEvent.VariablesValues(old: oldVariables, new: storage)
))
}
} else if let globalValue = storage.global[name] {
let oldVariables = storage
let isUpdated = storage.global.update(name: name, oldValue: globalValue, value: value)
if isUpdated {
update(with: ChangeEvent(
kind: .global([name]),
variables: ChangeEvent.VariablesValues(old: oldVariables, new: storage)
))
}
} else {
DivKitLogger.error("Variable is not declared: \(name)")
}
}
}
extension Dictionary where Key == DivVariableName, Value == DivVariableValue {
fileprivate mutating func update(
name: DivVariableName,
oldValue: DivVariableValue,
value: String
) -> Bool {
let newValue: DivVariableValue?
switch oldValue {
case .string:
newValue = .string(value)
case .number:
if let newNumber = Double(value) {
newValue = .number(newNumber)
} else {
newValue = nil
}
case .integer:
if let newInteger = Int(value) {
newValue = .integer(newInteger)
} else {
newValue = nil
}
case .bool:
if let newBool = Int(value) {
switch newBool {
case 0:
newValue = .bool(false)
case 1:
newValue = .bool(true)
default:
newValue = nil
}
} else {
newValue = nil
}
case .color:
if let newColor = Color.color(withHexString: value) {
newValue = .color(newColor)
} else {
newValue = nil
}
case .url:
if let newURL = URL(string: value) {
newValue = .url(newURL)
} else {
newValue = nil
}
}
if newValue == oldValue {
return false
}
if let newValue = newValue {
self[name] = newValue
return true
}
DivKitLogger.error("Incorrect value for variable \(name): \(value)")
return false
}
}
extension Collection where Element == DivVariable {
public func extractDivVariableValues() -> DivVariables {
var variables = DivVariables()
forEach { variable in
switch variable {
case let .stringVariable(stringVariable):
let name = DivVariableName(rawValue: stringVariable.name)
if variables.keys.contains(name) { return }
variables[name] = .string(stringVariable.value)
case let .numberVariable(numberVariable):
let name = DivVariableName(rawValue: numberVariable.name)
if variables.keys.contains(name) { return }
variables[name] = .number(numberVariable.value)
case let .integerVariable(integerVariable):
let name = DivVariableName(rawValue: integerVariable.name)
if variables.keys.contains(name) { return }
variables[name] = .integer(integerVariable.value)
case let .booleanVariable(booleanVariable):
let name = DivVariableName(rawValue: booleanVariable.name)
if variables.keys.contains(name) { return }
variables[name] = .bool(booleanVariable.value)
case let .colorVariable(colorVariable):
let name = DivVariableName(rawValue: colorVariable.name)
if variables.keys.contains(name) { return }
variables[name] = .color(colorVariable.value)
case let .urlVariable(urlVariable):
let name = DivVariableName(rawValue: urlVariable.name)
if variables.keys.contains(name) { return }
variables[name] = .url(urlVariable.value)
}
}
return variables
}
}
extension Dictionary where Key == String {
public func mapToDivVariables(
valueTransform: (Value) -> DivVariableValue
) -> DivVariables {
var divVariables = DivVariables()
forEach { element in
divVariables[DivVariableName(rawValue: element.key)]
= valueTransform(element.value)
}
return divVariables
}
}
extension Dictionary where Key == String, Value == Color {
public func mapToDivVariables() -> DivVariables {
mapToDivVariables(valueTransform: DivVariableValue.color)
}
}