Add text animation

This commit is contained in:
Ali 2022-12-30 17:18:55 +04:00
parent d8083e7c61
commit 012131397e
5 changed files with 274 additions and 26 deletions

View File

@ -0,0 +1,20 @@
load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library")
swift_library(
name = "AnimatedTextComponent",
module_name = "AnimatedTextComponent",
srcs = glob([
"Sources/**/*.swift",
]),
copts = [
"-warnings-as-errors",
],
deps = [
"//submodules/SSignalKit/SwiftSignalKit",
"//submodules/Display",
"//submodules/ComponentFlow",
],
visibility = [
"//visibility:public",
],
)

View File

@ -0,0 +1,190 @@
import Foundation
import UIKit
import Display
import ComponentFlow
public final class AnimatedTextComponent: Component {
public struct Item: Equatable {
public enum Content: Equatable {
case text(String)
case number(Int)
}
public var id: AnyHashable
public var isUnbreakable: Bool
public var content: Content
public init(id: AnyHashable, isUnbreakable: Bool = false, content: Content) {
self.id = id
self.isUnbreakable = isUnbreakable
self.content = content
}
}
public let font: UIFont
public let color: UIColor
public let items: [Item]
public init(
font: UIFont,
color: UIColor,
items: [Item]
) {
self.font = font
self.color = color
self.items = items
}
public static func ==(lhs: AnimatedTextComponent, rhs: AnimatedTextComponent) -> Bool {
if lhs.font != rhs.font {
return false
}
if lhs.color != rhs.color {
return false
}
if lhs.items != rhs.items {
return false
}
return true
}
private struct CharacterKey: Hashable {
var itemId: AnyHashable
var index: Int
var value: String
}
public final class View: UIView {
private var characters: [CharacterKey: ComponentView<Empty>] = [:]
private var component: AnimatedTextComponent?
private weak var state: EmptyComponentState?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder: NSCoder) {
preconditionFailure()
}
func update(component: AnimatedTextComponent, availableSize: CGSize, state: EmptyComponentState, environment: Environment<Empty>, transition: Transition) -> CGSize {
self.component = component
self.state = state
var size = CGSize()
let delayNorm: CGFloat = 0.002
var validKeys: [CharacterKey] = []
for item in component.items {
var itemText: [String] = []
switch item.content {
case let .text(text):
if item.isUnbreakable {
itemText = [text]
} else {
itemText = text.map(String.init)
}
case let .number(value):
if item.isUnbreakable {
itemText = ["\(value)"]
} else {
itemText = "\(value)".map(String.init)
}
}
var index = 0
for character in itemText {
let characterKey = CharacterKey(itemId: item.id, index: index, value: character)
index += 1
validKeys.append(characterKey)
var characterTransition = transition
let characterView: ComponentView<Empty>
if let current = self.characters[characterKey] {
characterView = current
} else {
characterTransition = .immediate
characterView = ComponentView()
self.characters[characterKey] = characterView
}
let characterSize = characterView.update(
transition: characterTransition,
component: AnyComponent(Text(
text: String(character),
font: component.font,
color: component.color
)),
environment: {},
containerSize: CGSize(width: 100.0, height: 100.0)
)
let characterFrame = CGRect(origin: CGPoint(x: size.width, y: 0.0), size: characterSize)
if let characterComponentView = characterView.view {
var animateIn = false
if characterComponentView.superview == nil {
self.addSubview(characterComponentView)
animateIn = true
}
if characterComponentView.frame != characterFrame {
if characterTransition.animation.isImmediate {
characterComponentView.frame = characterFrame
} else {
characterComponentView.bounds = CGRect(origin: CGPoint(), size: characterFrame.size)
let deltaPosition = CGPoint(x: characterFrame.midX - characterComponentView.frame.midX, y: characterFrame.midY - characterComponentView.frame.midY)
characterComponentView.center = characterFrame.center
characterComponentView.layer.animatePosition(from: CGPoint(x: -deltaPosition.x, y: -deltaPosition.y), to: CGPoint(), duration: 0.4, delay: delayNorm * size.width, timingFunction: kCAMediaTimingFunctionSpring, additive: true)
}
}
characterTransition.setFrame(view: characterComponentView, frame: characterFrame)
if animateIn, !transition.animation.isImmediate {
characterComponentView.layer.animateScale(from: 0.001, to: 1.0, duration: 0.4, delay: delayNorm * size.width, timingFunction: kCAMediaTimingFunctionSpring)
//characterComponentView.layer.animateSpring(from: (characterSize.height * 0.5) as NSNumber, to: 0.0 as NSNumber, keyPath: "position.y", duration: 0.5, additive: true)
characterComponentView.layer.animatePosition(from: CGPoint(x: 0.0, y: characterSize.height * 0.5), to: CGPoint(), duration: 0.4, delay: delayNorm * size.width, timingFunction: kCAMediaTimingFunctionSpring, additive: true)
characterComponentView.layer.animateAlpha(from: 0.0, to: 1.0, duration: 0.18, delay: delayNorm * size.width)
}
}
size.height = max(size.height, characterSize.height)
size.width += max(0.0, characterSize.width - UIScreenPixel * 2.0)
}
}
var removedKeys: [CharacterKey] = []
for (key, characterView) in self.characters {
if !validKeys.contains(key) {
removedKeys.append(key)
if let characterComponentView = characterView.view {
if !transition.animation.isImmediate {
characterComponentView.layer.animateScale(from: 1.0, to: 0.001, duration: 0.4, delay: delayNorm * characterComponentView.frame.minX, timingFunction: kCAMediaTimingFunctionSpring, removeOnCompletion: false)
characterComponentView.layer.animatePosition(from: CGPoint(), to: CGPoint(x: 0.0, y: -characterComponentView.bounds.height * 0.4), duration: 0.4, delay: delayNorm * characterComponentView.frame.minX, timingFunction: kCAMediaTimingFunctionSpring, removeOnCompletion: false, additive: true)
characterComponentView.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.18, delay: delayNorm * characterComponentView.frame.minX, removeOnCompletion: false, completion: { [weak characterComponentView] _ in
characterComponentView?.removeFromSuperview()
})
} else {
characterComponentView.removeFromSuperview()
}
}
}
}
for removedKey in removedKeys {
self.characters.removeValue(forKey: removedKey)
}
return size
}
}
public func makeView() -> View {
return View(frame: CGRect())
}
public func update(view: View, availableSize: CGSize, state: EmptyComponentState, environment: Environment<Empty>, transition: Transition) -> CGSize {
return view.update(component: self, availableSize: availableSize, state: state, environment: environment, transition: transition)
}
}

