Files
divkit/client/ios/Core/CommonCore/RemoteImageView.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

235 lines
6.0 KiB
Swift

// Copyright 2015 Yandex LLC. All rights reserved.
import UIKit
import Base
public final class RemoteImageView: UIView {
public struct Animation {
let duration: Double
let delay: Double
let startAlpha: Double
let endAlpha: Double
let options: UIView.AnimationOptions
public init(
duration: Double,
delay: Double,
startAlpha: Double,
endAlpha: Double,
options: UIView.AnimationOptions
) {
self.duration = duration
self.delay = delay
self.startAlpha = startAlpha
self.endAlpha = endAlpha
self.options = options
}
}
private let contentsLayer = CALayer()
private lazy var clipMask: CALayer = {
let mask = CALayer()
mask.backgroundColor = UIColor.white.cgColor
return mask
}()
var imageRequest: Cancellable?
public var imageHolder: ImageHolder? {
didSet {
imageRequest?.cancel()
setImage(nil, animated: false)
switch imageHolder?.placeholder {
case let .color(color)?:
backgroundColor = color.systemColor
case .none, .image?:
backgroundColor = nil
}
let newValue = imageHolder
imageRequest = imageHolder?.requestImageWithSource { [weak self] result in
guard let self = self,
newValue === self.imageHolder else {
return
}
self.setImage(result?.0, animated: result?.1.shouldAnimate)
self.backgroundColor = nil
}
}
}
public var appearanceAnimation: Animation?
private var templateLayer: CALayer?
private func updateContent() {
let content = Content(
image: image,
imageRedrawingColor: imageRedrawingColor
)
let gravity = imageContentMode
.contentsGravity(isGeometryFlipped: contentsLayer.contentsAreFlipped())
CATransaction.performWithoutAnimations {
switch content {
case let .plain(image):
contentsLayer.setContents(image)
contentsLayer.contentsGravity = gravity
contentsLayer.backgroundColor = nil
contentsLayer.mask = nil
templateLayer = nil
case let .template(image, color):
contentsLayer.setContents(nil)
contentsLayer.contentsGravity = .resize
contentsLayer.backgroundColor = color.cgColor
let template = templateLayer ?? CALayer()
template.setContents(image)
template.contentsGravity = gravity
contentsLayer.mask = template
templateLayer = template
}
}
setNeedsLayout()
}
private func setImage(_ image: UIImage?, animated: Bool?) {
self.image = image
if let appearanceAnimation = appearanceAnimation, animated == true {
self.alpha = appearanceAnimation.startAlpha
updateContent()
UIView.animate(
withDuration: appearanceAnimation.duration,
delay: appearanceAnimation.delay,
options: appearanceAnimation.options,
animations: { self.alpha = appearanceAnimation.endAlpha },
completion: nil
)
} else {
updateContent()
}
}
private var image: UIImage?
public var imageRedrawingColor: Color? {
didSet { updateContent() }
}
public var imageContentMode = ImageContentMode.default {
didSet { updateContent() }
}
public override init(frame: CGRect) {
super.init(frame: frame)
layer.addSublayer(contentsLayer)
}
@available(*, unavailable)
public required init?(coder _: NSCoder) {
fatalError()
}
public override func layoutSubviews() {
super.layoutSubviews()
CATransaction.performWithoutAnimations {
let layout = ImageLayerLayout(
contentMode: imageContentMode,
contentSize: image?.size ?? .zero,
boundsSize: bounds.size,
capInsets: image?.capInsets ?? .zero
)
contentsLayer.frame = layout.frame
contentsLayer.contentsRect = layout.contentRect
contentsLayer.contentsCenter = layout.contentCenter
templateLayer?.frame = contentsLayer.bounds
templateLayer?.contentsRect = layout.contentRect
templateLayer?.contentsCenter = layout.contentCenter
updateMask()
}
}
private func updateMask() {
let contentsHeight = templateLayer?.contentsRect.height ?? contentsLayer.contentsRect.height
// MOBYANDEXIOS-376: for now, coded the layout only for top-directed content collapsing
if contentsHeight > 1.0 {
clipMask.frame = CGRect(
x: 0,
y: 0,
width: bounds.width,
height: layer.bounds.height / contentsHeight
)
layer.mask = clipMask
} else if layer.mask != nil {
layer.mask = nil
}
layer.masksToBounds = true
}
deinit {
imageRequest?.cancel()
}
}
extension UIImage.Orientation {
fileprivate var layerTransform: CGAffineTransform {
switch self {
case .up:
return .identity
case .upMirrored:
return CGAffineTransform(scaleX: -1, y: 1)
case .down:
return CGAffineTransform(rotationAngle: .pi)
case .downMirrored:
return CGAffineTransform(rotationAngle: .pi).scaledBy(x: -1, y: 1)
case .left:
return CGAffineTransform(rotationAngle: -.pi / 2)
case .leftMirrored:
return CGAffineTransform(rotationAngle: -.pi / 2).scaledBy(x: -1, y: 1)
case .right:
return CGAffineTransform(rotationAngle: .pi / 2)
case .rightMirrored:
return CGAffineTransform(rotationAngle: .pi / 2).scaledBy(x: -1, y: 1)
@unknown default:
return .identity
}
}
}
extension CALayer {
fileprivate func setContents(_ source: Image?) {
contents = source?.cgImage
contentsScale = source?.scale ?? 1
setAffineTransform(source?.imageOrientation.layerTransform ?? .identity)
}
}
private enum Content {
case plain(Image?)
case template(Image, color: Color)
init(image: Image?, imageRedrawingColor: Color?) {
if let image = image, let color = imageRedrawingColor {
self = .template(image, color: color)
} else {
self = .plain(image)
}
}
}
extension URLRequestResult.Source {
var shouldAnimate: Bool {
switch self {
case .network: return true
case .cache: return false
}
}
}