View File

@ -26,6 +26,7 @@ swift_library(
"//submodules/TelegramStringFormatting:TelegramStringFormatting",
"//submodules/PresentationDataUtils:PresentationDataUtils",
"//submodules/TelegramUI/Components/EmojiStatusComponent",
"//submodules/TelegramUI/Components/AnimatedTextComponent",
"//submodules/CheckNode",
"//submodules/Markdown",
"//submodules/ContextUI",

View File

@ -206,14 +206,18 @@ final class StorageCategoryItemComponent: Component {
iconView.removeFromSuperview()
}
let fractionValue: Double = floor(component.category.sizeFraction * 100.0 * 10.0) / 10.0
let fractionString: String
if fractionValue < 0.1 {
fractionString = "<0.1"
} else if abs(Double(Int(fractionValue)) - fractionValue) < 0.001 {
fractionString = "\(Int(fractionValue))"
if component.category.sizeFraction != 0.0 {
let fractionValue: Double = floor(component.category.sizeFraction * 100.0 * 10.0) / 10.0
if fractionValue < 0.1 {
fractionString = "<0.1%"
} else if abs(Double(Int(fractionValue)) - fractionValue) < 0.001 {
fractionString = "\(Int(fractionValue))%"
} else {
fractionString = "\(fractionValue)%"
}
} else {
fractionString = "\(fractionValue)"
fractionString = ""
}
let labelSize = self.label.update(
@ -225,8 +229,8 @@ final class StorageCategoryItemComponent: Component {
availableWidth = max(1.0, availableWidth - labelSize.width - 1.0)
let titleValueSize = self.titleValue.update(
transition: transition,
component: AnyComponent(MultilineTextComponent(text: .plain(NSAttributedString(string: "\(fractionString)%", font: Font.regular(17.0), textColor: component.theme.list.itemSecondaryTextColor)))),
transition: .immediate,
component: AnyComponent(MultilineTextComponent(text: .plain(NSAttributedString(string: fractionString, font: Font.regular(17.0), textColor: component.theme.list.itemSecondaryTextColor)))),
environment: {},
containerSize: CGSize(width: availableWidth, height: 100.0)
)
@ -266,7 +270,12 @@ final class StorageCategoryItemComponent: Component {
titleValueView.isUserInteractionEnabled = false
self.addSubview(titleValueView)
}
transition.setFrame(view: titleValueView, frame: titleValueFrame)
if titleValueView.bounds.size != titleValueFrame.size {
titleValueView.frame = titleValueFrame
} else {
transition.setFrame(view: titleValueView, frame: titleValueFrame)
}
}
if let labelView = self.label.view {
if labelView.superview == nil {

View File

@ -22,6 +22,7 @@ import AnimatedStickerNode
import TelegramAnimatedStickerNode
import TelegramStringFormatting
import GalleryData
import AnimatedTextComponent
#if DEBUG
import os.signpost
@ -1230,9 +1231,13 @@ final class StorageUsageScreenComponent: Component {
var listCategories: [StorageCategoriesComponent.CategoryData] = []
var totalSize: Int64 = 0
var totalSelectedCategorySize: Int64 = 0
if let aggregatedData = self.aggregatedData {
for (_, value) in aggregatedData.contextStats.categories {
for (key, value) in aggregatedData.contextStats.categories {
totalSize += value.size
if aggregatedData.selectedCategories.contains(Category(key)) {
totalSelectedCategorySize += value.size
}
}
for category in allCategories {
@ -1262,10 +1267,12 @@ final class StorageUsageScreenComponent: Component {
}
let categoryFraction: Double
if categorySize == 0 || totalSize == 0 {
if !aggregatedData.selectedCategories.contains(category) {
categoryFraction = 0.0
} else if categorySize == 0 || totalSelectedCategorySize == 0 {
categoryFraction = 0.0
} else {
categoryFraction = Double(categorySize) / Double(totalSize)
categoryFraction = Double(categorySize) / Double(totalSelectedCategorySize)
}
if categorySize != 0 {
@ -1275,15 +1282,13 @@ final class StorageUsageScreenComponent: Component {
}
}
listCategories.sort(by: { $0.sizeFraction > $1.sizeFraction })
listCategories.sort(by: { $0.size > $1.size })
var otherListCategories: [StorageCategoriesComponent.CategoryData] = []
if listCategories.count > 5 {
for i in (4 ..< listCategories.count).reversed() {
if listCategories[i].sizeFraction < 0.04 {
otherListCategories.insert(listCategories[i], at: 0)
listCategories.remove(at: i)
}
otherListCategories.insert(listCategories[i], at: 0)
listCategories.remove(at: i)
}
}
self.otherCategories = Set(otherListCategories.map(\.key))
@ -1303,12 +1308,7 @@ final class StorageUsageScreenComponent: Component {
}
if !otherListCategories.isEmpty {
let categoryFraction: Double
if totalOtherSize == 0 || totalSize == 0 {
categoryFraction = 0.0
} else {
categoryFraction = Double(totalOtherSize) / Double(totalSize)
}
let categoryFraction: Double = otherListCategories.reduce(0.0, { $0 + $1.sizeFraction })
let isSelected = otherListCategories.allSatisfy { item in
return self.aggregatedData?.selectedCategories.contains(item.key) ?? false
}
@ -1573,15 +1573,43 @@ final class StorageUsageScreenComponent: Component {
}
transition.setAlpha(view: chartAvatarNode.view, alpha: listCategories.isEmpty ? 0.0 : 1.0)
} else {
let sizeText = dataSizeString(Int(totalSelectedCategorySize), forceDecimal: true, formatting: DataSizeStringFormatting(strings: environment.strings, decimalSeparator: "."))
var animatedTextItems: [AnimatedTextComponent.Item] = []
var remainingSizeText = sizeText
if let index = remainingSizeText.firstIndex(of: ".") {
animatedTextItems.append(AnimatedTextComponent.Item(id: "n-full", content: .text(String(remainingSizeText[remainingSizeText.startIndex ..< index]))))
animatedTextItems.append(AnimatedTextComponent.Item(id: "dot", content: .text(".")))
remainingSizeText = String(remainingSizeText[remainingSizeText.index(after: index)...])
}
if let index = remainingSizeText.firstIndex(of: " ") {
animatedTextItems.append(AnimatedTextComponent.Item(id: "n-fract", content: .text(String(remainingSizeText[remainingSizeText.startIndex ..< index]))))
remainingSizeText = String(remainingSizeText[index...])
}
if !remainingSizeText.isEmpty {
animatedTextItems.append(AnimatedTextComponent.Item(id: "rest", isUnbreakable: true, content: .text(remainingSizeText)))
}
let chartTotalLabelSize = self.chartTotalLabel.update(
transition: transition,
component: AnyComponent(Text(text: dataSizeString(Int(totalSize), formatting: DataSizeStringFormatting(strings: environment.strings, decimalSeparator: ".")), font: Font.with(size: 20.0, design: .round, weight: .bold), color: environment.theme.list.itemPrimaryTextColor)), environment: {}, containerSize: CGSize(width: 200.0, height: 200.0)
/*component: AnyComponent(Text(
text: dataSizeString(Int(totalSelectedCategorySize), formatting: DataSizeStringFormatting(strings: environment.strings, decimalSeparator: ".")),
font: Font.with(size: 20.0, design: .round, weight: .bold), color: environment.theme.list.itemPrimaryTextColor
)),*/
component: AnyComponent(AnimatedTextComponent(
font: Font.with(size: 20.0, design: .round, weight: .bold),
color: environment.theme.list.itemPrimaryTextColor,
items: animatedTextItems
)),
environment: {},
containerSize: CGSize(width: 200.0, height: 200.0)
)
if let chartTotalLabelView = self.chartTotalLabel.view {
if chartTotalLabelView.superview == nil {
self.scrollView.addSubview(chartTotalLabelView)
}
transition.setFrame(view: chartTotalLabelView, frame: CGRect(origin: CGPoint(x: pieChartFrame.minX + floor((pieChartFrame.width - chartTotalLabelSize.width) / 2.0), y: pieChartFrame.minY + floor((pieChartFrame.height - chartTotalLabelSize.height) / 2.0)), size: chartTotalLabelSize))
let totalLabelFrame = CGRect(origin: CGPoint(x: pieChartFrame.minX + floor((pieChartFrame.width - chartTotalLabelSize.width) / 2.0), y: pieChartFrame.minY + floor((pieChartFrame.height - chartTotalLabelSize.height) / 2.0)), size: chartTotalLabelSize)
transition.setFrame(view: chartTotalLabelView, frame: totalLabelFrame)
transition.setAlpha(view: chartTotalLabelView, alpha: listCategories.isEmpty ? 0.0 : 1.0)
}
}
@ -2727,7 +2755,7 @@ final class StorageUsageScreenComponent: Component {
if let _ = aggregatedData.peerId {
clearTitle = presentationData.strings.StorageManagement_ClearSelected
} else {
if aggregatedData.selectedCategories == aggregatedData.existingCategories {
if aggregatedData.selectedCategories == aggregatedData.existingCategories, fromCategories {
clearTitle = presentationData.strings.StorageManagement_ClearAll
} else {
clearTitle = presentationData.strings.StorageManagement_ClearSelected