From 1202f2a845b9e3f3edefa89469fe7ea7b2562ade Mon Sep 17 00:00:00 2001 From: robot-divkit Date: Mon, 11 Mar 2024 17:31:42 +0300 Subject: [PATCH] Release 29.9.0 6849b7344361b31073f0521e36374770b9c63c42 --- .mapping.json | 6 + DivKit/Actions/DivActionHandler.swift | 53 +++-- DivKit/Actions/DivActionIntent.swift | 30 +++ DivKit/Actions/DivActionURLHandler.swift | 82 +++++++- DivKit/Actions/ScrollMode.swift | 9 + DivKit/Debug/DebugParams.swift | 7 +- DivKit/DivBlockModelingContext.swift | 2 +- DivKit/DivError.swift | 4 +- DivKit/DivExtensionHandler.swift | 10 +- DivKit/DivFontProvider.swift | 8 +- DivKit/DivKitComponents.swift | 2 +- DivKit/DivKitInfo.swift | 2 +- DivKit/DivStatePath.swift | 4 +- .../CalcExpression/AnyCalcExpression.swift | 22 +- .../CalcExpression/CalcExpression.swift | 88 ++++---- .../CalcExpression/CalcExpressionError.swift | 21 +- DivKit/Expressions/CalcExpression/Value.swift | 12 +- DivKit/Expressions/Expression.swift | 6 +- DivKit/Expressions/ExpressionLink.swift | 14 +- DivKit/Expressions/ExpressionResolver.swift | 6 +- .../Functions/ArrayFunctions.swift | 66 +++--- .../Functions/BooleanOperators.swift | 18 +- .../Expressions/Functions/CastFunctions.swift | 30 +-- .../Functions/ColorFunctions.swift | 40 ++-- .../Functions/ComparisonOperators.swift | 8 +- .../Functions/DatetimeFunctions.swift | 66 +++--- .../Expressions/Functions/DictFunctions.swift | 68 +++---- .../Functions/EqualityOperators.swift | 4 +- DivKit/Expressions/Functions/Function.swift | 188 ++++++++++-------- .../Functions/IntervalFunctions.swift | 16 +- .../Expressions/Functions/MathFunctions.swift | 38 ++-- .../Expressions/Functions/MathOperators.swift | 24 +-- .../Functions/StringFunctions.swift | 44 ++-- .../Serialization/Expression+Helpers.swift | 47 +++-- .../Expression+ValidSerializationValue.swift | 32 +-- .../Expressions/ValueProvidersFactory.swift | 4 +- .../DeserializationResultExtensions.swift | 6 +- .../DivAccessibilityExtensions.swift | 4 +- .../Extensions/DivAction/DivActionBase.swift | 13 +- .../DivAction/DivActionExtensions.swift | 13 +- .../Extensions/DivAnimationExtensions.swift | 18 +- .../DivAppearanceTransitionExtensions.swift | 12 +- .../DivBase/DivBaseExtensions.swift | 31 +-- .../DivChangeTransitionExtensions.swift | 4 +- .../DivContainer/DivContainerExtensions.swift | 67 +++---- .../DivData/DivDataPatchExtensions.swift | 14 +- .../DivDrawable/DivDrawableExtensions.swift | 6 +- DivKit/Extensions/DivExtensions.swift | 24 +-- .../Extensions/DivFontWeightExtensions.swift | 8 +- .../DivGallery/DivGalleryExtensions.swift | 27 ++- DivKit/Extensions/DivGridExtensions.swift | 4 +- .../DivImage/DivImageContentMode.swift | 24 +-- .../DivImage/DivImageExtensions.swift | 21 +- .../DivImage/DivImageProtocol.swift | 4 +- .../Extensions/DivIndicatorExtensions.swift | 14 +- DivKit/Extensions/DivInputExtensions.swift | 32 +-- DivKit/Extensions/DivPagerExtensions.swift | 4 +- DivKit/Extensions/DivPivotExtensions.swift | 4 +- .../Extensions/DivSeparatorExtensions.swift | 4 +- DivKit/Extensions/DivSizeExtensions.swift | 12 +- DivKit/Extensions/DivSizeUnitExtensions.swift | 4 +- DivKit/Extensions/DivStateExtensions.swift | 14 +- DivKit/Extensions/DivTabsExtensions.swift | 11 +- DivKit/Extensions/DivTextExtensions.swift | 14 +- DivKit/Extensions/DivTooltipExtensions.swift | 18 +- DivKit/Extensions/DivVideoExtensions.swift | 6 +- DivKit/Extensions/GradientExtentions.swift | 18 +- DivKit/RunLoopCardUpdateAggregator.swift | 2 +- DivKit/States/DivStateManager.swift | 7 +- .../DivPersistentValuesStorage.swift | 24 +-- DivKit/Templates/Field.swift | 12 +- DivKit/Variables/DivTriggersStorage.swift | 12 +- DivKit/Variables/DivVariablesStorage.swift | 2 +- DivKit/Views/DivBlockProvider.swift | 6 +- DivKit/Views/DivView.swift | 9 +- DivKit/Views/DivViewSize.swift | 15 +- .../Animations/AnimationHolder.swift | 6 +- .../Animations/AnimationSourceType.swift | 8 +- .../Lottie/LottieExtensionHandler.swift | 11 +- .../Animations/Rive/RiveAnimationBlock.swift | 12 +- .../DivBackgroundExtensions.swift | 6 +- .../GestureExtensionHandler.swift | 8 +- .../SizeProviderExtensionHandler.swift | 11 +- LayoutKit/Interface/CommonHandler.swift | 4 +- LayoutKit/Interface/UserInterfaceAction.swift | 32 +-- .../LayoutKit/Base/Masks/MaskValidator.swift | 7 +- .../Base/Masks/PhoneMaskFormatter.swift | 4 +- .../LayoutKit/Blocks/Anchor/AnchorBlock.swift | 14 +- .../Blocks/Anchor/AnchorBlockLayout.swift | 14 +- LayoutKit/LayoutKit/Blocks/AnchorPoint.swift | 4 +- .../Blocks/Block+CAAnimationRendering.swift | 20 +- .../LayoutKit/Blocks/Block+Debugging.swift | 18 +- LayoutKit/LayoutKit/Blocks/Block.swift | 6 +- .../Blocks/BlockTooltip+Layout.swift | 57 +++--- .../LayoutKit/Blocks/BlockWithTraits.swift | 10 +- .../LayoutKit/Blocks/BoundaryTrait.swift | 4 +- .../Blocks/BoundaryTraitExtensions.swift | 10 +- .../Container/AxialAlignmentManager.swift | 4 +- .../Blocks/Container/ContainerBlock.swift | 25 +-- .../Container/ContainerBlockExtensions.swift | 12 +- .../Container/ContainerBlockLayout.swift | 21 +- .../Blocks/Container/WrapLayoutGroups.swift | 16 +- .../Decorations/Block+Decorations.swift | 4 +- LayoutKit/LayoutKit/Blocks/EmptyBlock.swift | 6 +- LayoutKit/LayoutKit/Blocks/GestureBlock.swift | 2 +- .../LayoutKit/Blocks/GradientBlock.swift | 12 +- .../LayoutKit/Blocks/Grid/GridLayout.swift | 16 +- .../LayoutKit/Blocks/ImageBaseBlock.swift | 8 +- .../LayoutKit/Blocks/IntrincisHeights.swift | 9 +- LayoutKit/LayoutKit/Blocks/LayoutTrait.swift | 4 +- .../LayoutKit/Blocks/PageControlBlock.swift | 7 +- LayoutKit/LayoutKit/Blocks/PagerBlock.swift | 7 +- .../LayoutKit/Blocks/SeparatorBlock.swift | 6 +- .../Blocks/SwipeContainerBlock.swift | 4 +- .../LayoutKit/Blocks/TextFieldBlock.swift | 20 +- .../LayoutKit/Blocks/TextInputBlock.swift | 6 +- .../Video/DefaultPlayer/DefaultPlayer.swift | 6 +- .../DefaultPlayer/DefaultPlayerView.swift | 6 +- .../LayoutKit/Blocks/Video/VideoBlock.swift | 8 +- LayoutKit/LayoutKit/Blocks/Visibility.swift | 4 +- LayoutKit/LayoutKit/GenericViewBlock.swift | 38 ++-- .../LayoutKit/Tooltips/TooltipFactory.swift | 69 +++---- .../LayoutKit/Tooltips/TooltipManager.swift | 7 +- .../IndicatorStateAnimator.swift | 4 +- .../PageIndicator/PageIndicatorLayer.swift | 11 +- ...ecoratingBlock+UIViewRenderableBlock.swift | 28 +-- .../PagerBlock+UIViewRenderableBlock.swift | 6 +- ...SwipeContainerBlock+UIViewRenderable.swift | 9 +- ...ContainerBlock+UIViewRenderableBlock.swift | 4 +- .../TextBlock+UIViewRenderableBlock.swift | 16 +- ...TextFieldBlock+UIViewRenderableBlock.swift | 48 ++--- ...TextInputBlock+UIViewRenderableBlock.swift | 59 +++--- .../UIView+TransitioningAnimation.swift | 26 ++- .../UI/Views/Background+UIViewRendering.swift | 8 +- .../LayoutKit/UI/Views/GalleryView.swift | 35 +++- .../TabbedPages/TabListViewDelegate.swift | 4 +- .../LayoutKit/ViewModels/Background.swift | 32 +-- .../ViewModels/GalleryViewLayout.swift | 40 ++-- .../ViewModels/GalleryViewModel.swift | 8 +- .../ViewModels/GalleryViewState.swift | 22 +- .../ViewModels/PagerViewLayout.swift | 18 +- .../TabbedPages/TabContentsViewLayout.swift | 7 +- .../TabbedPages/TabViewLayout.swift | 7 +- Serialization/DeserializationError.swift | 70 +++---- Serialization/DeserializationResult.swift | 16 +- Specs/DivKit/29.9.0/DivKit.podspec | 25 +++ .../29.9.0/DivKitExtensions.podspec | 22 ++ .../29.9.0/DivKit_LayoutKit.podspec | 25 +++ .../29.9.0/DivKit_LayoutKitInterface.podspec | 25 +++ .../29.9.0/DivKit_Serialization.podspec | 23 +++ 150 files changed, 1556 insertions(+), 1260 deletions(-) create mode 100644 DivKit/Actions/ScrollMode.swift create mode 100644 Specs/DivKit/29.9.0/DivKit.podspec create mode 100644 Specs/DivKitExtensions/29.9.0/DivKitExtensions.podspec create mode 100644 Specs/DivKit_LayoutKit/29.9.0/DivKit_LayoutKit.podspec create mode 100644 Specs/DivKit_LayoutKitInterface/29.9.0/DivKit_LayoutKitInterface.podspec create mode 100644 Specs/DivKit_Serialization/29.9.0/DivKit_Serialization.podspec diff --git a/.mapping.json b/.mapping.json index da6217ca..35de9f63 100644 --- a/.mapping.json +++ b/.mapping.json @@ -12,6 +12,7 @@ "DivKit/Actions/DivVideoAction.swift":"divkit/public-ios/DivKit/Actions/DivVideoAction.swift", "DivKit/Actions/FocusElementActionHandler.swift":"divkit/public-ios/DivKit/Actions/FocusElementActionHandler.swift", "DivKit/Actions/OverflowMode.swift":"divkit/public-ios/DivKit/Actions/OverflowMode.swift", + "DivKit/Actions/ScrollMode.swift":"divkit/public-ios/DivKit/Actions/ScrollMode.swift", "DivKit/Actions/SetVariableActionHandler.swift":"divkit/public-ios/DivKit/Actions/SetVariableActionHandler.swift", "DivKit/Debug/Block+DebugInfo.swift":"divkit/public-ios/DivKit/Debug/Block+DebugInfo.swift", "DivKit/Debug/DebugParams.swift":"divkit/public-ios/DivKit/Debug/DebugParams.swift", @@ -858,6 +859,7 @@ "Specs/DivKit/29.6.0/DivKit.podspec":"divkit/public-ios/Specs/DivKit/29.6.0/DivKit.podspec", "Specs/DivKit/29.7.0/DivKit.podspec":"divkit/public-ios/Specs/DivKit/29.7.0/DivKit.podspec", "Specs/DivKit/29.8.0/DivKit.podspec":"divkit/public-ios/Specs/DivKit/29.8.0/DivKit.podspec", + "Specs/DivKit/29.9.0/DivKit.podspec":"divkit/public-ios/Specs/DivKit/29.9.0/DivKit.podspec", "Specs/DivKitExtensions/24.3.0/DivKitExtensions.podspec":"divkit/public-ios/Specs/DivKitExtensions/24.3.0/DivKitExtensions.podspec", "Specs/DivKitExtensions/25.0.0/DivKitExtensions.podspec":"divkit/public-ios/Specs/DivKitExtensions/25.0.0/DivKitExtensions.podspec", "Specs/DivKitExtensions/25.1.0/DivKitExtensions.podspec":"divkit/public-ios/Specs/DivKitExtensions/25.1.0/DivKitExtensions.podspec", @@ -900,6 +902,7 @@ "Specs/DivKitExtensions/29.6.0/DivKitExtensions.podspec":"divkit/public-ios/Specs/DivKitExtensions/29.6.0/DivKitExtensions.podspec", "Specs/DivKitExtensions/29.7.0/DivKitExtensions.podspec":"divkit/public-ios/Specs/DivKitExtensions/29.7.0/DivKitExtensions.podspec", "Specs/DivKitExtensions/29.8.0/DivKitExtensions.podspec":"divkit/public-ios/Specs/DivKitExtensions/29.8.0/DivKitExtensions.podspec", + "Specs/DivKitExtensions/29.9.0/DivKitExtensions.podspec":"divkit/public-ios/Specs/DivKitExtensions/29.9.0/DivKitExtensions.podspec", "Specs/DivKit_LayoutKit/28.0.1/DivKit_LayoutKit.podspec":"divkit/public-ios/Specs/DivKit_LayoutKit/28.0.1/DivKit_LayoutKit.podspec", "Specs/DivKit_LayoutKit/28.1.0/DivKit_LayoutKit.podspec":"divkit/public-ios/Specs/DivKit_LayoutKit/28.1.0/DivKit_LayoutKit.podspec", "Specs/DivKit_LayoutKit/28.10.0/DivKit_LayoutKit.podspec":"divkit/public-ios/Specs/DivKit_LayoutKit/28.10.0/DivKit_LayoutKit.podspec", @@ -924,6 +927,7 @@ "Specs/DivKit_LayoutKit/29.6.0/DivKit_LayoutKit.podspec":"divkit/public-ios/Specs/DivKit_LayoutKit/29.6.0/DivKit_LayoutKit.podspec", "Specs/DivKit_LayoutKit/29.7.0/DivKit_LayoutKit.podspec":"divkit/public-ios/Specs/DivKit_LayoutKit/29.7.0/DivKit_LayoutKit.podspec", "Specs/DivKit_LayoutKit/29.8.0/DivKit_LayoutKit.podspec":"divkit/public-ios/Specs/DivKit_LayoutKit/29.8.0/DivKit_LayoutKit.podspec", + "Specs/DivKit_LayoutKit/29.9.0/DivKit_LayoutKit.podspec":"divkit/public-ios/Specs/DivKit_LayoutKit/29.9.0/DivKit_LayoutKit.podspec", "Specs/DivKit_LayoutKitInterface/28.0.1/DivKit_LayoutKitInterface.podspec":"divkit/public-ios/Specs/DivKit_LayoutKitInterface/28.0.1/DivKit_LayoutKitInterface.podspec", "Specs/DivKit_LayoutKitInterface/28.1.0/DivKit_LayoutKitInterface.podspec":"divkit/public-ios/Specs/DivKit_LayoutKitInterface/28.1.0/DivKit_LayoutKitInterface.podspec", "Specs/DivKit_LayoutKitInterface/28.10.0/DivKit_LayoutKitInterface.podspec":"divkit/public-ios/Specs/DivKit_LayoutKitInterface/28.10.0/DivKit_LayoutKitInterface.podspec", @@ -948,6 +952,7 @@ "Specs/DivKit_LayoutKitInterface/29.6.0/DivKit_LayoutKitInterface.podspec":"divkit/public-ios/Specs/DivKit_LayoutKitInterface/29.6.0/DivKit_LayoutKitInterface.podspec", "Specs/DivKit_LayoutKitInterface/29.7.0/DivKit_LayoutKitInterface.podspec":"divkit/public-ios/Specs/DivKit_LayoutKitInterface/29.7.0/DivKit_LayoutKitInterface.podspec", "Specs/DivKit_LayoutKitInterface/29.8.0/DivKit_LayoutKitInterface.podspec":"divkit/public-ios/Specs/DivKit_LayoutKitInterface/29.8.0/DivKit_LayoutKitInterface.podspec", + "Specs/DivKit_LayoutKitInterface/29.9.0/DivKit_LayoutKitInterface.podspec":"divkit/public-ios/Specs/DivKit_LayoutKitInterface/29.9.0/DivKit_LayoutKitInterface.podspec", "Specs/DivKit_Serialization/28.0.1/DivKit_Serialization.podspec":"divkit/public-ios/Specs/DivKit_Serialization/28.0.1/DivKit_Serialization.podspec", "Specs/DivKit_Serialization/28.1.0/DivKit_Serialization.podspec":"divkit/public-ios/Specs/DivKit_Serialization/28.1.0/DivKit_Serialization.podspec", "Specs/DivKit_Serialization/28.10.0/DivKit_Serialization.podspec":"divkit/public-ios/Specs/DivKit_Serialization/28.10.0/DivKit_Serialization.podspec", @@ -972,6 +977,7 @@ "Specs/DivKit_Serialization/29.6.0/DivKit_Serialization.podspec":"divkit/public-ios/Specs/DivKit_Serialization/29.6.0/DivKit_Serialization.podspec", "Specs/DivKit_Serialization/29.7.0/DivKit_Serialization.podspec":"divkit/public-ios/Specs/DivKit_Serialization/29.7.0/DivKit_Serialization.podspec", "Specs/DivKit_Serialization/29.8.0/DivKit_Serialization.podspec":"divkit/public-ios/Specs/DivKit_Serialization/29.8.0/DivKit_Serialization.podspec", + "Specs/DivKit_Serialization/29.9.0/DivKit_Serialization.podspec":"divkit/public-ios/Specs/DivKit_Serialization/29.9.0/DivKit_Serialization.podspec", "Specs/LayoutKit/24.3.0/LayoutKit.podspec":"divkit/public-ios/Specs/LayoutKit/24.3.0/LayoutKit.podspec", "Specs/LayoutKit/25.0.0/LayoutKit.podspec":"divkit/public-ios/Specs/LayoutKit/25.0.0/LayoutKit.podspec", "Specs/LayoutKit/25.1.0/LayoutKit.podspec":"divkit/public-ios/Specs/LayoutKit/25.1.0/LayoutKit.podspec", diff --git a/DivKit/Actions/DivActionHandler.swift b/DivKit/Actions/DivActionHandler.swift index 32b94f9f..db711ea4 100644 --- a/DivKit/Actions/DivActionHandler.swift +++ b/DivKit/Actions/DivActionHandler.swift @@ -96,14 +96,13 @@ public final class DivActionHandler { params: UserInterfaceAction.DivActionParams, sender: AnyObject? ) { - let action: DivActionBase? - switch params.source { + let action: DivActionBase? = switch params.source { case .visibility: - action = parseAction(type: DivVisibilityActionTemplate.self, json: params.action) + parseAction(type: DivVisibilityActionTemplate.self, json: params.action) case .disappear: - action = parseAction(type: DivDisappearActionTemplate.self, json: params.action) + parseAction(type: DivDisappearActionTemplate.self, json: params.action) default: - action = parseAction(type: DivActionTemplate.self, json: params.action) + parseAction(type: DivActionTemplate.self, json: params.action) } guard let action else { return @@ -113,6 +112,7 @@ public final class DivActionHandler { action, cardId: DivCardID(rawValue: params.cardId), source: params.source, + prototypeVariables: params.prototypeVariables, sender: sender ) } @@ -121,9 +121,13 @@ public final class DivActionHandler { _ action: DivActionBase, cardId: DivCardID, source: UserInterfaceAction.DivActionSource, + prototypeVariables: [String: AnyHashable] = [:], sender: AnyObject? ) { - let expressionResolver = makeExpressionResolver(cardId: cardId) + let expressionResolver = makeExpressionResolver( + cardId: cardId, + prototypeVariables: prototypeVariables + ) let context = DivActionHandlingContext( cardId: cardId, expressionResolver: expressionResolver, @@ -192,15 +196,19 @@ public final class DivActionHandler { guard let self else { return } - let callbackActions: [DivAction] - switch result { + let callbackActions: [DivAction] = switch result { case .success: - callbackActions = action.downloadCallbacks?.onSuccessActions ?? [] + action.downloadCallbacks?.onSuccessActions ?? [] case .failure: - callbackActions = action.downloadCallbacks?.onFailActions ?? [] + action.downloadCallbacks?.onFailActions ?? [] } callbackActions.forEach { - self.handle($0, cardId: context.cardId, source: source, sender: sender) + self.handle( + $0, + cardId: context.cardId, + source: source, + sender: sender + ) } } ) @@ -226,11 +234,24 @@ public final class DivActionHandler { } } - private func makeExpressionResolver(cardId: DivCardID) -> ExpressionResolver { - ExpressionResolver( - variables: variablesStorage.makeVariables(for: cardId), - persistentValuesStorage: persistentValuesStorage, - errorTracker: reporter.asExpressionErrorTracker(cardId: cardId) + private func makeExpressionResolver( + cardId: DivCardID, + prototypeVariables: [String: AnyHashable] + ) -> ExpressionResolver { + let variableValueProvider = makeVariableValueProvider( + cardId: cardId, + variablesStorage: variablesStorage, + prototypesStorage: prototypeVariables + ) + let functionsProvider = FunctionsProvider( + variableValueProvider: variableValueProvider, + persistentValuesStorage: persistentValuesStorage + ) + return ExpressionResolver( + variableValueProvider: variableValueProvider, + functionsProvider: functionsProvider, + errorTracker: reporter.asExpressionErrorTracker(cardId: cardId), + variableTracker: { _ in } ) } diff --git a/DivKit/Actions/DivActionIntent.swift b/DivKit/Actions/DivActionIntent.swift index ceb2b759..be7b2847 100644 --- a/DivKit/Actions/DivActionIntent.swift +++ b/DivKit/Actions/DivActionIntent.swift @@ -12,6 +12,7 @@ enum DivActionIntent { case setCurrentItem(id: String, index: Int) case setNextItem(id: String, overflow: OverflowMode) case setPreviousItem(id: String, overflow: OverflowMode) + case scroll(id: String, mode: ScrollMode) case timer(id: String, action: DivTimerAction) case video(id: String, action: DivVideoAction) case setStoredValue(storedValue: DivStoredValue) @@ -64,6 +65,31 @@ enum DivActionIntent { return nil } self = .setPreviousItem(id: id, overflow: url.overflow) + case "scroll_forward": + guard let id = url.id, let step = url.step else { + return nil + } + self = .scroll(id: id, mode: .forward(step: step, overflow: url.overflow)) + case "scroll_backward": + guard let id = url.id, let step = url.step else { + return nil + } + self = .scroll(id: id, mode: .backward(step: step, overflow: url.overflow)) + case "scroll_to_position": + guard let id = url.id, let step = url.step else { + return nil + } + self = .scroll(id: id, mode: .position(step: step)) + case "scroll_to_start": + guard let id = url.id else { + return nil + } + self = .scroll(id: id, mode: .start) + case "scroll_to_end": + guard let id = url.id else { + return nil + } + self = .scroll(id: id, mode: .end) case "timer": guard let id = url.id, let action = url.timerAction else { return nil @@ -171,6 +197,10 @@ extension URL { return .clamp } } + + fileprivate var step: CGFloat? { + queryParamValue(forName: "step").flatMap(Int.init).flatMap(CGFloat.init) + } fileprivate var storedValue: DivStoredValue? { guard let name = getParam(forName: "name"), diff --git a/DivKit/Actions/DivActionURLHandler.swift b/DivKit/Actions/DivActionURLHandler.swift index e9b5e03c..7d0afd63 100644 --- a/DivKit/Actions/DivActionURLHandler.swift +++ b/DivKit/Actions/DivActionURLHandler.swift @@ -113,6 +113,8 @@ public final class DivActionURLHandler { case let .setPreviousItem(id, overflow): setPreviousItem(id: id, cardId: cardId, overflow: overflow) updateCard(.state(cardId)) + case let .scroll(id, mode): + setContentOffset(id: id, cardId: cardId, mode: mode) case let .video(id: id, action: action): blockStateStorage.setState( id: id, @@ -143,6 +145,54 @@ public final class DivActionURLHandler { } } + private func setContentOffset(id: String, cardId: DivCardID, mode: ScrollMode) { + let state: GalleryViewState? = blockStateStorage.getState(id, cardId: cardId) + if let state, let newOffset = getNewOffset(state: state, mode: mode) { + blockStateStorage.setState( + id: id, + cardId: cardId, + state: GalleryViewState( + contentPosition: .offset(newOffset), + itemsCount: state.itemsCount, + isScrolling: state.isScrolling, + scrollRange: state.scrollRange + ) + ) + updateCard(.state(cardId)) + } + } + + private func getNewOffset(state: GalleryViewState, mode: ScrollMode) -> CGFloat? { + guard let scrollRange = state.scrollRange, scrollRange > 0 else { + return nil + } + switch mode { + case let .forward(step, overflow): + return getOffset(offset: state.currentOffset + step, scrollRange: scrollRange, overflow: overflow) + case let .backward(step, overflow): + return getOffset(offset: state.currentOffset - step, scrollRange: scrollRange, overflow: overflow) + case let .position(step): + return getOffset(offset: step, scrollRange: scrollRange, overflow: .clamp) + case .start: + return 0 + case .end: + return scrollRange + } + } + + private func getOffset( + offset: CGFloat, + scrollRange: CGFloat, + overflow: OverflowMode + ) -> CGFloat { + switch overflow { + case .ring: + return (offset + scrollRange).truncatingRemainder(dividingBy: scrollRange) + case .clamp: + return offset.clamp(0...scrollRange) + } + } + private func setCurrentItem(id: String, cardId: DivCardID, index: Int) { switch blockStateStorage.getStateUntyped(id, cardId: cardId) { case let galleryState as GalleryViewState: @@ -150,7 +200,7 @@ public final class DivActionURLHandler { id: id, cardId: cardId, index: index, - itemsCount: galleryState.itemsCount + state: galleryState ) case let pagerState as PagerViewState: setPagerCurrentItem( @@ -178,7 +228,7 @@ public final class DivActionURLHandler { id: id, cardId: cardId, index: index, - itemsCount: galleryState.itemsCount + state: galleryState ) case let pagerState as PagerViewState: let nextIndex = getNextIndex( @@ -237,7 +287,7 @@ public final class DivActionURLHandler { id: id, cardId: cardId, index: index, - itemsCount: galleryState.itemsCount + state: galleryState ) case let pagerState as PagerViewState: let prevIndex = getPreviousIndex( @@ -288,9 +338,9 @@ public final class DivActionURLHandler { id: String, cardId: DivCardID, index: Int, - itemsCount: Int + state: GalleryViewState ) { - let clampedIndex = clamp(index, min: 0, max: max(0, itemsCount - 1)) + let clampedIndex = clamp(index, min: 0, max: max(0, state.itemsCount - 1)) guard clampedIndex == index else { return } @@ -298,8 +348,10 @@ public final class DivActionURLHandler { id: id, cardId: cardId, state: GalleryViewState( - contentPageIndex: CGFloat(clampedIndex), - itemsCount: itemsCount + contentPosition: .paging(index: CGFloat(clampedIndex)), + itemsCount: state.itemsCount, + isScrolling: state.isScrolling, + scrollRange: state.scrollRange ) ) } @@ -340,9 +392,21 @@ extension GalleryViewState { fileprivate var currentItemIndex: Int { switch contentPosition { case let .offset(_, firstVisibleItemsIndex): - return firstVisibleItemsIndex + firstVisibleItemsIndex case let .paging(index): - return Int(index) + Int(index) + } + } + + fileprivate var currentOffset: CGFloat { + switch contentPosition { + case let .offset(value, _): + return value + case let .paging(index): + guard let scrollRange, itemsCount > 0 else { + return 0 + } + return scrollRange / CGFloat(itemsCount - 1) * index } } } diff --git a/DivKit/Actions/ScrollMode.swift b/DivKit/Actions/ScrollMode.swift new file mode 100644 index 00000000..7d142d55 --- /dev/null +++ b/DivKit/Actions/ScrollMode.swift @@ -0,0 +1,9 @@ +import Foundation + +enum ScrollMode { + case forward(step: CGFloat, overflow: OverflowMode) + case backward(step: CGFloat, overflow: OverflowMode) + case position(step: CGFloat) + case start + case end +} diff --git a/DivKit/Debug/DebugParams.swift b/DivKit/Debug/DebugParams.swift index 482a849e..5e4b8e0f 100644 --- a/DivKit/Debug/DebugParams.swift +++ b/DivKit/Debug/DebugParams.swift @@ -46,11 +46,10 @@ public struct DebugParams { #if os(iOS) extension DebugParams { public static func showDebugInfo(_ view: ViewType) { - let window: UIWindow? - if #available(iOS 13.0, *) { - window = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first + let window: UIWindow? = if #available(iOS 13.0, *) { + (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first } else { - window = UIApplication.shared.windows.first + UIApplication.shared.windows.first } view.frame.center = window?.center ?? .zero window?.addSubview(view) diff --git a/DivKit/DivBlockModelingContext.swift b/DivKit/DivBlockModelingContext.swift index 2743b508..61d572a7 100644 --- a/DivKit/DivBlockModelingContext.swift +++ b/DivKit/DivBlockModelingContext.swift @@ -41,7 +41,7 @@ public struct DivBlockModelingContext { private let variableTracker: ExpressionResolver.VariableTracker public private(set) var parentPath: UIElementPath private(set) var sizeModifier: DivSizeModifier? - private var prototypesStorage = [String: Any]() + private(set) var prototypesStorage = [String: AnyHashable]() public init( cardId: DivCardID, diff --git a/DivKit/DivError.swift b/DivKit/DivError.swift index 79cb9684..ca76dbda 100644 --- a/DivKit/DivError.swift +++ b/DivKit/DivError.swift @@ -65,9 +65,9 @@ extension DeserializationError: DivError { private func getPath(parent: UIElementPath?) -> UIElementPath? { switch self { case let .nestedObjectError(field, error): - return error.getPath(parent: parent.map { $0 + field } ?? UIElementPath(field)) + error.getPath(parent: parent.map { $0 + field } ?? UIElementPath(field)) default: - return parent + parent } } diff --git a/DivKit/DivExtensionHandler.swift b/DivKit/DivExtensionHandler.swift index 55605cd9..cce7b0ee 100644 --- a/DivKit/DivExtensionHandler.swift +++ b/DivKit/DivExtensionHandler.swift @@ -18,7 +18,7 @@ import LayoutKit public protocol DivExtensionHandler: AccessibilityContaining { /// A unique identifier for the extension. var id: String { get } - + /// Notifies extension handler that div will be processed by DivKit. /// /// - Parameters: @@ -28,7 +28,7 @@ public protocol DivExtensionHandler: AccessibilityContaining { div: DivBase, context: DivBlockModelingContext ) - + /// Applies additional properties to the block before the base properties. /// /// - Parameters: @@ -60,10 +60,10 @@ public protocol DivExtensionHandler: AccessibilityContaining { extension DivExtensionHandler { public func accept( - div: DivBase, - context: DivBlockModelingContext + div _: DivBase, + context _: DivBlockModelingContext ) {} - + public func applyBeforeBaseProperties( to block: Block, div _: DivBase, diff --git a/DivKit/DivFontProvider.swift b/DivKit/DivFontProvider.swift index 5c5ee71b..4a180049 100644 --- a/DivKit/DivFontProvider.swift +++ b/DivKit/DivFontProvider.swift @@ -41,13 +41,13 @@ extension DivFontWeight { fileprivate var baseUIFontWeight: BaseUIPublic.FontWeight { switch self { case .light: - return .light + .light case .regular: - return .regular + .regular case .medium: - return .medium + .medium case .bold: - return .bold + .bold } } } diff --git a/DivKit/DivKitComponents.swift b/DivKit/DivKitComponents.swift index 4ccb80a2..81185295 100644 --- a/DivKit/DivKitComponents.swift +++ b/DivKit/DivKitComponents.swift @@ -329,7 +329,7 @@ public final class DivKitComponents { public func flushUpdateActions() { updateAggregator.flushUpdateActions() } - + public func forceUpdate() { updateAggregator.forceUpdate() } diff --git a/DivKit/DivKitInfo.swift b/DivKit/DivKitInfo.swift index a4c31844..935c5438 100644 --- a/DivKit/DivKitInfo.swift +++ b/DivKit/DivKitInfo.swift @@ -1,3 +1,3 @@ public enum DivKitInfo { - public static let version = "29.8.0" + public static let version = "29.9.0" } diff --git a/DivKit/DivStatePath.swift b/DivKit/DivStatePath.swift index 918df46e..9e3227cc 100644 --- a/DivKit/DivStatePath.swift +++ b/DivKit/DivStatePath.swift @@ -58,9 +58,9 @@ extension Tagged where Tag == DivDataStateIDTag, RawValue == Int { extension DivStatePath? { public static func +(parent: Self, child: String) -> DivStatePath { if let parent { - return parent + DivStateID(rawValue: child) + parent + DivStateID(rawValue: child) } else { - return DivStatePath(rawValue: UIElementPath(child)) + DivStatePath(rawValue: UIElementPath(child)) } } } diff --git a/DivKit/Expressions/CalcExpression/AnyCalcExpression.swift b/DivKit/Expressions/CalcExpression/AnyCalcExpression.swift index f9513a0c..0ba81c36 100644 --- a/DivKit/Expressions/CalcExpression/AnyCalcExpression.swift +++ b/DivKit/Expressions/CalcExpression/AnyCalcExpression.swift @@ -62,19 +62,19 @@ struct AnyCalcExpression { impureSymbols: { symbol in switch symbol { case .function, .infix, .prefix: - return functions[symbol]?.symbolEvaluator + functions[symbol]?.symbolEvaluator default: - return nil + nil } }, pureSymbols: { symbol in switch symbol { case let .variable(name): - return variables(name).map { value in { _ in value } } + variables(name).map { value in { _ in value } } case .function, .infix, .prefix: - return functions[symbol]?.symbolEvaluator + functions[symbol]?.symbolEvaluator default: - return nil + nil } } ) @@ -97,19 +97,19 @@ struct AnyCalcExpression { } return String(name.dropFirst().dropLast()) } - func funcEvaluator(for symbol: Symbol, _ value: Any) -> CalcExpression.SymbolEvaluator? { + func funcEvaluator(for _: Symbol, _ value: Any) -> CalcExpression.SymbolEvaluator? { // TODO: should funcEvaluator call the `.infix("()")` implementation? switch value { case let fn as SymbolEvaluator: - return { args in + { args in try box.store(fn(args.map(box.load))) } case let fn as CalcExpression.SymbolEvaluator: - return { args in + { args in try fn(args) } default: - return nil + nil } } @@ -565,9 +565,9 @@ extension AnyCalcExpression { .infix("!:"): { args in switch args[0] { case .error: - return args[1] + args[1] default: - return args[0] + args[0] } }, ] diff --git a/DivKit/Expressions/CalcExpression/CalcExpression.swift b/DivKit/Expressions/CalcExpression/CalcExpression.swift index ce00f7d7..d6c0d32a 100644 --- a/DivKit/Expressions/CalcExpression/CalcExpression.swift +++ b/DivKit/Expressions/CalcExpression/CalcExpression.swift @@ -64,9 +64,9 @@ final class CalcExpression: CustomStringConvertible { var description: String { switch self { case let .exactly(value): - return "\(value) argument\(value == 1 ? "" : "s")" + "\(value) argument\(value == 1 ? "" : "s")" case let .atLeast(value): - return "at least \(value) argument\(value == 1 ? "" : "s")" + "at least \(value) argument\(value == 1 ? "" : "s")" } } @@ -86,10 +86,10 @@ final class CalcExpression: CustomStringConvertible { switch (self, arity) { case let (.exactly(lhs), .exactly(rhs)), let (.atLeast(lhs), .atLeast(rhs)): - return lhs == rhs + lhs == rhs case let (.atLeast(min), .exactly(value)), let (.exactly(value), .atLeast(min)): - return value >= min + value >= min } } } @@ -123,7 +123,7 @@ final class CalcExpression: CustomStringConvertible { let .postfix(name), let .function(name, _), let .array(name): - return name + name } } @@ -136,23 +136,23 @@ final class CalcExpression: CustomStringConvertible { var description: String { switch self { case .variable: - return "variable \(escapedName)" + "variable \(escapedName)" case .infix("?:"): - return "ternary operator \(escapedName)" + "ternary operator \(escapedName)" case .infix("[]"): - return "subscript operator \(escapedName)" + "subscript operator \(escapedName)" case .infix("()"): - return "function call operator \(escapedName)" + "function call operator \(escapedName)" case .infix: - return "infix operator \(escapedName)" + "infix operator \(escapedName)" case .prefix: - return "prefix operator \(escapedName)" + "prefix operator \(escapedName)" case .postfix: - return "postfix operator \(escapedName)" + "postfix operator \(escapedName)" case .function: - return "function \(escapedName)()" + "function \(escapedName)()" case .array: - return "array \(escapedName)[]" + "array \(escapedName)[]" } } } @@ -169,7 +169,7 @@ final class CalcExpression: CustomStringConvertible { root = try expression.root.optimized( withImpureSymbols: impureSymbols, pureSymbols: { - if let fn = try pureSymbols($0){ + if let fn = try pureSymbols($0) { return fn } if case let .function(name, _) = $0 { @@ -234,9 +234,13 @@ extension CalcExpression { static func errorEvaluator(for symbol: Symbol) -> SymbolEvaluator { switch symbol { case .infix("[]"), .function("[]", _), .infix("()"): - return { _ in throw Error.unexpectedToken(String(symbol.name.prefix(1))) } + { _ in throw Error.unexpectedToken(String(symbol.name.prefix(1))) } + case let .function(name, _): + { _ in + throw Error.message("Failed to evaluate [\(name)()]. Unknown function name: \(name).") + } default: - return { _ in throw Error.undefinedSymbol(symbol) } + { _ in throw Error.undefinedSymbol(symbol) } } } } @@ -360,9 +364,9 @@ extension CalcExpression { 0xC_00_00...0xC_FF_FD, 0xD_00_00...0xD_FF_FD, 0xE_00_00...0xE_FF_FD: - return true + true default: - return false + false } } @@ -373,9 +377,9 @@ extension CalcExpression { 0x1D_C0...0x1D_FF, 0x20_D0...0x20_FF, 0xFE_20...0xFE_2F: - return true + true default: - return isIdentifierHead(c) + isIdentifierHead(c) } } } @@ -420,14 +424,14 @@ private enum Subexpression: CustomStringConvertible { case let .symbol(symbol, args, _) where args.isEmpty: switch symbol { case .infix, .prefix, .postfix: - return false + false default: - return true + true } case .symbol, .literal: - return true + true case .error: - return false + false } } @@ -493,22 +497,20 @@ private enum Subexpression: CustomStringConvertible { return "\(args[0])[\(args[1])]" case let .infix(name): let lhs = args[0] - let lhsDescription: String - switch lhs { + let lhsDescription = switch lhs { case let .symbol(.infix(opName), _, _) where !CalcExpression.operator(opName, takesPrecedenceOver: name): - lhsDescription = "(\(lhs))" + "(\(lhs))" default: - lhsDescription = "\(lhs)" + "\(lhs)" } let rhs = args[1] - let rhsDescription: String - switch rhs { + let rhsDescription = switch rhs { case let .symbol(.infix(opName), _, _) where CalcExpression.operator(name, takesPrecedenceOver: opName): - rhsDescription = "(\(rhs))" + "(\(rhs))" default: - rhsDescription = "\(rhs)" + "\(rhs)" } return "\(lhsDescription) \(symbol.escapedName) \(rhsDescription)" case .variable: @@ -657,9 +659,9 @@ extension UnicodeScalarView { var value: String { switch self { case let .number(value): - return value + value case let .integer(value): - return value + value } } } @@ -698,9 +700,9 @@ extension UnicodeScalarView { scanCharacters { switch $0 { case " ", "\t", "\n", "\r": - return false + false default: - return true + true } } } @@ -709,9 +711,9 @@ extension UnicodeScalarView { if let _ = scanCharacters({ switch $0 { case " ", "\t", "\n", "\r": - return true + true default: - return false + false } }) { return true @@ -748,9 +750,9 @@ extension UnicodeScalarView { scanCharacters { switch $0 { case "0"..."9", "A"..."F", "a"..."f": - return true + true default: - return false + false } } } @@ -926,9 +928,9 @@ extension UnicodeScalarView { let hex = scanCharacters { switch $0 { case "0"..."9", "A"..."F", "a"..."f": - return true + true default: - return false + false } } ?? "" guard scanCharacter("}") else { diff --git a/DivKit/Expressions/CalcExpression/CalcExpressionError.swift b/DivKit/Expressions/CalcExpression/CalcExpressionError.swift index 71c96562..f2697c0c 100644 --- a/DivKit/Expressions/CalcExpression/CalcExpressionError.swift +++ b/DivKit/Expressions/CalcExpression/CalcExpressionError.swift @@ -39,22 +39,21 @@ extension CalcExpression { case let .missingVariable(symbol): return "Variable '\(symbol.escapedName)' is missing." case let .arityMismatch(symbol): - let arity: Arity - switch symbol { + let arity: Arity = switch symbol { case let .function(_, requiredArity): - arity = requiredArity + requiredArity case .infix("()"): - arity = .atLeast(1) + .atLeast(1) case .array, .infix("[]"): - arity = 1 + 1 case .infix("?:"): - arity = 3 + 3 case .infix: - arity = 2 + 2 case .postfix, .prefix: - arity = 1 + 1 case .variable: - arity = 0 + 0 } let description = symbol.description return "\(description.prefix(1).uppercased())\(description.dropFirst()) expects \(arity)" @@ -66,9 +65,9 @@ extension CalcExpression { func makeOutputMessage(for expression: String) -> String { switch self { case let .shortMessage(message): - return "Failed to evaluate [\(expression.escaped)]. \(message)" + "Failed to evaluate [\(expression.escaped)]. \(message)" default: - return self.description + self.description } } } diff --git a/DivKit/Expressions/CalcExpression/Value.swift b/DivKit/Expressions/CalcExpression/Value.swift index 58d8dbbd..d7737227 100644 --- a/DivKit/Expressions/CalcExpression/Value.swift +++ b/DivKit/Expressions/CalcExpression/Value.swift @@ -15,17 +15,17 @@ extension CalcExpression.Value { var value: Double { switch self { case let .integer(integer): - return Double(integer) + Double(integer) case let .number(number): - return number + number case .string: - return .nan + .nan case let .datetime(date): - return date.timeIntervalSince1970 + date.timeIntervalSince1970 case let .boolean(bool): - return bool ? 1 : 0 + bool ? 1 : 0 case .error: - return .nan + .nan } } } diff --git a/DivKit/Expressions/Expression.swift b/DivKit/Expressions/Expression.swift index bdc5858a..55428323 100644 --- a/DivKit/Expressions/Expression.swift +++ b/DivKit/Expressions/Expression.swift @@ -10,11 +10,11 @@ extension Expression: Equatable where T: Equatable { public static func ==(lhs: Self, rhs: Self) -> Bool { switch (lhs, rhs) { case let (.value(lValue), .value(rValue)): - return lValue == rValue + lValue == rValue case let (.link(lValue), .link(rValue)): - return lValue == rValue + lValue == rValue case (.value, _), (.link, _): - return false + false } } } diff --git a/DivKit/Expressions/ExpressionLink.swift b/DivKit/Expressions/ExpressionLink.swift index 10124b5c..a74d48aa 100644 --- a/DivKit/Expressions/ExpressionLink.swift +++ b/DivKit/Expressions/ExpressionLink.swift @@ -21,7 +21,7 @@ public struct ExpressionLink { validator: AnyValueValidator? = nil, errorTracker: ExpressionErrorTracker? = nil, resolveNested: Bool = true - ) throws { + ) { guard !rawValue.isEmpty else { errorTracker?(ExpressionError("Empty expression", expression: nil)) return nil @@ -38,7 +38,7 @@ public struct ExpressionLink { guard let (start, end) = currentValue.makeLinkIndices() else { let error = ExpressionError("Error tokenizing '\(rawValue)'.", expression: rawValue) errorTracker?(error) - throw error + return nil } if !currentString.isEmpty { items.append(.string(currentString)) @@ -48,7 +48,7 @@ public struct ExpressionLink { items.append(.string("")) } else { let value = String(currentValue[start...end]) - if resolveNested, let link = try ExpressionLink( + if resolveNested, let link = ExpressionLink( rawValue: value, errorTracker: errorTracker ) { @@ -129,13 +129,13 @@ extension ExpressionLink.Item: Equatable { static func ==(lhs: ExpressionLink.Item, rhs: ExpressionLink.Item) -> Bool { switch (lhs, rhs) { case let (.calcExpression(left), .calcExpression(right)): - return left.description == right.description + left.description == right.description case let (.string(left), .string(right)): - return left == right + left == right case let (.nestedCalcExpression(left), .nestedCalcExpression(right)): - return left == right + left == right case (.calcExpression, _), (.string, _), (.nestedCalcExpression, _): - return false + false } } } diff --git a/DivKit/Expressions/ExpressionResolver.swift b/DivKit/Expressions/ExpressionResolver.swift index e8b578ca..796ed2f2 100644 --- a/DivKit/Expressions/ExpressionResolver.swift +++ b/DivKit/Expressions/ExpressionResolver.swift @@ -64,7 +64,7 @@ public final class ExpressionResolver { } public func resolveNumeric(_ expression: String) -> T? { - if let link = try? ExpressionLink(rawValue: expression) { + if let link = ExpressionLink(rawValue: expression) { return resolveNumeric(.link(link)) } return nil @@ -223,7 +223,7 @@ public final class ExpressionResolver { stringValue += value case let .nestedCalcExpression(link): if let expression = evaluateString(link: link) { - let link = try? ExpressionLink( + let link = ExpressionLink( rawValue: "@{\(expression)}", errorTracker: errorTracker, resolveNested: false @@ -275,7 +275,7 @@ public final class ExpressionResolver { _ expression: String, initializer: (String) -> T? ) -> T? { - if let link = try? ExpressionLink(rawValue: expression) { + if let link = ExpressionLink(rawValue: expression) { return resolveString(.link(link), initializer: initializer) } return initializer(expression) diff --git a/DivKit/Expressions/Functions/ArrayFunctions.swift b/DivKit/Expressions/Functions/ArrayFunctions.swift index 93483fd5..05d24cad 100644 --- a/DivKit/Expressions/Functions/ArrayFunctions.swift +++ b/DivKit/Expressions/Functions/ArrayFunctions.swift @@ -35,34 +35,34 @@ enum ArrayFunctions: String, CaseIterable { var function: Function { switch self { case .getArrayString: - return FunctionBinary(impl: _getArrayString) + FunctionBinary(impl: _getArrayString) case .getArrayNumber: - return FunctionBinary(impl: _getArrayNumber) + FunctionBinary(impl: _getArrayNumber) case .getArrayInteger: - return FunctionBinary(impl: _getArrayInteger) + FunctionBinary(impl: _getArrayInteger) case .getArrayBoolean: - return FunctionBinary(impl: _getArrayBoolean) + FunctionBinary(impl: _getArrayBoolean) case .getArrayColor: - return FunctionBinary(impl: _getArrayColor) + FunctionBinary(impl: _getArrayColor) case .getArrayUrl: - return FunctionBinary(impl: _getArrayUrl) + FunctionBinary(impl: _getArrayUrl) case .getArrayOptString: - return FunctionTernary(impl: _getArrayOptString) + FunctionTernary(impl: _getArrayOptString) case .getArrayOptNumber: - return FunctionTernary(impl: _getArrayOptNumber) + FunctionTernary(impl: _getArrayOptNumber) case .getArrayOptInteger: - return FunctionTernary(impl: _getArrayOptInteger) + FunctionTernary(impl: _getArrayOptInteger) case .getArrayOptBoolean: - return FunctionTernary(impl: _getArrayOptBoolean) + FunctionTernary(impl: _getArrayOptBoolean) case .getArrayOptColor: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionTernary(impl: _getArrayOptColorWithColorFallback), FunctionTernary(impl: _getArrayOptColorWithStringFallback), ] ) case .getArrayOptUrl: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionTernary(impl: _getArrayOptUrlWithURLFallback), FunctionTernary(impl: _getArrayOptUrlWithStringFallback), @@ -70,47 +70,47 @@ enum ArrayFunctions: String, CaseIterable { ) case .getStringFromArray: - return FunctionBinary(impl: _getStringFromArray) + FunctionBinary(impl: _getStringFromArray) case .getOptStringFromArray: - return FunctionTernary(impl: _getOptStringFromArray) + FunctionTernary(impl: _getOptStringFromArray) case .getIntegerFromArray: - return FunctionBinary(impl: _getIntegerFromArray) + FunctionBinary(impl: _getIntegerFromArray) case .getOptIntegerFromArray: - return FunctionTernary(impl: _getOptIntegerFromArray) + FunctionTernary(impl: _getOptIntegerFromArray) case .getNumberFromArray: - return FunctionBinary(impl: _getNumberFromArray) + FunctionBinary(impl: _getNumberFromArray) case .getOptNumberFromArray: - return FunctionTernary(impl: _getOptNumberFromArray) + FunctionTernary(impl: _getOptNumberFromArray) case .getBooleanFromArray: - return FunctionBinary(impl: _getBooleanFromArray) + FunctionBinary(impl: _getBooleanFromArray) case .getOptBooleanFromArray: - return FunctionTernary(impl: _getOptBooleanFromArray) + FunctionTernary(impl: _getOptBooleanFromArray) case .getColorFromArray: - return FunctionBinary(impl: _getColorFromArray) + FunctionBinary(impl: _getColorFromArray) case .getOptColorFromArray: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionTernary(impl: _getOptColorFromArrayWithColorFallback), FunctionTernary(impl: _getOptColorFromArrayWithStringFallback), ] ) case .getUrlFromArray: - return FunctionBinary(impl: _getUrlFromArray) + FunctionBinary(impl: _getUrlFromArray) case .getOptUrlFromArray: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionTernary(impl: _getOptUrlFromArrayWithURLFallback), FunctionTernary(impl: _getOptUrlFromArrayWithStringFallback), ] ) case .getArrayFromArray: - return FunctionBinary(impl: _getArrayFromArray) + FunctionBinary(impl: _getArrayFromArray) case .getOptArrayFromArray: - return FunctionBinary(impl: _getOptArrayFromArray) + FunctionBinary(impl: _getOptArrayFromArray) case .getDictFromArray: - return FunctionBinary(impl: _getDictFromArray) + FunctionBinary(impl: _getDictFromArray) case .getOptDictFromArray: - return FunctionBinary(impl: _getOptDictFromArray) + FunctionBinary(impl: _getOptDictFromArray) } } @@ -510,15 +510,15 @@ enum ArrayFunctions: String, CaseIterable { private var description: String { switch self { case let .indexOutOfBounds(expression, requstedIndex, arraySize): - return "Failed to evaluate [\(expression)]. Requested index (\(requstedIndex)) out of bounds array size (\(arraySize))." + "Failed to evaluate [\(expression)]. Requested index (\(requstedIndex)) out of bounds array size (\(arraySize))." case let .incorrectValueType(expression, expectedType, actualType): - return "Failed to evaluate [\(expression)]. Incorrect value type: expected \"\(expectedType)\", got \"\(actualType)\"." + "Failed to evaluate [\(expression)]. Incorrect value type: expected \"\(expectedType)\", got \"\(actualType)\"." case let .cannotConvertToInteger(expression): - return "Failed to evaluate [\(expression)]. Cannot convert value to integer." + "Failed to evaluate [\(expression)]. Cannot convert value to integer." case let .integerOverflow(expression): - return "Failed to evaluate [\(expression)]. Integer overflow." + "Failed to evaluate [\(expression)]. Integer overflow." case let .incorrectColorFormat(expression): - return "Failed to evaluate [\(expression)]. Unable to convert value to Color, expected format #AARRGGBB." + "Failed to evaluate [\(expression)]. Unable to convert value to Color, expected format #AARRGGBB." } } diff --git a/DivKit/Expressions/Functions/BooleanOperators.swift b/DivKit/Expressions/Functions/BooleanOperators.swift index 12ea322c..8f0b1f5a 100644 --- a/DivKit/Expressions/Functions/BooleanOperators.swift +++ b/DivKit/Expressions/Functions/BooleanOperators.swift @@ -9,16 +9,16 @@ enum BooleanOperators: String, CaseIterable { var symbol: AnyCalcExpression.Symbol { switch self { case .and, .or, .ternary: - return .infix(rawValue) + .infix(rawValue) case .not: - return .prefix(rawValue) + .prefix(rawValue) } } var function: Function { OverloadedFunction( functions: [ - makeFunction() + makeFunction(), ], makeError: makeError ) @@ -43,11 +43,17 @@ enum BooleanOperators: String, CaseIterable { if args[0].type == .boolean { return OperatorsError.unsupportedType(symbol: rawValue, args: args).message } - return .message("Failed to evaluate [\(args[0].formattedValue) \(rawValue) ...]. '\(rawValue)' must be called with boolean operands.") + return .message( + "Failed to evaluate [\(args[0].formattedValue) \(rawValue) ...]. '\(rawValue)' must be called with boolean operands." + ) case .not: - return .message("Failed to evaluate [!\(args[0].formattedValue)]. A Boolean is expected after a unary not.") + return .message( + "Failed to evaluate [!\(args[0].formattedValue)]. A Boolean is expected after a unary not." + ) case .ternary: - return .message("Failed to evaluate [\(args[0].formattedValue) ? \(args[1].formattedValue) : \(args[2].formattedValue)]. Ternary must be called with a Boolean value as a condition.") + return .message( + "Failed to evaluate [\(args[0].formattedValue) ? \(args[1].formattedValue) : \(args[2].formattedValue)]. Ternary must be called with a Boolean value as a condition." + ) } } } diff --git a/DivKit/Expressions/Functions/CastFunctions.swift b/DivKit/Expressions/Functions/CastFunctions.swift index 735ae96c..d546d0c1 100644 --- a/DivKit/Expressions/Functions/CastFunctions.swift +++ b/DivKit/Expressions/Functions/CastFunctions.swift @@ -13,7 +13,7 @@ enum CastFunctions: String, CaseIterable { var function: Function { switch self { case .toBoolean: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary(impl: _stringToBoolean), FunctionUnary(impl: _intToBoolean), @@ -23,11 +23,11 @@ enum CastFunctions: String, CaseIterable { } ) case .toString: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary(impl: _boolToString), - FunctionUnary(impl: _doubleToString), FunctionUnary(impl: _intToString), + FunctionUnary(impl: _doubleToString), FunctionUnary(impl: _colorToString), FunctionUnary(impl: _urlToString), ], @@ -36,7 +36,7 @@ enum CastFunctions: String, CaseIterable { } ) case .toNumber: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary(impl: _intToNumber), FunctionUnary(impl: _stringToNumber), @@ -46,7 +46,7 @@ enum CastFunctions: String, CaseIterable { } ) case .toInteger: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary(impl: _boolToInteger), FunctionUnary(impl: _doubleToInteger), @@ -57,9 +57,9 @@ enum CastFunctions: String, CaseIterable { } ) case .toColor: - return FunctionUnary(impl: _stringToColor) + FunctionUnary(impl: _stringToColor) case .toUrl: - return FunctionUnary(impl: _stringToUrl) + FunctionUnary(impl: _stringToUrl) } } } @@ -156,9 +156,9 @@ extension Bool { fileprivate func toInteger() -> Int { switch self { case true: - return 1 + 1 case false: - return 0 + 0 } } } @@ -237,22 +237,22 @@ extension AnyCalcExpression.Error { private static func formatValue(_ value: Any?) -> String { switch value { case let strValue as String: - return "'\(strValue)'" + "'\(strValue)'" case let doubleValue as Double: - return doubleValue.toString() ?? "" + doubleValue.toString() ?? "" default: - return "\(value ?? "")" + "\(value ?? "")" } } private static func formatType(_ value: Any?) -> String { switch value { case is Double: - return "Number" + "Number" case is Bool: - return "Boolean" + "Boolean" default: - return "\(type(of: value))" + "\(type(of: value))" } } } diff --git a/DivKit/Expressions/Functions/ColorFunctions.swift b/DivKit/Expressions/Functions/ColorFunctions.swift index 93d436f2..1d30fbdd 100644 --- a/DivKit/Expressions/Functions/ColorFunctions.swift +++ b/DivKit/Expressions/Functions/ColorFunctions.swift @@ -16,13 +16,13 @@ enum ColorFunctions: CaseIterable { private var description: String { switch self { case let .cast(type): - return "Argument couldn't be casted to \(type)" + "Argument couldn't be casted to \(type)" case let .outOfRange(expression): - return "Failed to evaluate [\(expression)]. Value out of range 0..1." + "Failed to evaluate [\(expression)]. Value out of range 0..1." case let .get(channel, value): - return makeErrorDescription("[getColor\(channel.description)('\(value)')]") + makeErrorDescription("[getColor\(channel.description)('\(value)')]") case let .set(channel, first, second): - return makeErrorDescription("[setColor\(channel.description)('\(first)', \(second))]") + makeErrorDescription("[setColor\(channel.description)('\(first)', \(second))]") } } } @@ -50,24 +50,24 @@ enum ColorFunctions: CaseIterable { var rawValue: String { switch self { case .argb: - return "argb" + "argb" case .rgb: - return "rgb" + "rgb" case let .get(channel): - return "getColor\(channel.description)" + "getColor\(channel.description)" case let .set(channel): - return "setColor\(channel.description)" + "setColor\(channel.description)" } } var function: Function { switch self { case .argb: - return FunctionQuaternary(impl: _argb) + FunctionQuaternary(impl: _argb) case .rgb: - return FunctionTernary(impl: _rgb) + FunctionTernary(impl: _rgb) case let .get(channel): - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary(impl: { try getChannel(channel, from: $0) }), FunctionUnary(impl: { getChannelFromColor(channel, from: $0) }), @@ -76,7 +76,7 @@ enum ColorFunctions: CaseIterable { ColorFunctions.Error.get(channel, String(describing: $0.first?.value)).message } case let .set(channel): - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: { try setChannel(channel, to: $0, value: $1) }), FunctionBinary(impl: { try setChannelForColor(channel, to: $0, value: $1) }), @@ -151,26 +151,26 @@ extension Color { fileprivate func makeChannel(_ channel: ColorFunctions.Channel) -> Double { switch channel { case .alpha: - return alpha + alpha case .red: - return red + red case .green: - return green + green case .blue: - return blue + blue } } fileprivate func set(_ value: Double, for channel: ColorFunctions.Channel) -> Color { switch channel { case .alpha: - return Color(red: red, green: green, blue: blue, alpha: value) + Color(red: red, green: green, blue: blue, alpha: value) case .red: - return Color(red: value, green: green, blue: blue, alpha: alpha) + Color(red: value, green: green, blue: blue, alpha: alpha) case .green: - return Color(red: red, green: value, blue: blue, alpha: alpha) + Color(red: red, green: value, blue: blue, alpha: alpha) case .blue: - return Color(red: red, green: green, blue: value, alpha: alpha) + Color(red: red, green: green, blue: value, alpha: alpha) } } } diff --git a/DivKit/Expressions/Functions/ComparisonOperators.swift b/DivKit/Expressions/Functions/ComparisonOperators.swift index a522be08..0a7cf28d 100644 --- a/DivKit/Expressions/Functions/ComparisonOperators.swift +++ b/DivKit/Expressions/Functions/ComparisonOperators.swift @@ -24,13 +24,13 @@ enum ComparisonOperators: String, CaseIterable { FunctionBinary { switch self { case .greater: - return $0 > $1 + $0 > $1 case .greaterOrEqual: - return $0 >= $1 + $0 >= $1 case .less: - return $0 < $1 + $0 < $1 case .lessOrEqual: - return $0 <= $1 + $0 <= $1 } } } diff --git a/DivKit/Expressions/Functions/DatetimeFunctions.swift b/DivKit/Expressions/Functions/DatetimeFunctions.swift index 932ec366..a44c175a 100644 --- a/DivKit/Expressions/Functions/DatetimeFunctions.swift +++ b/DivKit/Expressions/Functions/DatetimeFunctions.swift @@ -21,23 +21,23 @@ enum DatetimeFunctions: String, CaseIterable { private var description: String { switch self { case let .month(date, value): - return "Failed to evaluate [setMonth(\(date.formatString), \(value))]. Expecting month in [1..12], instead got \(value)." + "Failed to evaluate [setMonth(\(date.formatString), \(value))]. Expecting month in [1..12], instead got \(value)." case let .day(date, value): - return "Failed to evaluate [setDay(\(date.formatString), \(value))]. Unable to set day \(value) for date \(date.formatString)." + "Failed to evaluate [setDay(\(date.formatString), \(value))]. Unable to set day \(value) for date \(date.formatString)." case let .hours(date, value): - return "Failed to evaluate [setHours(\(date.formatString), \(value))]. Expecting hours in [0..23], instead got \(value)." + "Failed to evaluate [setHours(\(date.formatString), \(value))]. Expecting hours in [0..23], instead got \(value)." case let .minutes(date, value): - return "Failed to evaluate [setMinutes(\(date.formatString), \(value))]. Expecting minutes in [0..59], instead got \(value)." + "Failed to evaluate [setMinutes(\(date.formatString), \(value))]. Expecting minutes in [0..59], instead got \(value)." case let .seconds(date, value): - return "Failed to evaluate [setSeconds(\(date.formatString), \(value))]. Expecting seconds in [0..59], instead got \(value)." + "Failed to evaluate [setSeconds(\(date.formatString), \(value))]. Expecting seconds in [0..59], instead got \(value)." case let .millis(date, value): - return "Failed to evaluate [setMillis(\(date.formatString), \(value))]. Expecting millis in [0..999], instead got \(value)." + "Failed to evaluate [setMillis(\(date.formatString), \(value))]. Expecting millis in [0..999], instead got \(value)." case let .components(funcName): - return "Failed to evaluate [\(funcName)]. Date components not found." + "Failed to evaluate [\(funcName)]. Date components not found." case let .component(funcName, component): - return "Failed to evaluate [\(funcName)]. Component '\(component)' not found." + "Failed to evaluate [\(funcName)]. Component '\(component)' not found." case let .format(format): - return "z/Z not supported in [\(format)]" + "z/Z not supported in [\(format)]" } } } @@ -69,51 +69,51 @@ enum DatetimeFunctions: String, CaseIterable { var function: Function { switch self { case .parseUnixTime: - return FunctionUnary(impl: _parseUnixTime) + FunctionUnary(impl: _parseUnixTime) case .parseUnixTimeAsLocal: - return FunctionUnary(impl: _parseUnixTimeAsLocal) + FunctionUnary(impl: _parseUnixTimeAsLocal) case .nowLocal: - return FunctionNullary(impl: _nowLocal) + FunctionNullary(impl: _nowLocal) case .addMillis: - return FunctionBinary(impl: _addMillis) + FunctionBinary(impl: _addMillis) case .setYear: - return FunctionBinary(impl: _setYear) + FunctionBinary(impl: _setYear) case .setMonth: - return FunctionBinary(impl: _setMonth) + FunctionBinary(impl: _setMonth) case .setDay: - return FunctionBinary(impl: _setDay) + FunctionBinary(impl: _setDay) case .setHours: - return FunctionBinary(impl: _setHours) + FunctionBinary(impl: _setHours) case .setMinutes: - return FunctionBinary(impl: _setMinutes) + FunctionBinary(impl: _setMinutes) case .setSeconds: - return FunctionBinary(impl: _setSeconds) + FunctionBinary(impl: _setSeconds) case .setMillis: - return FunctionBinary(impl: _setMillis) + FunctionBinary(impl: _setMillis) case .getYear: - return FunctionUnary(impl: _getYear) + FunctionUnary(impl: _getYear) case .getMonth: - return FunctionUnary(impl: _getMonth) + FunctionUnary(impl: _getMonth) case .getDay: - return FunctionUnary(impl: _getDay) + FunctionUnary(impl: _getDay) case .getDayOfWeek: - return FunctionUnary(impl: _getDayOfWeek) + FunctionUnary(impl: _getDayOfWeek) case .getHours: - return FunctionUnary(impl: _getHours) + FunctionUnary(impl: _getHours) case .getMinutes: - return FunctionUnary(impl: _getMinutes) + FunctionUnary(impl: _getMinutes) case .getSeconds: - return FunctionUnary(impl: _getSeconds) + FunctionUnary(impl: _getSeconds) case .getMillis: - return FunctionUnary(impl: _getMillis) + FunctionUnary(impl: _getMillis) case .formatDateAsLocal: - return FunctionBinary(impl: _formatDateAsLocal) + FunctionBinary(impl: _formatDateAsLocal) case .formatDateAsLocalWithLocale: - return FunctionTernary(impl: _formatDateAsLocalWithLocale) + FunctionTernary(impl: _formatDateAsLocalWithLocale) case .formatDateAsUTC: - return FunctionBinary(impl: _formatDateAsUTC) + FunctionBinary(impl: _formatDateAsUTC) case .formatDateAsUTCWithLocale: - return FunctionTernary(impl: _formatDateAsUTCWithLocale) + FunctionTernary(impl: _formatDateAsUTCWithLocale) } } } @@ -301,7 +301,7 @@ private func formatDate( isUTC: Bool = false, locale: String? = nil ) throws -> String { - guard !format.contains("Z") && !format.contains("z") else { + guard !format.contains("Z"), !format.contains("z") else { throw DatetimeFunctions.Error.format(format).message } return makeDateFormatter(format, isUTC: isUTC, locale: locale).string(from: value) diff --git a/DivKit/Expressions/Functions/DictFunctions.swift b/DivKit/Expressions/Functions/DictFunctions.swift index de29a353..f8fda1da 100644 --- a/DivKit/Expressions/Functions/DictFunctions.swift +++ b/DivKit/Expressions/Functions/DictFunctions.swift @@ -35,34 +35,34 @@ enum DictFunctions: String, CaseIterable { var function: Function { switch self { case .getDictString: - return FunctionVarBinary(impl: _getDictString) + FunctionVarBinary(impl: _getDictString) case .getDictNumber: - return FunctionVarBinary(impl: _getDictNumber) + FunctionVarBinary(impl: _getDictNumber) case .getDictInteger: - return FunctionVarBinary(impl: _getDictInteger) + FunctionVarBinary(impl: _getDictInteger) case .getDictBoolean: - return FunctionVarBinary(impl: _getDictBoolean) + FunctionVarBinary(impl: _getDictBoolean) case .getDictColor: - return FunctionVarBinary(impl: _getDictColor) + FunctionVarBinary(impl: _getDictColor) case .getDictUrl: - return FunctionVarBinary(impl: _getDictUrl) + FunctionVarBinary(impl: _getDictUrl) case .getDictOptString: - return FunctionVarTernary(impl: _getDictOptString) + FunctionVarTernary(impl: _getDictOptString) case .getDictOptNumber: - return FunctionVarTernary(impl: _getDictOptNumber) + FunctionVarTernary(impl: _getDictOptNumber) case .getDictOptInteger: - return FunctionVarTernary(impl: _getDictOptInteger) + FunctionVarTernary(impl: _getDictOptInteger) case .getDictOptBoolean: - return FunctionVarTernary(impl: _getDictOptBoolean) + FunctionVarTernary(impl: _getDictOptBoolean) case .getDictOptColor: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarTernary(impl: _getDictOptColorWithColorFallback), FunctionVarTernary(impl: _getDictOptColorWithStringFallback), ] ) case .getDictOptUrl: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarTernary(impl: _getDictOptUrlWithURLFallback), FunctionVarTernary(impl: _getDictOptUrlWithStringFallback), @@ -70,47 +70,47 @@ enum DictFunctions: String, CaseIterable { ) case .getStringFromDict: - return FunctionVarBinary(impl: _getStringFromDict) + FunctionVarBinary(impl: _getStringFromDict) case .getOptStringFromDict: - return FunctionVarTernary(impl: _getOptStringFromDict) + FunctionVarTernary(impl: _getOptStringFromDict) case .getIntegerFromDict: - return FunctionVarBinary(impl: _getIntegerFromDict) + FunctionVarBinary(impl: _getIntegerFromDict) case .getOptIntegerFromDict: - return FunctionVarTernary(impl: _getOptIntegerFromDict) + FunctionVarTernary(impl: _getOptIntegerFromDict) case .getNumberFromDict: - return FunctionVarBinary(impl: _getNumberFromDict) + FunctionVarBinary(impl: _getNumberFromDict) case .getOptNumberFromDict: - return FunctionVarTernary(impl: _getOptNumberFromDict) + FunctionVarTernary(impl: _getOptNumberFromDict) case .getBooleanFromDict: - return FunctionVarBinary(impl: _getBooleanFromDict) + FunctionVarBinary(impl: _getBooleanFromDict) case .getOptBooleanFromDict: - return FunctionVarTernary(impl: _getOptBooleanFromDict) + FunctionVarTernary(impl: _getOptBooleanFromDict) case .getColorFromDict: - return FunctionVarBinary(impl: _getColorFromDict) + FunctionVarBinary(impl: _getColorFromDict) case .getOptColorFromDict: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarTernary(impl: _getOptColorFromDictWithStringFallback), FunctionVarTernary(impl: _getOptColorFromDictWithColorFallback), ] ) case .getUrlFromDict: - return FunctionVarBinary(impl: _getUrlFromDict) + FunctionVarBinary(impl: _getUrlFromDict) case .getOptUrlFromDict: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarTernary(impl: _getOptUrlFromDictWithURLFallback), FunctionVarTernary(impl: _getOptUrlFromDictWithStringFallback), ] ) case .getArrayFromDict: - return FunctionVarBinary(impl: _getArrayFromDict) + FunctionVarBinary(impl: _getArrayFromDict) case .getOptArrayFromDict: - return FunctionVarBinary(impl: _getOptArrayFromDict) + FunctionVarBinary(impl: _getOptArrayFromDict) case .getDictFromDict: - return FunctionVarBinary(impl: _getDictFromDict) + FunctionVarBinary(impl: _getDictFromDict) case .getOptDictFromDict: - return FunctionVarBinary(impl: _getOptDictFromDict) + FunctionVarBinary(impl: _getOptDictFromDict) } } @@ -589,17 +589,17 @@ private enum Error { private var description: String { switch self { case let .missingProperty(expression, missing): - return "Failed to evaluate [\(expression)]. Missing property \"\(missing)\" in the dict." + "Failed to evaluate [\(expression)]. Missing property \"\(missing)\" in the dict." case let .wrongPath(expression): - return "Failed to evaluate [\(expression)]. Path is wrong." + "Failed to evaluate [\(expression)]. Path is wrong." case let .incorrectValueType(expression, expectedType, actualType): - return "Failed to evaluate [\(expression)]. Incorrect value type: expected \"\(expectedType)\", got \"\(actualType)\"." + "Failed to evaluate [\(expression)]. Incorrect value type: expected \"\(expectedType)\", got \"\(actualType)\"." case let .cannotConvertToInteger(expression): - return "Failed to evaluate [\(expression)]. Cannot convert value to integer." + "Failed to evaluate [\(expression)]. Cannot convert value to integer." case let .integerOverflow(expression): - return "Failed to evaluate [\(expression)]. Integer overflow." + "Failed to evaluate [\(expression)]. Integer overflow." case let .incorrectColorFormat(expression): - return "Failed to evaluate [\(expression)]. Unable to convert value to Color, expected format #AARRGGBB." + "Failed to evaluate [\(expression)]. Unable to convert value to Color, expected format #AARRGGBB." } } diff --git a/DivKit/Expressions/Functions/EqualityOperators.swift b/DivKit/Expressions/Functions/EqualityOperators.swift index 88db0d24..799a44e2 100644 --- a/DivKit/Expressions/Functions/EqualityOperators.swift +++ b/DivKit/Expressions/Functions/EqualityOperators.swift @@ -29,9 +29,9 @@ enum EqualityOperators: String, CaseIterable { FunctionBinary { switch self { case .equals: - return $0 == $1 + $0 == $1 case .notEquals: - return $0 != $1 + $0 != $1 } } } diff --git a/DivKit/Expressions/Functions/Function.swift b/DivKit/Expressions/Functions/Function.swift index eee49ccd..55b17588 100644 --- a/DivKit/Expressions/Functions/Function.swift +++ b/DivKit/Expressions/Functions/Function.swift @@ -19,8 +19,7 @@ extension SimpleFunction { } func symbolEvaluator(_ args: [Any]) throws -> Any { - try signature.checkArguments(args: args) - return try invoke(args: args) + try invoke(args: args) } func verify(signature: FunctionSignature) throws { @@ -68,10 +67,7 @@ struct FunctionUnary: SimpleFunction { } func invoke(args: [Any]) throws -> Any { - guard let v1 = args[0] as? T1 else { - throw FunctionSignature.Error.arityMismatch.message - } - return try impl(v1) + try impl(castArg(args[0])) } } @@ -95,10 +91,10 @@ struct FunctionBinary: SimpleFunction { } func invoke(args: [Any]) throws -> Any { - guard let v1 = args[0] as? T1, let v2 = args[1] as? T2 else { - throw FunctionSignature.Error.arityMismatch.message - } - return try impl(v1, v2) + try impl( + castArg(args[0]), + castArg(args[1]) + ) } } @@ -123,10 +119,11 @@ struct FunctionTernary: SimpleFunction { } func invoke(args: [Any]) throws -> Any { - guard let v1 = args[0] as? T1, let v2 = args[1] as? T2, let v3 = args[2] as? T3 else { - throw FunctionSignature.Error.arityMismatch.message - } - return try impl(v1, v2, v3) + try impl( + castArg(args[0]), + castArg(args[1]), + castArg(args[2]) + ) } } @@ -152,11 +149,12 @@ struct FunctionQuaternary: SimpleFunction { } func invoke(args: [Any]) throws -> Any { - guard let v1 = args[0] as? T1, let v2 = args[1] as? T2, let v3 = args[2] as? T3, - let v4 = args[3] as? T4 else { - throw FunctionSignature.Error.arityMismatch.message - } - return try impl(v1, v2, v3, v4) + try impl( + castArg(args[0]), + castArg(args[1]), + castArg(args[2]), + castArg(args[3]) + ) } } @@ -179,10 +177,7 @@ struct FunctionVarUnary: SimpleFunction { } func invoke(args: [Any]) throws -> Any { - guard let v1 = args as? [T1] else { - throw FunctionSignature.Error.arityMismatch.message - } - return try impl(v1) + try impl(args.map { try castArg($0) }) } } @@ -206,11 +201,10 @@ struct FunctionVarBinary: SimpleFunction { } func invoke(args: [Any]) throws -> Any { - guard let v1 = args[0] as? T1 else { - throw FunctionSignature.Error.arityMismatch.message - } - let v2 = args.dropFirst().map { $0 as! T2 } - return try impl(v1, v2) + return try impl( + castArg(args[0]), + args.dropFirst().map { try castArg($0) } + ) } } @@ -235,11 +229,11 @@ struct FunctionVarTernary: SimpleFunction { } func invoke(args: [Any]) throws -> Any { - guard let v1 = args[0] as? T1, let v2 = args[1] as? T2 else { - throw FunctionSignature.Error.arityMismatch.message - } - let v3 = args.dropFirst(2).map { $0 as! T3 } - return try impl(v1, v2, v3) + try impl( + castArg(args[0]), + castArg(args[1]), + args.dropFirst(2).map { try castArg($0) } + ) } } @@ -253,7 +247,7 @@ struct OverloadedFunction: Function { init(functions: [SimpleFunction], makeError: (([Argument]) -> Error)? = nil) { self.functions = functions - self.makeError = makeError ?? { FunctionSignature.Error.typeMismatch(args: $0).message } + self.makeError = makeError ?? { _ in FunctionSignature.Error.notFound.message } } func verify(signature: FunctionSignature) throws { @@ -266,21 +260,36 @@ struct OverloadedFunction: Function { let arguments = try args.map { try FunctionSignature.ArgumentSignature(type: .from(type: type(of: $0))) } - guard let function = try functions - .first(where: { try - zip($0.signature.allArguments(arguments.count), arguments) - .allSatisfy { $0.type == $1.type || $0.type == .any } - - }) - else { - throw makeError(zip(args, arguments).map { Argument(type: $1.type, value: $0) }) + var function = try getFunction(args: arguments) { + $0.type == $1.type + } + if function == nil { + function = try getFunction(args: arguments) { + $0.type.isCastableFrom($1.type) + } + } + if let function { + return try function.invoke(args: args) } - return try function.invoke(args: args) + throw makeError(zip(args, arguments).map { Argument(type: $1.type, value: $0) }) } func symbolEvaluator(_ args: [Any]) throws -> Any { try invoke(args: args) } + + private func getFunction( + args: [FunctionSignature.ArgumentSignature], + predicate: (FunctionSignature.ArgumentSignature, FunctionSignature.ArgumentSignature) -> Bool + ) throws -> SimpleFunction? { + let sutableFunctions = try functions.filter { + try zip($0.signature.allArguments(args.count), args).allSatisfy(predicate) + } + if sutableFunctions.count > 1 { + throw CalcExpression.Error.message("Multiple matching overloads") + } + return sutableFunctions.first + } } struct Argument { @@ -309,9 +318,9 @@ struct FunctionSignature: Decodable { var arity: CalcExpression.Arity { if arguments.last?.vararg == true { - return .atLeast(arguments.count) + .atLeast(arguments.count) } else { - return .exactly(arguments.count) + .exactly(arguments.count) } } @@ -327,41 +336,51 @@ struct FunctionSignature: Decodable { case array case any - func check(arg: Any) -> Bool { - type(of: arg) == swiftType - } - var swiftType: Any.Type { switch self { case .string: - return String.self + String.self case .number: - return Double.self + Double.self case .integer: - return Int.self + Int.self case .boolean: - return Bool.self + Bool.self case .datetime: - return Date.self + Date.self case .color: - return Color.self + Color.self case .url: - return URL.self + URL.self case .dict: - return [String: AnyHashable].self + [String: AnyHashable].self case .array: - return [AnyHashable].self + [AnyHashable].self case .any: - return Any.self + Any.self } } var name: String { switch self { case .datetime: - return "DateTime" + "DateTime" + default: + rawValue.stringWithFirstCharCapitalized() + } + } + + func isCastableFrom(_ type: ArgumentType) -> Bool { + if self == type { + return true + } + switch self { + case .any: + return true + case .number: + return type == .integer default: - return rawValue.stringWithFirstCharCapitalized() + return false } } @@ -374,9 +393,7 @@ struct FunctionSignature: Decodable { } enum Error { - case cast(ArgumentType) case arityMismatch - case typeMismatch(args: [Argument]) case argumentTypeMismatch(Int, ArgumentType, ArgumentType) case resultTypeMismatch(ArgumentType, ArgumentType) case notFound @@ -388,48 +405,33 @@ struct FunctionSignature: Decodable { private var description: String { switch self { - case let .cast(type): - return "Argument couldn't be casted to \(type.rawValue.capitalized)" case .arityMismatch: - return "Function arity mismatch" - case let .typeMismatch(args): - return "Type mismatch \(args.map { $0.formattedValue }.joined(separator: " "))" + "Function arity mismatch" case let .argumentTypeMismatch(i, expected, found): - return "Argument \(i + 1) type mismatch, expected: \(expected), found: \(found)" + "Argument \(i + 1) type mismatch, expected: \(expected), found: \(found)" case let .resultTypeMismatch(expected, found): - return "Result type mismatch, expected: \(expected), found: \(found)" + "Result type mismatch, expected: \(expected), found: \(found)" case .notFound: - return "Function with signature is not found" + "Function with signature is not found" case .type: - return "Type is not supported" - } - } - } - - fileprivate func checkArguments(args: [Any]) throws { - guard arity.matches(.exactly(args.count)) else { - throw FunctionSignature.Error.arityMismatch.message - } - try zip(allArguments(args.count), args).forEach { signatureArg, arg in - if !signatureArg.type.check(arg: arg) { - throw FunctionSignature.Error.cast(signatureArg.type).message + "Type is not supported" } } } fileprivate func allArguments(_ i: Int) -> [ArgumentSignature] { if let last = arguments.last, last.vararg == true { - return (arguments + Array(repeating: last, times: UInt(i - arguments.count))).map { + (arguments + Array(repeating: last, times: UInt(i - arguments.count))).map { .init(type: $0.type) } } else { - return arguments + arguments } } fileprivate func verify(_ signature: FunctionSignature) throws { guard arity.matches(signature.arity) else { - throw FunctionSignature.Error.arityMismatch.message + throw Error.arityMismatch.message } try zip(arguments, signature.arguments).enumerated().forEach { i, a in if a.0 != a.1 { @@ -437,7 +439,19 @@ struct FunctionSignature: Decodable { } } if resultType != signature.resultType { - throw FunctionSignature.Error.resultTypeMismatch(resultType, signature.resultType).message + throw Error.resultTypeMismatch(resultType, signature.resultType).message } } } + +private func castArg(_ value: Any) throws -> T { + if let castedValue = value as? T { + return castedValue + } + + if T.self == Double.self, let intValue = value as? Int { + return Double(intValue) as! T + } + + throw AnyCalcExpression.Error.message("Argument couldn't be casted to \(T.self)") +} diff --git a/DivKit/Expressions/Functions/IntervalFunctions.swift b/DivKit/Expressions/Functions/IntervalFunctions.swift index 97e84009..e0fc86a6 100644 --- a/DivKit/Expressions/Functions/IntervalFunctions.swift +++ b/DivKit/Expressions/Functions/IntervalFunctions.swift @@ -13,21 +13,21 @@ enum IntervalFunctions: String, CaseIterable { var function: Function { switch self { case .getIntervalSeconds: - return FunctionUnary(impl: _getIntervalSeconds) + FunctionUnary(impl: _getIntervalSeconds) case .getIntervalTotalSeconds: - return FunctionUnary(impl: _getIntervalTotalSeconds) + FunctionUnary(impl: _getIntervalTotalSeconds) case .getIntervalMinutes: - return FunctionUnary(impl: _getIntervalMinutes) + FunctionUnary(impl: _getIntervalMinutes) case .getIntervalTotalMinutes: - return FunctionUnary(impl: _getIntervalTotalMinutes) + FunctionUnary(impl: _getIntervalTotalMinutes) case .getIntervalHours: - return FunctionUnary(impl: _getIntervalHours) + FunctionUnary(impl: _getIntervalHours) case .getIntervalTotalHours: - return FunctionUnary(impl: _getIntervalTotalHours) + FunctionUnary(impl: _getIntervalTotalHours) case .getIntervalTotalDays: - return FunctionUnary(impl: _getIntervalTotalDays) + FunctionUnary(impl: _getIntervalTotalDays) case .getIntervalTotalWeeks: - return FunctionUnary(impl: _getIntervalTotalWeeks) + FunctionUnary(impl: _getIntervalTotalWeeks) } } diff --git a/DivKit/Expressions/Functions/MathFunctions.swift b/DivKit/Expressions/Functions/MathFunctions.swift index 52035047..faed105a 100644 --- a/DivKit/Expressions/Functions/MathFunctions.swift +++ b/DivKit/Expressions/Functions/MathFunctions.swift @@ -22,84 +22,84 @@ enum MathFunctions: String, CaseIterable { var function: Function { switch self { case .div: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: _divInt), FunctionBinary(impl: _divDouble), ] ) case .mod: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: _modInt), FunctionBinary(impl: _modDouble), ] ) case .mul: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarUnary(impl: _mulInt), FunctionVarUnary(impl: _mulDouble), ] ) case .sub: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarUnary(impl: _subInt), FunctionVarUnary(impl: _subDouble), ] ) case .sum: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarUnary(impl: _sumInt), FunctionVarUnary(impl: _sumDouble), ] ) case .maxInteger: - return FunctionNullary(impl: _maxInteger) + FunctionNullary(impl: _maxInteger) case .minInteger: - return FunctionNullary(impl: _minInteger) + FunctionNullary(impl: _minInteger) case .maxNumber: - return FunctionNullary(impl: _maxNumber) + FunctionNullary(impl: _maxNumber) case .minNumber: - return FunctionNullary(impl: _minNumber) + FunctionNullary(impl: _minNumber) case .max: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarUnary(impl: _maxInt), FunctionVarUnary(impl: _maxDouble), ] ) case .min: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionVarUnary(impl: _minInt), FunctionVarUnary(impl: _minDouble), ] ) case .abs: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary(impl: _absInt), FunctionUnary(impl: _absDouble), ] ) case .signum: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary(impl: _signumInt), FunctionUnary(impl: _signumDouble), ] ) case .round: - return FunctionUnary(impl: _round) + FunctionUnary(impl: _round) case .floor: - return FunctionUnary(impl: _floor) + FunctionUnary(impl: _floor) case .ceil: - return FunctionUnary(impl: _ceil) + FunctionUnary(impl: _ceil) case .copySign: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: _copySignInt), FunctionBinary(impl: _copySignDouble), @@ -263,9 +263,9 @@ private enum Error { private var description: String { switch self { case let .typeMismatch(args): - return "Type mismatch \(args.map { "\($0)" }.joined(separator: " "))" + "Type mismatch \(args.map { "\($0)" }.joined(separator: " "))" case let .divisionByZero(function, lhs, rhs): - return "Failed to evaluate [\(function)(\(lhs), \(rhs))]. Division by zero is not supported." + "Failed to evaluate [\(function)(\(lhs), \(rhs))]. Division by zero is not supported." } } diff --git a/DivKit/Expressions/Functions/MathOperators.swift b/DivKit/Expressions/Functions/MathOperators.swift index 4a039b07..eabee360 100644 --- a/DivKit/Expressions/Functions/MathOperators.swift +++ b/DivKit/Expressions/Functions/MathOperators.swift @@ -12,18 +12,18 @@ enum MathOperators: String, CaseIterable { var symbol: AnyCalcExpression.Symbol { switch self { case .sum, .sub, .mul, .div, .mod: - return .infix(rawValue) + .infix(rawValue) case .plus: - return .prefix("+") + .prefix("+") case .minus: - return .prefix("-") + .prefix("-") } } var function: Function { switch self { case .sum: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: _sumInt), FunctionBinary(impl: _sumDouble), @@ -32,7 +32,7 @@ enum MathOperators: String, CaseIterable { makeError: makeError ) case .sub: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: _subInt), FunctionBinary(impl: _subDouble), @@ -40,7 +40,7 @@ enum MathOperators: String, CaseIterable { makeError: makeError ) case .mul: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: _mulInt), FunctionBinary(impl: _mulDouble), @@ -48,7 +48,7 @@ enum MathOperators: String, CaseIterable { makeError: makeError ) case .div: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: _divInt), FunctionBinary(impl: _divDouble), @@ -56,7 +56,7 @@ enum MathOperators: String, CaseIterable { makeError: makeError ) case .mod: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionBinary(impl: _modInt), FunctionBinary(impl: _modDouble), @@ -64,7 +64,7 @@ enum MathOperators: String, CaseIterable { makeError: makeError ) case .plus: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary { $0 }, FunctionUnary { $0 }, @@ -72,7 +72,7 @@ enum MathOperators: String, CaseIterable { makeError: makeUnaryError ) case .minus: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionUnary { -$0 }, FunctionUnary { -$0 }, @@ -168,9 +168,9 @@ private enum Error { private var description: String { switch self { case let .divisionByZero(symbol, lhs, rhs): - return "Failed to evaluate [\(lhs) \(symbol) \(rhs)]. Division by zero is not supported." + "Failed to evaluate [\(lhs) \(symbol) \(rhs)]. Division by zero is not supported." case let .unaryUnsupportedType(symbol, symbolName, arg): - return "Failed to evaluate [\(symbol)\(arg.formattedValue)]. A Number is expected after a unary \(symbolName)." + "Failed to evaluate [\(symbol)\(arg.formattedValue)]. A Number is expected after a unary \(symbolName)." } } diff --git a/DivKit/Expressions/Functions/StringFunctions.swift b/DivKit/Expressions/Functions/StringFunctions.swift index 055d8d44..6a3ff31e 100644 --- a/DivKit/Expressions/Functions/StringFunctions.swift +++ b/DivKit/Expressions/Functions/StringFunctions.swift @@ -12,17 +12,17 @@ enum StringFunctions: String, CaseIterable { private var description: String { switch self { case .cast: - return "Argument couldn't be casted to String" + "Argument couldn't be casted to String" case .indexesCast: - return "Indexes couldn't be casted to Integer" + "Indexes couldn't be casted to Integer" case let .indexesOrder(expression): - return "Failed to evaluate [\(expression)]. Indexes should be in ascending order." + "Failed to evaluate [\(expression)]. Indexes should be in ascending order." case let .indexesValue(expression): - return "Failed to evaluate [\(expression)]. Indexes are out of bounds." + "Failed to evaluate [\(expression)]. Indexes are out of bounds." case .encodeEmpty: - return "String is empty after encoding." + "String is empty after encoding." case .decodeEmpty: - return "String is empty after decoding." + "String is empty after decoding." } } @@ -51,47 +51,47 @@ enum StringFunctions: String, CaseIterable { var function: Function { switch self { case .len: - return FunctionUnary(impl: _len) + FunctionUnary(impl: _len) case .contains: - return FunctionBinary(impl: _contains) + FunctionBinary(impl: _contains) case .substring: - return FunctionTernary(impl: _substring) + FunctionTernary(impl: _substring) case .replaceAll: - return FunctionTernary(impl: _replaceAll) + FunctionTernary(impl: _replaceAll) case .index: - return FunctionBinary(impl: _index) + FunctionBinary(impl: _index) case .lastIndex: - return FunctionBinary(impl: _lastIndex) + FunctionBinary(impl: _lastIndex) case .trim: - return FunctionUnary(impl: _trim) + FunctionUnary(impl: _trim) case .trimLeft: - return FunctionUnary(impl: _trimLeft) + FunctionUnary(impl: _trimLeft) case .trimRight: - return FunctionUnary(impl: _trimRight) + FunctionUnary(impl: _trimRight) case .toUpperCase: - return FunctionUnary(impl: _toUpperCase) + FunctionUnary(impl: _toUpperCase) case .toLowerCase: - return FunctionUnary(impl: _toLowerCase) + FunctionUnary(impl: _toLowerCase) case .encodeUri: - return FunctionUnary(impl: _encodeUri) + FunctionUnary(impl: _encodeUri) case .decodeUri: - return FunctionUnary(impl: _decodeUri) + FunctionUnary(impl: _decodeUri) case .padStart: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionTernary(impl: _padStart), FunctionTernary(impl: _padStartInt), ] ) case .padEnd: - return OverloadedFunction( + OverloadedFunction( functions: [ FunctionTernary(impl: _padEnd), FunctionTernary(impl: _padEndInt), ] ) case .testRegex: - return FunctionBinary(impl: _testRegex) + FunctionBinary(impl: _testRegex) } } } diff --git a/DivKit/Expressions/Serialization/Expression+Helpers.swift b/DivKit/Expressions/Serialization/Expression+Helpers.swift index 1d58f47a..cee03364 100644 --- a/DivKit/Expressions/Serialization/Expression+Helpers.swift +++ b/DivKit/Expressions/Serialization/Expression+Helpers.swift @@ -9,36 +9,53 @@ func expressionTransform( transform: (U) -> T?, validator: AnyValueValidator? = nil ) -> Expression? { - do { - if let rawValue = value as? String, - !rawValue.isEmpty, - let resolver = try ExpressionLink( - rawValue: rawValue, - validator: validator, - errorTracker: { DivKitLogger.error($0.description) } - ) { - return .link(resolver) - } - } catch { + guard let value else { return nil } - guard let value else { - return nil + if let rawValue = value as? String, !rawValue.isEmpty { + if let link = ExpressionLink( + rawValue: rawValue, + validator: validator, + errorTracker: { DivKitLogger.error($0.description) } + ) { + return .link(link) + } } - guard let value = value as? U else { + guard let castedValue: U = cast(value) else { DivKitLogger.error("Failed to cast value: \(value)") return nil } - if let transformedValue = transform(value), validator?.isValid(transformedValue) != false { + if let transformedValue = transform(castedValue), validator?.isValid(transformedValue) != false { return .value(transformedValue) } return nil } +@inlinable +func cast(_ value: Any) -> T? { + if let castedValue = value as? T { + return castedValue + } + + if T.self == Int.self, let doubleValue = value as? Double { + return Int(doubleValue) as? T + } + + if T.self == String.self { + if let intValue = value as? Int { + return String(intValue) as? T + } else if let doubleValue = value as? Double { + return String(doubleValue) as? T + } + } + + return nil +} + @inlinable func deserialize( _ value: Any, diff --git a/DivKit/Expressions/Serialization/Expression+ValidSerializationValue.swift b/DivKit/Expressions/Serialization/Expression+ValidSerializationValue.swift index 1ffb7266..01a6148d 100644 --- a/DivKit/Expressions/Serialization/Expression+ValidSerializationValue.swift +++ b/DivKit/Expressions/Serialization/Expression+ValidSerializationValue.swift @@ -7,9 +7,9 @@ extension Expression where T == Bool { func toValidSerializationValue() -> ValidSerializationValue { switch self { case let .value(value): - return value + value case let .link(link): - return link.rawValue + link.rawValue } } } @@ -18,9 +18,9 @@ extension Expression where T == Double { func toValidSerializationValue() -> ValidSerializationValue { switch self { case let .value(value): - return value + value case let .link(link): - return link.rawValue + link.rawValue } } } @@ -29,9 +29,9 @@ extension Expression where T == Int { func toValidSerializationValue() -> ValidSerializationValue { switch self { case let .value(value): - return value + value case let .link(link): - return link.rawValue + link.rawValue } } } @@ -40,9 +40,9 @@ extension Expression where T == Color { func toValidSerializationValue() -> String { switch self { case let .value(value): - return value.hexString + value.hexString case let .link(link): - return link.rawValue + link.rawValue } } } @@ -51,9 +51,9 @@ extension Expression where T == String { func toValidSerializationValue() -> String { switch self { case let .value(value): - return value + value case let .link(link): - return link.rawValue + link.rawValue } } } @@ -62,9 +62,9 @@ extension Expression where T == URL { func toValidSerializationValue() -> String { switch self { case let .value(value): - return value.absoluteString + value.absoluteString case let .link(link): - return link.rawValue + link.rawValue } } } @@ -73,9 +73,9 @@ extension Expression where T == [Any] { func toValidSerializationValue() -> ValidSerializationValue { switch self { case let .value(value): - return value + value case let .link(link): - return link.rawValue + link.rawValue } } } @@ -84,9 +84,9 @@ extension Expression where T: RawRepresentable, T.RawValue == String { func toValidSerializationValue() -> String { switch self { case let .value(value): - return value.rawValue + value.rawValue case let .link(link): - return link.rawValue + link.rawValue } } } diff --git a/DivKit/Expressions/ValueProvidersFactory.swift b/DivKit/Expressions/ValueProvidersFactory.swift index ff20cbcb..d5a496eb 100644 --- a/DivKit/Expressions/ValueProvidersFactory.swift +++ b/DivKit/Expressions/ValueProvidersFactory.swift @@ -1,10 +1,10 @@ func makeVariableValueProvider( cardId: DivCardID, variablesStorage: DivVariablesStorage, - prototypesStorage: [String: Any]? = nil + prototypesStorage: [String: AnyHashable]? = nil ) -> AnyCalcExpression.ValueProvider { { - if let value: Any = prototypesStorage?[$0] { + if let value: Any = prototypesStorage?[$0]?.base { return value } return variablesStorage.getVariableValue( diff --git a/DivKit/Extensions/DeserializationResultExtensions.swift b/DivKit/Extensions/DeserializationResultExtensions.swift index 39d88dba..952c423d 100644 --- a/DivKit/Extensions/DeserializationResultExtensions.swift +++ b/DivKit/Extensions/DeserializationResultExtensions.swift @@ -11,11 +11,11 @@ extension DeserializationResult { public func asCardResult(cardId: DivCardID) -> Self { switch self { case let .partialSuccess(value, warnings): - return .partialSuccess(value, warnings: warnings.map { $0.asCardError(cardId: cardId) }) + .partialSuccess(value, warnings: warnings.map { $0.asCardError(cardId: cardId) }) case let .failure(errors): - return .failure(errors.map { $0.asCardError(cardId: cardId) }) + .failure(errors.map { $0.asCardError(cardId: cardId) }) default: - return self + self } } } diff --git a/DivKit/Extensions/DivAccessibilityExtensions.swift b/DivKit/Extensions/DivAccessibilityExtensions.swift index ffb8d391..04c52107 100644 --- a/DivKit/Extensions/DivAccessibilityExtensions.swift +++ b/DivKit/Extensions/DivAccessibilityExtensions.swift @@ -61,10 +61,10 @@ extension DivAccessibility { struct CustomAccessibilityParams { static let `default` = CustomAccessibilityParams() - + let defaultTraits: AccessibilityElement.Traits let descriptionProvider: (() -> String?)? - + init( defaultTraits: AccessibilityElement.Traits = .none, descriptionProvider: (() -> String?)? = nil diff --git a/DivKit/Extensions/DivAction/DivActionBase.swift b/DivKit/Extensions/DivAction/DivActionBase.swift index 2bf5adec..bdf2e3e6 100644 --- a/DivKit/Extensions/DivAction/DivActionBase.swift +++ b/DivKit/Extensions/DivAction/DivActionBase.swift @@ -21,16 +21,16 @@ public protocol DivActionBase: Serializable { extension DivActionBase { func makeDivActionPayload( cardId: DivCardID, - source: UserInterfaceAction.DivActionSource + source: UserInterfaceAction.DivActionSource, + prototypeVariables: [String: AnyHashable] = [:] ) -> UserInterfaceAction.Payload { // url parameter is used for backward compatibility, it should be removed // when all custom div-action handlers will be replaced - let url: URL? - switch self.url { + let url: URL? = switch self.url { case let .value(value): - url = value.adding(cardId: cardId.rawValue) + value.adding(cardId: cardId.rawValue) case .link, .none: - url = nil + nil } return .divAction( @@ -38,7 +38,8 @@ extension DivActionBase { action: .object(toDictionary().typedJSON()), cardId: cardId.rawValue, source: source, - url: url + url: url, + prototypeVariables: prototypeVariables ) ) } diff --git a/DivKit/Extensions/DivAction/DivActionExtensions.swift b/DivKit/Extensions/DivAction/DivActionExtensions.swift index ffa361ac..0d5f1ab0 100644 --- a/DivKit/Extensions/DivAction/DivActionExtensions.swift +++ b/DivKit/Extensions/DivAction/DivActionExtensions.swift @@ -13,14 +13,17 @@ extension DivAction { payload = menuPayload } else { // don't make .divAction payloads for menu actions until DivActionHandler could handle it - payload = makeDivActionPayload(cardId: context.cardId, source: .tap) + payload = makeDivActionPayload( + cardId: context.cardId, + source: .tap, + prototypeVariables: context.prototypesStorage + ) } - let path: UIElementPath - if let cardLogId = context.cardLogId { - path = UIElementPath(cardLogId) + logId + let path = if let cardLogId = context.cardLogId { + UIElementPath(cardLogId) + logId } else { - path = UIElementPath(logId) + UIElementPath(logId) } return UserInterfaceAction(payload: payload, path: path) diff --git a/DivKit/Extensions/DivAnimationExtensions.swift b/DivKit/Extensions/DivAnimationExtensions.swift index 1991b007..bfc1658b 100644 --- a/DivKit/Extensions/DivAnimationExtensions.swift +++ b/DivKit/Extensions/DivAnimationExtensions.swift @@ -53,10 +53,10 @@ extension DivAnimation { extension DivAnimationInterpolator { func asTimingFunction() -> TimingFunction { switch self { - case .linear: return .linear - case .easeIn: return .easeIn - case .easeOut: return .easeOut - case .easeInOut, .ease, .spring: return .easeInEaseOut + case .linear: .linear + case .easeIn: .easeIn + case .easeOut: .easeOut + case .easeInOut, .ease, .spring: .easeInEaseOut } } } @@ -69,9 +69,9 @@ private enum TimeOrientation { extension DivAnimation.Name { fileprivate var kind: TransitioningAnimation.Kind? { switch self { - case .fade: return .fade - case .scale: return .scaleXY - case .set, .translate, .noAnimation, .native: return nil + case .fade: .fade + case .scale: .scaleXY + case .set, .translate, .noAnimation, .native: nil } } } @@ -101,8 +101,8 @@ extension TransitioningAnimation.Kind { extension TimeOrientation { fileprivate func inverted() -> Self { switch self { - case .direct: return .reverse - case .reverse: return .direct + case .direct: .reverse + case .reverse: .direct } } } diff --git a/DivKit/Extensions/DivAppearanceTransitionExtensions.swift b/DivKit/Extensions/DivAppearanceTransitionExtensions.swift index 48dc7906..59b2df36 100644 --- a/DivKit/Extensions/DivAppearanceTransitionExtensions.swift +++ b/DivKit/Extensions/DivAppearanceTransitionExtensions.swift @@ -36,9 +36,9 @@ extension DivAppearanceTransition { value1 = item.distance?.resolveScaledValue(expressionResolver).map { switch edge { case .left, .top: - return -$0 + -$0 case .right, .bottom: - return $0 + $0 } } ?? getDefaultSlideValue(edge) value2 = 0 @@ -67,9 +67,9 @@ extension TransitioningAnimationType { func inverted() -> Self { switch self { case .appearing: - return .disappearing + .disappearing case .disappearing: - return .appearing + .appearing } } } @@ -77,9 +77,9 @@ extension TransitioningAnimationType { fileprivate func getDefaultSlideValue(_ edge: DivSlideTransition.Edge) -> Double { switch edge { case .left, .top: - return TransitioningAnimation.defaultLeadingSlideDistance + TransitioningAnimation.defaultLeadingSlideDistance case .right, .bottom: - return TransitioningAnimation.defaultTrailingSlideDistance + TransitioningAnimation.defaultTrailingSlideDistance } } diff --git a/DivKit/Extensions/DivBase/DivBaseExtensions.swift b/DivKit/Extensions/DivBase/DivBaseExtensions.swift index 64797507..42e68e4b 100644 --- a/DivKit/Extensions/DivBase/DivBaseExtensions.swift +++ b/DivKit/Extensions/DivBase/DivBaseExtensions.swift @@ -15,11 +15,11 @@ extension DivBase { clipToBounds: Bool = true ) throws -> Block { let extensionHandlers = context.getExtensionHandlers(for: self) - + extensionHandlers.forEach { $0.accept(div: self, context: context) } - + let expressionResolver = context.expressionResolver let statePath = context.parentDivStatePath ?? DivData.rootPath @@ -32,7 +32,6 @@ extension DivBase { var block = try block() - extensionHandlers.forEach { block = $0.applyBeforeBaseProperties(to: block, div: self, context: context) } @@ -67,13 +66,12 @@ extension DivBase { ) let border = getBorder(isFocused) - let boundary: BoundaryTrait? - if !clipToBounds { - boundary = .noClip + let boundary: BoundaryTrait? = if !clipToBounds { + .noClip } else if let border { - boundary = .clipCorner(border.resolveCornerRadii(expressionResolver)) + .clipCorner(border.resolveCornerRadii(expressionResolver)) } else { - boundary = nil + nil } let shadow = border?.resolveShadow(expressionResolver) @@ -185,11 +183,14 @@ extension DivBase { } let expressionResolver = context.expressionResolver - let animationIn: [TransitioningAnimation]? - if isAppearing(statePath: statePath, id: id, context: context) { - animationIn = transitionIn?.resolveAnimations(expressionResolver, type: .appearing) + let animationIn: [TransitioningAnimation]? = if isAppearing( + statePath: statePath, + id: id, + context: context + ) { + transitionIn?.resolveAnimations(expressionResolver, type: .appearing) } else { - animationIn = nil + nil } context.stateManager.setBlockVisibility( @@ -304,15 +305,15 @@ extension LayoutTrait { fileprivate func trim(_ insets: SideInsets) -> LayoutTrait { switch self { case let .fixed(value): - return .fixed(value - insets.sum) + .fixed(value - insets.sum) case let .intrinsic(constrained, minSize, maxSize): - return .intrinsic( + .intrinsic( constrained: constrained, minSize: minSize - insets.sum, maxSize: maxSize - insets.sum ) case .weighted: - return self + self } } } diff --git a/DivKit/Extensions/DivChangeTransitionExtensions.swift b/DivKit/Extensions/DivChangeTransitionExtensions.swift index ef3d2979..ebeb28b5 100644 --- a/DivKit/Extensions/DivChangeTransitionExtensions.swift +++ b/DivKit/Extensions/DivChangeTransitionExtensions.swift @@ -6,14 +6,14 @@ extension DivChangeTransition { ) -> ChangeBoundsTransition? { switch self { case let .divChangeBoundsTransition(transition): - return ChangeBoundsTransition( + ChangeBoundsTransition( duration: Duration(milliseconds: transition.resolveDuration(expressionResolver)), delay: Delay(milliseconds: transition.resolveStartDelay(expressionResolver)), timingFunction: transition.resolveInterpolator(expressionResolver) .asTimingFunction() ) case .divChangeSetTransition: - return nil + nil } } } diff --git a/DivKit/Extensions/DivContainer/DivContainerExtensions.swift b/DivKit/Extensions/DivContainer/DivContainerExtensions.swift index 90d5a556..ee54c6d5 100644 --- a/DivKit/Extensions/DivContainer/DivContainerExtensions.swift +++ b/DivKit/Extensions/DivContainer/DivContainerExtensions.swift @@ -26,12 +26,11 @@ extension DivContainer: DivBlockModeling { ) let expressionResolver = context.expressionResolver let orientation = resolveOrientation(expressionResolver) - let block: Block - switch orientation { + let block: Block = switch orientation { case .overlap: - block = try makeOverlapBlock(context: childContext) + try makeOverlapBlock(context: childContext) case .horizontal, .vertical: - block = try makeContainerBlock( + try makeContainerBlock( context: childContext, orientation: orientation, layoutMode: resolveLayoutMode(expressionResolver) @@ -229,11 +228,11 @@ extension DivAlignmentHorizontal { var alignment: Alignment { switch self { case .left, .start: - return .leading + .leading case .center: - return .center + .center case .right, .end: - return .trailing + .trailing } } @@ -241,30 +240,30 @@ extension DivAlignmentHorizontal { .CrossAlignment { switch self { case .left: - return .leading + .leading case .right: - return .trailing + .trailing case .start: - return uiLayoutDirection == .leftToRight ? .leading : .trailing + uiLayoutDirection == .leftToRight ? .leading : .trailing case .center: - return .center + .center case .end: - return uiLayoutDirection == .rightToLeft ? .leading : .trailing + uiLayoutDirection == .rightToLeft ? .leading : .trailing } } func makeContentAlignment(uiLayoutDirection: UserInterfaceLayoutDirection) -> Alignment { switch self { case .left: - return .leading + .leading case .right: - return .trailing + .trailing case .start: - return uiLayoutDirection == .leftToRight ? .leading : .trailing + uiLayoutDirection == .leftToRight ? .leading : .trailing case .center: - return .center + .center case .end: - return uiLayoutDirection == .rightToLeft ? .leading : .trailing + uiLayoutDirection == .rightToLeft ? .leading : .trailing } } } @@ -287,13 +286,13 @@ extension DivAlignmentVertical { var crossAlignment: ContainerBlock.CrossAlignment { switch self { case .top: - return .leading + .leading case .center: - return .center + .center case .bottom: - return .trailing + .trailing case .baseline: - return .baseline + .baseline } } } @@ -334,9 +333,9 @@ extension DivContainer.LayoutMode { fileprivate var system: ContainerBlock.LayoutMode { switch self { case .noWrap: - return .noWrap + .noWrap case .wrap: - return .wrap + .wrap } } } @@ -351,30 +350,30 @@ fileprivate func makeCrossAlignment( case .horizontal: switch verticalAlignment { case .top: - return .leading + .leading case .center: - return .center + .center case .bottom: - return .trailing + .trailing case .baseline: - return .baseline + .baseline case .spaceBetween, .spaceEvenly, .spaceAround: - return .leading + .leading } case .vertical: switch horizontalAlignment { case .left: - return uiLayoutDirection == .leftToRight ? .leading : .trailing + uiLayoutDirection == .leftToRight ? .leading : .trailing case .right: - return uiLayoutDirection == .rightToLeft ? .leading : .trailing + uiLayoutDirection == .rightToLeft ? .leading : .trailing case .start: - return .leading + .leading case .center: - return .center + .center case .end: - return .trailing + .trailing case .spaceBetween, .spaceEvenly, .spaceAround: - return .center + .center } } } diff --git a/DivKit/Extensions/DivData/DivDataPatchExtensions.swift b/DivKit/Extensions/DivData/DivDataPatchExtensions.swift index 4a9b6a80..4cc29d37 100644 --- a/DivKit/Extensions/DivData/DivDataPatchExtensions.swift +++ b/DivKit/Extensions/DivData/DivDataPatchExtensions.swift @@ -62,19 +62,19 @@ extension Div { .divVideo, .divText: // no children - return self + self case let .divContainer(value): - return .divContainer(value.applyPatch(patch)) + .divContainer(value.applyPatch(patch)) case let .divGallery(value): - return .divGallery(value.applyPatch(patch)) + .divGallery(value.applyPatch(patch)) case let .divGrid(value): - return .divGrid(value.applyPatch(patch)) + .divGrid(value.applyPatch(patch)) case let .divPager(value): - return .divPager(value.applyPatch(patch)) + .divPager(value.applyPatch(patch)) case let .divState(value): - return .divState(value.applyPatch(patch)) + .divState(value.applyPatch(patch)) case let .divTabs(value): - return .divTabs(value.applyPatch(patch)) + .divTabs(value.applyPatch(patch)) } } } diff --git a/DivKit/Extensions/DivDrawable/DivDrawableExtensions.swift b/DivKit/Extensions/DivDrawable/DivDrawableExtensions.swift index 194fb0a0..0e74de22 100644 --- a/DivKit/Extensions/DivDrawable/DivDrawableExtensions.swift +++ b/DivKit/Extensions/DivDrawable/DivDrawableExtensions.swift @@ -11,7 +11,7 @@ extension DivDrawable { ) -> Block { switch self { case let .divShapeDrawable(shapeDrawable): - return shapeDrawable.makeBlock( + shapeDrawable.makeBlock( context: context, widthTrait: widthTrait, corners: corners @@ -22,14 +22,14 @@ extension DivDrawable { func resolveWidth(_ context: DivBlockModelingContext) -> CGFloat { switch self { case let .divShapeDrawable(shapeDrawable): - return shapeDrawable.resolveWidth(context) + shapeDrawable.resolveWidth(context) } } func resolveHeight(_ context: DivBlockModelingContext) -> CGFloat { switch self { case let .divShapeDrawable(shapeDrawable): - return shapeDrawable.resolveHeight(context) + shapeDrawable.resolveHeight(context) } } } diff --git a/DivKit/Extensions/DivExtensions.swift b/DivKit/Extensions/DivExtensions.swift index 020b1e9b..db80b328 100644 --- a/DivKit/Extensions/DivExtensions.swift +++ b/DivKit/Extensions/DivExtensions.swift @@ -3,13 +3,13 @@ import Foundation extension Div { var children: [Div] { switch self { - case let .divContainer(div): return div.nonNilItems - case let .divGrid(div): return div.nonNilItems - case let .divGallery(div): return div.nonNilItems - case let .divPager(div): return div.nonNilItems - case let .divTabs(div): return div.items.map(\.div) - case let .divCustom(div): return div.items ?? [] - case let .divState(div): return div.states.compactMap(\.div) + case let .divContainer(div): div.nonNilItems + case let .divGrid(div): div.nonNilItems + case let .divGallery(div): div.nonNilItems + case let .divPager(div): div.nonNilItems + case let .divTabs(div): div.items.map(\.div) + case let .divCustom(div): div.items ?? [] + case let .divState(div): div.states.compactMap(\.div) case .divGifImage, .divImage, .divIndicator, @@ -19,7 +19,7 @@ extension Div { .divSlider, .divVideo, .divText: - return [] + [] } } } @@ -28,18 +28,18 @@ extension Div { var isHorizontallyMatchParent: Bool { switch value.width { case .divMatchParentSize: - return true + true case .divFixedSize, .divWrapContentSize: - return false + false } } var isVerticallyMatchParent: Bool { switch value.height { case .divMatchParentSize: - return true + true case .divFixedSize, .divWrapContentSize: - return false + false } } } diff --git a/DivKit/Extensions/DivFontWeightExtensions.swift b/DivKit/Extensions/DivFontWeightExtensions.swift index 27e35878..bd344e20 100644 --- a/DivKit/Extensions/DivFontWeightExtensions.swift +++ b/DivKit/Extensions/DivFontWeightExtensions.swift @@ -4,13 +4,13 @@ extension DivFontWeight { var fontWeight: Font.Weight { switch self { case .light: - return .light + .light case .regular: - return .regular + .regular case .medium: - return .medium + .medium case .bold: - return .bold + .bold } } } diff --git a/DivKit/Extensions/DivGallery/DivGalleryExtensions.swift b/DivKit/Extensions/DivGallery/DivGalleryExtensions.swift index e1bab6e8..7d48ae0f 100644 --- a/DivKit/Extensions/DivGallery/DivGalleryExtensions.swift +++ b/DivKit/Extensions/DivGallery/DivGalleryExtensions.swift @@ -48,6 +48,7 @@ extension DivGallery: DivBlockModeling, DivGalleryProtocol { ) -> GalleryViewState { let path = context.parentPath let index: CGFloat + let scrollRange: CGFloat? if let state: GalleryViewState = context.blockStateStorage.getState(path) { switch state.contentPosition { case .offset: @@ -55,6 +56,7 @@ extension DivGallery: DivBlockModeling, DivGalleryProtocol { case let .paging(savedIndex): index = savedIndex } + scrollRange = state.scrollRange } else { index = CGFloat(resolveDefaultItem(context.expressionResolver)) if index == 0 { @@ -62,11 +64,14 @@ extension DivGallery: DivBlockModeling, DivGalleryProtocol { context.blockStateStorage.setState(path: path, state: newState) return newState } + scrollRange = nil } let newState = GalleryViewState( - contentPageIndex: index.clamp(0.0...CGFloat(itemsCount - 1)), - itemsCount: itemsCount + contentPosition: .paging(index: index.clamp(0.0...CGFloat(itemsCount - 1))), + itemsCount: itemsCount, + isScrolling: false, + scrollRange: scrollRange ) context.blockStateStorage.setState(path: path, state: newState) return newState @@ -77,9 +82,9 @@ extension DivGallery.Orientation { fileprivate var direction: GalleryViewModel.Direction { switch self { case .horizontal: - return .horizontal + .horizontal case .vertical: - return .vertical + .vertical } } } @@ -88,9 +93,9 @@ extension DivGallery.ScrollMode { fileprivate var blockScrollMode: GalleryViewModel.ScrollMode { switch self { case .default: - return .default + .default case .paging: - return .autoPaging + .autoPaging } } } @@ -98,9 +103,9 @@ extension DivGallery.ScrollMode { extension DivGallery.CrossContentAlignment { fileprivate var blockAlignment: Alignment { switch self { - case .start: return .leading - case .center: return .center - case .end: return .trailing + case .start: .leading + case .center: .center + case .end: .trailing } } } @@ -109,9 +114,9 @@ extension DivGallery.Scrollbar { fileprivate var blockScrollbar: GalleryViewModel.Scrollbar { switch self { case .none: - return .none + .none case .auto: - return .auto + .auto } } } diff --git a/DivKit/Extensions/DivGridExtensions.swift b/DivKit/Extensions/DivGridExtensions.swift index 50885ead..7138b1f8 100644 --- a/DivKit/Extensions/DivGridExtensions.swift +++ b/DivKit/Extensions/DivGridExtensions.swift @@ -88,9 +88,9 @@ extension DivSize { ) -> LayoutTrait.Weight? { switch self { case .divFixedSize, .divWrapContentSize: - return nil + nil case let .divMatchParentSize(size): - return size.resolveWeight(expressionResolver) + size.resolveWeight(expressionResolver) .flatMap { LayoutTrait.Weight(floatLiteral: $0) } } } diff --git a/DivKit/Extensions/DivImage/DivImageContentMode.swift b/DivKit/Extensions/DivImage/DivImageContentMode.swift index e956e356..ae6f0d70 100644 --- a/DivKit/Extensions/DivImage/DivImageContentMode.swift +++ b/DivKit/Extensions/DivImage/DivImageContentMode.swift @@ -28,13 +28,13 @@ extension DivImageScale { fileprivate var contentModeScale: ImageContentMode.Scale { switch self { case .fill: - return .aspectFill + .aspectFill case .fit: - return .aspectFit + .aspectFit case .stretch: - return .resize + .resize case .noScale: - return .noScale + .noScale } } } @@ -59,11 +59,11 @@ extension DivAlignmentHorizontal { fileprivate var contentModeAlignment: ImageContentMode.HorizontalAlignment { switch self { case .left, .start: - return .left + .left case .center: - return .center + .center case .right, .end: - return .right + .right } } @@ -71,15 +71,15 @@ extension DivAlignmentHorizontal { .HorizontalAlignment { switch self { case .left: - return .left + .left case .center: - return .center + .center case .right: - return .right + .right case .start: - return uiLayoutDirection == .leftToRight ? .left : .right + uiLayoutDirection == .leftToRight ? .left : .right case .end: - return uiLayoutDirection == .leftToRight ? .right : .left + uiLayoutDirection == .leftToRight ? .right : .left } } } diff --git a/DivKit/Extensions/DivImage/DivImageExtensions.swift b/DivKit/Extensions/DivImage/DivImageExtensions.swift index 268c157f..5fd9550a 100644 --- a/DivKit/Extensions/DivImage/DivImageExtensions.swift +++ b/DivKit/Extensions/DivImage/DivImageExtensions.swift @@ -20,11 +20,12 @@ extension DivImage: DivBlockModeling, DivImageProtocol { let expressionResolver = context.expressionResolver let highPriority = resolveHighPriorityPreviewShow(expressionResolver) - let imageHolderFactory: DivImageHolderFactory - if highPriority, let highPriorityImageHolderFactory = context.highPriorityImageHolderFactory { - imageHolderFactory = highPriorityImageHolderFactory + let imageHolderFactory: DivImageHolderFactory = if highPriority, + let highPriorityImageHolderFactory = context + .highPriorityImageHolderFactory { + highPriorityImageHolderFactory } else { - imageHolderFactory = context.imageHolderFactory + context.imageHolderFactory } return ImageBlock( @@ -47,17 +48,17 @@ extension DivBlendMode { fileprivate var tintMode: TintMode { switch self { case .sourceIn: - return .sourceIn + .sourceIn case .sourceAtop: - return .sourceAtop + .sourceAtop case .darken: - return .darken + .darken case .lighten: - return .lighten + .lighten case .multiply: - return .multiply + .multiply case .screen: - return .screen + .screen } } } diff --git a/DivKit/Extensions/DivImage/DivImageProtocol.swift b/DivKit/Extensions/DivImage/DivImageProtocol.swift index 2e1648e3..5c3e1992 100644 --- a/DivKit/Extensions/DivImage/DivImageProtocol.swift +++ b/DivKit/Extensions/DivImage/DivImageProtocol.swift @@ -24,9 +24,9 @@ extension DivImageProtocol { ) -> ImagePlaceholder { if let base64 = resolvePreview(expressionResolver) { - return .imageData(ImageData(base64: base64, highPriority: highPriority)) + .imageData(ImageData(base64: base64, highPriority: highPriority)) } else { - return .color(resolvePlaceholderColor(expressionResolver)) + .color(resolvePlaceholderColor(expressionResolver)) } } diff --git a/DivKit/Extensions/DivIndicatorExtensions.swift b/DivKit/Extensions/DivIndicatorExtensions.swift index a8e7cbe6..f55b4392 100644 --- a/DivKit/Extensions/DivIndicatorExtensions.swift +++ b/DivKit/Extensions/DivIndicatorExtensions.swift @@ -126,9 +126,9 @@ extension DivShape { fileprivate var rectangle: DivRoundedRectangleShape? { switch self { case let .divRoundedRectangleShape(rectangle): - return rectangle + rectangle case .divCircleShape: - return nil + nil } } } @@ -137,11 +137,11 @@ extension DivIndicator.Animation { fileprivate var asBlockAnimation: PageIndicatorConfiguration.Animation { switch self { case .scale: - return .scale + .scale case .worm: - return .worm + .worm case .slider: - return .slider + .slider } } } @@ -152,13 +152,13 @@ extension DivIndicatorItemPlacement { ) -> PageIndicatorConfiguration.ItemPlacement { switch self { case let .divDefaultIndicatorItemPlacement(placement): - return .fixed( + .fixed( spaceBetweenCenters: CGFloat( placement.spaceBetweenCenters.resolveValue(expressionResolver) ?? 0 ) ) case let .divStretchIndicatorItemPlacement(placement): - return .stretch( + .stretch( spacing: CGFloat(placement.itemSpacing.resolveValue(expressionResolver) ?? 0), maxVisibleItems: placement.resolveMaxVisibleItems(expressionResolver) ) diff --git a/DivKit/Extensions/DivInputExtensions.swift b/DivKit/Extensions/DivInputExtensions.swift index d4221a73..97e85be8 100644 --- a/DivKit/Extensions/DivInputExtensions.swift +++ b/DivKit/Extensions/DivInputExtensions.swift @@ -144,15 +144,15 @@ extension DivAlignmentHorizontal { fileprivate var textAlignment: TextInputBlock.TextAlignmentHorizontal { switch self { case .left: - return .left + .left case .center: - return .center + .center case .right: - return .right + .right case .start: - return .start + .start case .end: - return .end + .end } } } @@ -177,15 +177,15 @@ extension DivInput.KeyboardType { fileprivate var system: TextInputBlock.InputType { switch self { case .singleLineText, .multiLineText: - return .default + .default case .phone: - return .keyboard(.phonePad) + .keyboard(.phonePad) case .number: - return .keyboard(.decimalPad) + .keyboard(.decimalPad) case .email: - return .keyboard(.emailAddress) + .keyboard(.emailAddress) case .uri: - return .keyboard(.URL) + .keyboard(.URL) } } } @@ -194,16 +194,16 @@ extension DivInputMask { fileprivate func makeMaskValidator(_ resolver: ExpressionResolver) -> MaskValidator? { switch self { case let .divFixedLengthInputMask(divFixedLengthInputMask): - return MaskValidator(formatter: FixedLengthMaskFormatter( + MaskValidator(formatter: FixedLengthMaskFormatter( pattern: divFixedLengthInputMask.resolvePattern(resolver) ?? "", alwaysVisible: divFixedLengthInputMask.resolveAlwaysVisible(resolver), patternElements: divFixedLengthInputMask.patternElements .map { $0.makePatternElement(resolver) } )) case .divCurrencyInputMask: - return nil + nil case .divPhoneInputMask: - return MaskValidator(formatter: PhoneMaskFormatter( + MaskValidator(formatter: PhoneMaskFormatter( masksByCountryCode: PhoneMasks().value.typedJSON(), extraSymbols: PhoneMasks.extraNumbers )) @@ -213,14 +213,14 @@ extension DivInputMask { fileprivate func makeRawVariable(_ context: DivBlockModelingContext) -> Binding? { switch self { case let .divFixedLengthInputMask(divFixedLengthInputMask): - return context.makeBinding( + context.makeBinding( variableName: divFixedLengthInputMask.rawTextVariable, defaultValue: "" ) case .divCurrencyInputMask: - return nil + nil case let .divPhoneInputMask(divPhoneInputMask): - return context.makeBinding( + context.makeBinding( variableName: divPhoneInputMask.rawTextVariable, defaultValue: "" ) diff --git a/DivKit/Extensions/DivPagerExtensions.swift b/DivKit/Extensions/DivPagerExtensions.swift index 09947ce4..d454a679 100644 --- a/DivKit/Extensions/DivPagerExtensions.swift +++ b/DivKit/Extensions/DivPagerExtensions.swift @@ -68,8 +68,8 @@ extension DivPager: DivBlockModeling, DivGalleryProtocol { extension DivPager.Orientation { var direction: GalleryViewModel.Direction { switch self { - case .horizontal: return .horizontal - case .vertical: return .vertical + case .horizontal: .horizontal + case .vertical: .vertical } } } diff --git a/DivKit/Extensions/DivPivotExtensions.swift b/DivKit/Extensions/DivPivotExtensions.swift index 63a81a70..24aa3d49 100644 --- a/DivKit/Extensions/DivPivotExtensions.swift +++ b/DivKit/Extensions/DivPivotExtensions.swift @@ -6,9 +6,9 @@ extension DivPivot { func resolveAnchorValue(_ expressionResolver: ExpressionResolver) -> AnchorValue { switch self { case let .divPivotPercentage(value): - return .relative(value: value.resolveValue(expressionResolver) ?? 50) + .relative(value: value.resolveValue(expressionResolver) ?? 50) case let .divPivotFixed(value): - return .absolute(value: value.resolveValue(expressionResolver).flatMap(CGFloat.init) ?? 0) + .absolute(value: value.resolveValue(expressionResolver).flatMap(CGFloat.init) ?? 0) } } } diff --git a/DivKit/Extensions/DivSeparatorExtensions.swift b/DivKit/Extensions/DivSeparatorExtensions.swift index f0b66d6f..026d6121 100644 --- a/DivKit/Extensions/DivSeparatorExtensions.swift +++ b/DivKit/Extensions/DivSeparatorExtensions.swift @@ -79,9 +79,9 @@ extension DivSeparator.DelimiterStyle.Orientation { fileprivate var direction: SeparatorBlock.Direction { switch self { case .horizontal: - return .horizontal + .horizontal case .vertical: - return .vertical + .vertical } } } diff --git a/DivKit/Extensions/DivSizeExtensions.swift b/DivKit/Extensions/DivSizeExtensions.swift index 423f7839..34b3ea66 100644 --- a/DivKit/Extensions/DivSizeExtensions.swift +++ b/DivKit/Extensions/DivSizeExtensions.swift @@ -41,9 +41,9 @@ extension DivSize { var isIntrinsic: Bool { switch self { case .divFixedSize, .divMatchParentSize: - return false + false case .divWrapContentSize: - return true + true } } } @@ -53,13 +53,13 @@ extension DivSize: Equatable { public static func ==(lhs: DivSize, rhs: DivSize) -> Bool { switch (lhs, rhs) { case let (.divFixedSize(l), .divFixedSize(r)): - return l == r + l == r case let (.divMatchParentSize(l), .divMatchParentSize(r)): - return l == r + l == r case let (.divWrapContentSize(l), .divWrapContentSize(r)): - return l == r + l == r default: - return false + false } } } diff --git a/DivKit/Extensions/DivSizeUnitExtensions.swift b/DivKit/Extensions/DivSizeUnitExtensions.swift index ce810676..d35da92c 100644 --- a/DivKit/Extensions/DivSizeUnitExtensions.swift +++ b/DivKit/Extensions/DivSizeUnitExtensions.swift @@ -15,9 +15,9 @@ extension DivSizeUnit { private var scale: CGFloat { switch self { case .px: - return PlatformDescription.screenScale() + PlatformDescription.screenScale() case .dp, .sp: - return 1 + 1 } } } diff --git a/DivKit/Extensions/DivStateExtensions.swift b/DivKit/Extensions/DivStateExtensions.swift index 457e1e72..b52102a5 100644 --- a/DivKit/Extensions/DivStateExtensions.swift +++ b/DivKit/Extensions/DivStateExtensions.swift @@ -132,11 +132,11 @@ extension DivState: DivBlockModeling { ) -> DivState.State? { switch stateManagerItem.previousState { case .empty: - return nil + nil case .initial: - return states[0] + states[0] case let .withID(stateId): - return states.first(where: { $0.stateId == stateId.rawValue }) + states.first(where: { $0.stateId == stateId.rawValue }) } } } @@ -180,10 +180,10 @@ extension TransitioningAnimation.Kind { extension DivAnimation.Name { fileprivate var kind: TransitioningAnimation.Kind? { switch self { - case .fade: return .fade - case .scale: return .scaleXY - case .translate: return .translationY - case .set, .noAnimation, .native: return nil + case .fade: .fade + case .scale: .scaleXY + case .translate: .translationY + case .set, .noAnimation, .native: nil } } } diff --git a/DivKit/Extensions/DivTabsExtensions.swift b/DivKit/Extensions/DivTabsExtensions.swift index 00184f7c..53d1b9b1 100644 --- a/DivKit/Extensions/DivTabsExtensions.swift +++ b/DivKit/Extensions/DivTabsExtensions.swift @@ -89,11 +89,10 @@ extension DivTabs: DivBlockModeling { ) -> TabViewState { let stateStorage = context.blockStateStorage let path = context.parentPath - let index: CGFloat - if let state: TabViewState = stateStorage.getState(path) { - index = state.selectedPageIndex + let index: CGFloat = if let state: TabViewState = stateStorage.getState(path) { + state.selectedPageIndex } else { - index = CGFloat(resolveSelectedTab(context.expressionResolver)) + CGFloat(resolveSelectedTab(context.expressionResolver)) } let newState = TabViewState( selectedPageIndex: min(index, CGFloat(tabs.count) - 1), @@ -180,9 +179,9 @@ extension DivTabs.TabTitleStyle { extension Typo { fileprivate func with(height: Int?) -> Typo { if let height { - return with(height: CGFloat(height)) + with(height: CGFloat(height)) } else { - return self + self } } } diff --git a/DivKit/Extensions/DivTextExtensions.swift b/DivKit/Extensions/DivTextExtensions.swift index 98e39db4..6f12afce 100644 --- a/DivKit/Extensions/DivTextExtensions.swift +++ b/DivKit/Extensions/DivTextExtensions.swift @@ -255,15 +255,15 @@ extension DivAlignmentHorizontal { ) -> TextAlignment { switch self { case .start: - return uiLayoutDirection == .leftToRight ? .left : .right + uiLayoutDirection == .leftToRight ? .left : .right case .end: - return uiLayoutDirection == .leftToRight ? .right : .left + uiLayoutDirection == .leftToRight ? .right : .left case .left: - return .left + .left case .center: - return .center + .center case .right: - return .right + .right } } } @@ -325,8 +325,8 @@ extension DivText.Range { extension DivLineStyle { fileprivate var underlineStyle: UnderlineStyle { switch self { - case .none: return [] - case .single: return .single + case .none: [] + case .single: .single } } } diff --git a/DivKit/Extensions/DivTooltipExtensions.swift b/DivKit/Extensions/DivTooltipExtensions.swift index 0da9a120..8e2eddd6 100644 --- a/DivKit/Extensions/DivTooltipExtensions.swift +++ b/DivKit/Extensions/DivTooltipExtensions.swift @@ -40,15 +40,15 @@ extension DivTooltip { extension DivTooltip.Position { fileprivate func cast() -> BlockTooltip.Position { switch self { - case .left: return .left - case .topLeft: return .topLeft - case .top: return .top - case .topRight: return .topRight - case .right: return .right - case .bottomRight: return .bottomRight - case .bottom: return .bottom - case .bottomLeft: return .bottomLeft - case .center: return .center + case .left: .left + case .topLeft: .topLeft + case .top: .top + case .topRight: .topRight + case .right: .right + case .bottomRight: .bottomRight + case .bottom: .bottom + case .bottomLeft: .bottomLeft + case .center: .center } } } diff --git a/DivKit/Extensions/DivVideoExtensions.swift b/DivKit/Extensions/DivVideoExtensions.swift index 368e42ee..2890fbfa 100644 --- a/DivKit/Extensions/DivVideoExtensions.swift +++ b/DivKit/Extensions/DivVideoExtensions.swift @@ -99,11 +99,11 @@ extension DivVideoScale { fileprivate var scale: VideoScale { switch self { case .fill: - return .fill + .fill case .noScale: - return .noScale + .noScale case .fit: - return .fit + .fit } } } diff --git a/DivKit/Extensions/GradientExtentions.swift b/DivKit/Extensions/GradientExtentions.swift index ea74f8ff..7552e389 100644 --- a/DivKit/Extensions/GradientExtentions.swift +++ b/DivKit/Extensions/GradientExtentions.swift @@ -71,17 +71,17 @@ extension DivRadialGradient { func resolveRadius(_ resolver: ExpressionResolver) -> Gradient.Radial.Radius { switch radius { case let .divFixedSize(size): - return .absolute(size.resolveValue(resolver) ?? 0) + .absolute(size.resolveValue(resolver) ?? 0) case let .divRadialGradientRelativeRadius(radius): switch radius.resolveValue(resolver) ?? .farthestCorner { case .farthestCorner: - return .relativeToBorders(.farthestCorner) + .relativeToBorders(.farthestCorner) case .farthestSide: - return .relativeToBorders(.farthestSide) + .relativeToBorders(.farthestSide) case .nearestCorner: - return .relativeToBorders(.nearestCorner) + .relativeToBorders(.nearestCorner) case .nearestSide: - return .relativeToBorders(.nearestSide) + .relativeToBorders(.nearestSide) } } } @@ -89,18 +89,18 @@ extension DivRadialGradient { func resolveCenterX(_ resolver: ExpressionResolver) -> Gradient.Radial.CenterPoint { switch centerX { case let .divRadialGradientRelativeCenter(x): - return .relative(x.resolveValue(resolver) ?? 0) + .relative(x.resolveValue(resolver) ?? 0) case let .divRadialGradientFixedCenter(x): - return .absolute(x.resolveValue(resolver) ?? 0) + .absolute(x.resolveValue(resolver) ?? 0) } } func resolveCenterY(_ resolver: ExpressionResolver) -> Gradient.Radial.CenterPoint { switch centerY { case let .divRadialGradientRelativeCenter(y): - return .relative(y.resolveValue(resolver) ?? 0) + .relative(y.resolveValue(resolver) ?? 0) case let .divRadialGradientFixedCenter(y): - return .absolute(y.resolveValue(resolver) ?? 0) + .absolute(y.resolveValue(resolver) ?? 0) } } } diff --git a/DivKit/RunLoopCardUpdateAggregator.swift b/DivKit/RunLoopCardUpdateAggregator.swift index fa778854..9dcf8bdb 100644 --- a/DivKit/RunLoopCardUpdateAggregator.swift +++ b/DivKit/RunLoopCardUpdateAggregator.swift @@ -42,7 +42,7 @@ final class RunLoopCardUpdateAggregator { batch = [] updateCardAction(reasons) } - + func forceUpdate() { batch.append(.variable(.all)) flushUpdateActions() diff --git a/DivKit/States/DivStateManager.swift b/DivKit/States/DivStateManager.swift index 5226d2e6..9d8a5104 100644 --- a/DivKit/States/DivStateManager.swift +++ b/DivKit/States/DivStateManager.swift @@ -97,11 +97,10 @@ public class DivStateManager { private func updateState(path: DivStatePath, stateID: DivStateID) { // need to take a write lock before let previousItem = _items[path] - let previousState: PreviousState - if let previousStateID = previousItem?.currentStateID { - previousState = .withID(previousStateID) + let previousState: PreviousState = if let previousStateID = previousItem?.currentStateID { + .withID(previousStateID) } else { - previousState = .initial + .initial } _stateBindings[path]?.value = stateID.rawValue _items[path] = Item( diff --git a/DivKit/StoredValues/DivPersistentValuesStorage.swift b/DivKit/StoredValues/DivPersistentValuesStorage.swift index 68d91b2f..abd36453 100644 --- a/DivKit/StoredValues/DivPersistentValuesStorage.swift +++ b/DivKit/StoredValues/DivPersistentValuesStorage.swift @@ -83,39 +83,39 @@ extension DivStoredValue { var variable: DivVariableValue? { switch type { case .string: - return .string(value) + .string(value) case .number: if let value = Double(value) { - return .number(value) + .number(value) } else { - return nil + nil } case .integer: if let value = Int(value) { - return .integer(value) + .integer(value) } else { - return nil + nil } case .bool: switch value.lowercased() { case "0", "false": - return .bool(false) + .bool(false) case "1", "true": - return .bool(true) + .bool(true) default: - return nil + nil } case .color: if let value = Color.color(withHexString: value) { - return .color(value) + .color(value) } else { - return nil + nil } case .url: if let value = URL(string: value) { - return .url(value) + .url(value) } else { - return nil + nil } } } diff --git a/DivKit/Templates/Field.swift b/DivKit/Templates/Field.swift index 1bfede28..c65075b4 100644 --- a/DivKit/Templates/Field.swift +++ b/DivKit/Templates/Field.swift @@ -39,8 +39,8 @@ extension Field { var link: String? { switch self { - case .value: return nil - case let .link(link): return link + case .value: nil + case let .link(link): link } } @@ -165,9 +165,9 @@ extension Field where T: TemplateValue { func resolveParent(templates: [TemplateName: Any]) throws -> Field { switch self { case let .link(link): - return .link(link) + .link(link) case let .value(value): - return try .value(value.resolveParent(templates: templates)) + try .value(value.resolveParent(templates: templates)) } } @@ -200,9 +200,9 @@ extension Field where T: TemplateValue { func tryResolveParent(templates: [TemplateName: Any]) -> Field? { switch self { case .link: - return self + self case let .value(value): - return value.tryResolveParent(templates: templates).map(Field.value) + value.tryResolveParent(templates: templates).map(Field.value) } } diff --git a/DivKit/Variables/DivTriggersStorage.swift b/DivKit/Variables/DivTriggersStorage.swift index 41790e07..1d78bc82 100644 --- a/DivKit/Variables/DivTriggersStorage.swift +++ b/DivKit/Variables/DivTriggersStorage.swift @@ -104,9 +104,9 @@ extension DivVariablesStorage.ChangeEvent.Kind { var names: Set { switch self { case let .local(_, names): - return names + names case let .global(names): - return names + names } } } @@ -117,9 +117,9 @@ private func makeChangedCardIds( ) -> [DivCardID] { switch eventKind { case let .local(cardId, _): - return [cardId] + [cardId] case .global: - return cardIds + cardIds } } @@ -168,9 +168,9 @@ extension Expression { fileprivate var variablesNames: Set { switch self { case let .link(link): - return Set(link.variablesNames.map(DivVariableName.init(rawValue:))) + Set(link.variablesNames.map(DivVariableName.init(rawValue:))) case .value: - return [] + [] } } } diff --git a/DivKit/Variables/DivVariablesStorage.swift b/DivKit/Variables/DivVariablesStorage.swift index cfbefd44..7efed75d 100644 --- a/DivKit/Variables/DivVariablesStorage.swift +++ b/DivKit/Variables/DivVariablesStorage.swift @@ -87,7 +87,7 @@ public final class DivVariablesStorage { cardId: DivCardID, variables: DivVariables ) { - var changeEvent: ChangeEvent? = nil + var changeEvent: ChangeEvent? lock.write { let oldValues = allValues cardVariables[cardId] = variables diff --git a/DivKit/Views/DivBlockProvider.swift b/DivKit/Views/DivBlockProvider.swift index 3df961c6..f56af59c 100644 --- a/DivKit/Views/DivBlockProvider.swift +++ b/DivKit/Views/DivBlockProvider.swift @@ -42,7 +42,7 @@ final class DivBlockProvider { cardSize = DivViewSize(block: block) } } - + weak var parentScrollView: ScrollView? { didSet { guard oldValue !== parentScrollView else { return } @@ -262,9 +262,9 @@ extension DivActionURLHandler.UpdateReason { fileprivate func patch(for divCardId: DivCardID) -> DivPatch? { switch self { case let .patch(cardId, patch): - return cardId == divCardId ? patch : nil + cardId == divCardId ? patch : nil case .timer, .variable, .state: - return nil + nil } } } diff --git a/DivKit/Views/DivView.swift b/DivKit/Views/DivView.swift index 105ef928..14ab7b35 100644 --- a/DivKit/Views/DivView.swift +++ b/DivKit/Views/DivView.swift @@ -146,14 +146,13 @@ public final class DivView: VisibleBoundsTrackingView { assertionFailure("Width depends on other dimension size") width = DivView.noIntrinsicMetric } - let height: CGFloat - switch cardSize.height { + let height: CGFloat = switch cardSize.height { case .matchParent: - height = bounds.height == 0 ? DivView.noIntrinsicMetric : bounds.height + bounds.height == 0 ? DivView.noIntrinsicMetric : bounds.height case let .desired(value): - height = value + value case let .dependsOnOtherDimensionSize(heightForWidth): - height = heightForWidth(width) + heightForWidth(width) } return CGSize(width: width, height: height) } diff --git a/DivKit/Views/DivViewSize.swift b/DivKit/Views/DivViewSize.swift index 6a23c06a..b77a6d3c 100644 --- a/DivKit/Views/DivViewSize.swift +++ b/DivKit/Views/DivViewSize.swift @@ -20,12 +20,12 @@ public struct DivViewSize: Equatable { public static func ==(lhs: DivDimension, rhs: DivDimension) -> Bool { switch (lhs, rhs) { case let (.desired(lhs), .desired(rhs)): - return lhs == rhs + lhs == rhs case (.matchParent, .matchParent), (.dependsOnOtherDimensionSize, dependsOnOtherDimensionSize): - return true + true default: - return false + false } } } @@ -59,14 +59,13 @@ public struct DivViewSize: Equatable { assertionFailure("Unexpected width") width = -1 } - let height: CGFloat - switch self.height { + let height: CGFloat = switch self.height { case .matchParent: - height = parentViewSize.height + parentViewSize.height case let .desired(value): - height = value + value case let .dependsOnOtherDimensionSize(heightForWidth): - height = heightForWidth(width) + heightForWidth(width) } return CGSize(width: width, height: height) } diff --git a/DivKitExtensions/Animations/AnimationHolder.swift b/DivKitExtensions/Animations/AnimationHolder.swift index a77e158c..d134abae 100644 --- a/DivKitExtensions/Animations/AnimationHolder.swift +++ b/DivKitExtensions/Animations/AnimationHolder.swift @@ -22,11 +22,11 @@ func ==(lhs: AnimationHolder, rhs: AnimationHolder) -> Bool { func ==(lhs: AnimationHolder?, rhs: AnimationHolder?) -> Bool { switch (lhs, rhs) { case (.none, .none): - return true + true case let (.some(value1), .some(value2)): - return value1 == value2 + value1 == value2 default: - return false + false } } diff --git a/DivKitExtensions/Animations/AnimationSourceType.swift b/DivKitExtensions/Animations/AnimationSourceType.swift index 246ab79e..ea3a7768 100644 --- a/DivKitExtensions/Animations/AnimationSourceType.swift +++ b/DivKitExtensions/Animations/AnimationSourceType.swift @@ -10,11 +10,11 @@ public enum LottieAnimationSourceType: AnimationSourceType, Equatable { public static func ==(lhs: LottieAnimationSourceType, rhs: LottieAnimationSourceType) -> Bool { switch (lhs, rhs) { case let (.data(lhs), .data(rhs)): - return lhs == rhs + lhs == rhs case let (.json(lhs), .json(rhs)): - return NSDictionary(dictionary: lhs).isEqual(to: rhs) + NSDictionary(dictionary: lhs).isEqual(to: rhs) case (.data, _), (.json, _): - return false + false } } } @@ -26,7 +26,7 @@ public enum RiveAnimationSourceType: AnimationSourceType, Equatable { public static func ==(lhs: RiveAnimationSourceType, rhs: RiveAnimationSourceType) -> Bool { switch (lhs, rhs) { case let (.data(lhs), .data(rhs)): - return lhs == rhs + lhs == rhs } } } diff --git a/DivKitExtensions/Animations/Lottie/LottieExtensionHandler.swift b/DivKitExtensions/Animations/Lottie/LottieExtensionHandler.swift index d25d0b2b..795ac7e6 100644 --- a/DivKitExtensions/Animations/Lottie/LottieExtensionHandler.swift +++ b/DivKitExtensions/Animations/Lottie/LottieExtensionHandler.swift @@ -33,17 +33,16 @@ public final class LottieExtensionHandler: DivExtensionHandler { return block } - let animationHolder: AnimationHolder - switch params.source { + let animationHolder: AnimationHolder = switch params.source { case let .url(url): - animationHolder = RemoteAnimationHolder( + RemoteAnimationHolder( url: url, animationType: .lottie, requester: requester, localDataProvider: localAnimationDataProvider ) case let .json(json): - animationHolder = JSONAnimationHolder(json: json) + JSONAnimationHolder(json: json) } return LottieAnimationBlock( animatableView: Lazy( @@ -150,8 +149,8 @@ private struct LottieExtensionParams { extension LottieExtensionParams.Source { fileprivate var url: URL? { switch self { - case let .url(url): return url - case .json: return nil + case let .url(url): url + case .json: nil } } } diff --git a/DivKitExtensions/Animations/Rive/RiveAnimationBlock.swift b/DivKitExtensions/Animations/Rive/RiveAnimationBlock.swift index 7cc429ad..d1ad7eaf 100644 --- a/DivKitExtensions/Animations/Rive/RiveAnimationBlock.swift +++ b/DivKitExtensions/Animations/Rive/RiveAnimationBlock.swift @@ -28,22 +28,22 @@ public final class RiveAnimationBlock: BlockWithTraits { public var intrinsicContentWidth: CGFloat { switch widthTrait { case let .fixed(value): - return value + value case let .intrinsic(_, minSize, _): - return minSize + minSize case .weighted: - return 0 + 0 } } public func intrinsicContentHeight(forWidth _: CGFloat) -> CGFloat { switch heightTrait { case let .fixed(value): - return value + value case let .intrinsic(_, minSize, _): - return minSize + minSize case .weighted: - return 0 + 0 } } diff --git a/DivKitExtensions/DivBackgroundExtensions.swift b/DivKitExtensions/DivBackgroundExtensions.swift index daea4850..54ededc2 100644 --- a/DivKitExtensions/DivBackgroundExtensions.swift +++ b/DivKitExtensions/DivBackgroundExtensions.swift @@ -6,11 +6,11 @@ extension DivBackground { func resolveImageURL(_ expressionResolver: ExpressionResolver) -> URL? { switch self { case let .divImageBackground(imageBackground): - return imageBackground.resolveImageUrl(expressionResolver) + imageBackground.resolveImageUrl(expressionResolver) case let .divNinePatchBackground(ninePatchImage): - return ninePatchImage.resolveImageUrl(expressionResolver) + ninePatchImage.resolveImageUrl(expressionResolver) case .divLinearGradient, .divRadialGradient, .divSolidBackground: - return nil + nil } } } diff --git a/DivKitExtensions/ExtensionHandlers/GestureExtensionHandler.swift b/DivKitExtensions/ExtensionHandlers/GestureExtensionHandler.swift index 49ccdf4c..f62859fd 100644 --- a/DivKitExtensions/ExtensionHandlers/GestureExtensionHandler.swift +++ b/DivKitExtensions/ExtensionHandlers/GestureExtensionHandler.swift @@ -37,7 +37,7 @@ private struct GestureExtensionParams { self.leftActions = params.makeDivActions(for: "swipe_left") self.rightActions = params.makeDivActions(for: "swipe_right") - if upActions == nil && downActions == nil && leftActions == nil && rightActions == nil { + if upActions == nil, downActions == nil, leftActions == nil, rightActions == nil { DivKitLogger.warning("No actions provided for gesture") return nil } @@ -49,8 +49,8 @@ extension [String: Any] { let actions = (self[key] as? [[String: Any]])?.map { DivTemplates.empty.parseValue(type: DivActionTemplate.self, from: $0) } - actions?.compactMap { $0.warnings }.reduce([], +).forEach { DivKitLogger.warning($0.errorMessage) } - actions?.compactMap { $0.errors }.reduce([], +).forEach { DivKitLogger.error($0.errorMessage) } - return actions?.compactMap { $0.value } + actions?.compactMap(\.warnings).reduce([], +).forEach { DivKitLogger.warning($0.errorMessage) } + actions?.compactMap(\.errors).reduce([], +).forEach { DivKitLogger.error($0.errorMessage) } + return actions?.compactMap(\.value) } } diff --git a/DivKitExtensions/SizeProvider/SizeProviderExtensionHandler.swift b/DivKitExtensions/SizeProvider/SizeProviderExtensionHandler.swift index 73f711d2..b14f8975 100644 --- a/DivKitExtensions/SizeProvider/SizeProviderExtensionHandler.swift +++ b/DivKitExtensions/SizeProvider/SizeProviderExtensionHandler.swift @@ -17,12 +17,11 @@ public final class SizeProviderExtensionHandler: DivExtensionHandler { self.variablesStorage = variablesStorage variablesStorage.changeEvents.addObserver { [weak self] event in - let variableNames: Set - switch event.kind { + let variableNames: Set = switch event.kind { case let .global(names): - variableNames = names + names case let .local(_, names): - variableNames = names + names } if let updatedVariables = self?.updatedVariables, !variableNames.isSubset(of: updatedVariables) { @@ -59,9 +58,9 @@ public final class SizeProviderExtensionHandler: DivExtensionHandler { let hasNotVariableReason = reasons.isEmpty || reasons.contains { switch $0 { case .variable: - return false + false default: - return true + true } } if hasNotVariableReason { diff --git a/LayoutKit/Interface/CommonHandler.swift b/LayoutKit/Interface/CommonHandler.swift index 1ce6c259..e2d95f55 100644 --- a/LayoutKit/Interface/CommonHandler.swift +++ b/LayoutKit/Interface/CommonHandler.swift @@ -13,9 +13,9 @@ extension CommonHandler: Equatable { ) -> Bool { switch (lhs, rhs) { case let (.action(lAction), .action(rAction)): - return lAction == rAction + lAction == rAction case (.action, _), (.block, _): - return false + false } } } diff --git a/LayoutKit/Interface/UserInterfaceAction.swift b/LayoutKit/Interface/UserInterfaceAction.swift index 16c50b28..a6aa49fa 100644 --- a/LayoutKit/Interface/UserInterfaceAction.swift +++ b/LayoutKit/Interface/UserInterfaceAction.swift @@ -19,17 +19,20 @@ public struct UserInterfaceAction: Equatable, Codable { public let cardId: String public let source: DivActionSource public let url: URL? + public let prototypeVariables: [String: AnyHashable] public init( action: JSONObject, cardId: String, source: DivActionSource, - url: URL? + url: URL?, + prototypeVariables: [String: AnyHashable] = [:] ) { self.action = action self.cardId = cardId self.source = source self.url = url + self.prototypeVariables = prototypeVariables } } @@ -157,17 +160,17 @@ extension UserInterfaceAction.Payload: Codable { private var kind: Kind { switch self { case .empty: - return .empty + .empty case .url: - return .url + .url case .menu: - return .menu + .menu case .json: - return .json + .json case .composite: - return .composite + .composite case .divAction: - return .divAction + .divAction } } @@ -203,7 +206,8 @@ extension UserInterfaceAction.Payload: Codable { action: container.decode(JSONObject.self, forKey: .json), cardId: container.decode(String.self, forKey: .cardId), source: UserInterfaceAction.DivActionSource(rawValue: source ?? "") ?? .tap, - url: container.decodeIfPresent(URL.self, forKey: .url) + url: container.decodeIfPresent(URL.self, forKey: .url), + prototypeVariables: [:] ) self = .divAction(params: params) } @@ -239,17 +243,17 @@ extension UserInterfaceAction.Payload: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .empty: - return "Empty" + "Empty" case let .url(value): - return "URL: \(value)" + "URL: \(value)" case let .menu(value): - return "Menu: \(value)" + "Menu: \(value)" case let .json(value): - return "JSON: \(value))" + "JSON: \(value))" case let .divAction(params): - return "DivAction: \(params.action)" + "DivAction: \(params.action)" case let .composite(lhs, rhs): - return """ + """ Composite [ \(lhs.debugDescription.indented()) \(rhs.debugDescription.indented()) diff --git a/LayoutKit/LayoutKit/Base/Masks/MaskValidator.swift b/LayoutKit/LayoutKit/Base/Masks/MaskValidator.swift index 58ccb4d8..5680d1be 100644 --- a/LayoutKit/LayoutKit/Base/Masks/MaskValidator.swift +++ b/LayoutKit/LayoutKit/Base/Masks/MaskValidator.swift @@ -38,12 +38,15 @@ public final class MaskValidator: Equatable { ) } - public func removeSymbols(at range: Range, data: InputData) -> (String, CursorData?) { + public func removeSymbols( + at range: Range, + data: InputData + ) -> (String, CursorData?) { let range = range.clamped(to: data.text.wholeStringRange) return ( String(data.rawData.filter { data.text.distance(from: range.lowerBound, to: $0.index) < 0 || - data.text.distance(from: range.upperBound, to: $0.index) >= 0 + data.text.distance(from: range.upperBound, to: $0.index) >= 0 }.map(\.char)), data.rawData.firstIndex { data.text.distance(from: range.lowerBound, to: $0.index) >= 0 } .flatMap { diff --git a/LayoutKit/LayoutKit/Base/Masks/PhoneMaskFormatter.swift b/LayoutKit/LayoutKit/Base/Masks/PhoneMaskFormatter.swift index 64bab83d..fe1abc1a 100644 --- a/LayoutKit/LayoutKit/Base/Masks/PhoneMaskFormatter.swift +++ b/LayoutKit/LayoutKit/Base/Masks/PhoneMaskFormatter.swift @@ -108,9 +108,9 @@ extension Character { extension JSONDictionary { fileprivate var maskValue: String? { if case let .string(mask) = self["value"] { - return mask + mask } else { - return nil + nil } } diff --git a/LayoutKit/LayoutKit/Blocks/Anchor/AnchorBlock.swift b/LayoutKit/LayoutKit/Blocks/Anchor/AnchorBlock.swift index 9b18ba16..473f9aeb 100644 --- a/LayoutKit/LayoutKit/Blocks/Anchor/AnchorBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/Anchor/AnchorBlock.swift @@ -83,12 +83,11 @@ public final class AnchorBlock: BlockWithLayout, BlockWithTraits { } let widths = contents.map(\.intrinsicContentWidth) - var result: CGFloat - switch direction { + var result: CGFloat = switch direction { case .horizontal: - result = widths.reduce(0, +) + widths.reduce(0, +) case .vertical: - result = widths.max()! + widths.max()! } if case let .intrinsic(_, minSize, maxSize) = widthTrait { @@ -106,12 +105,11 @@ public final class AnchorBlock: BlockWithLayout, BlockWithTraits { $0?.intrinsicContentHeight(forWidth: width) } - var result: CGFloat - switch direction { + var result: CGFloat = switch direction { case .horizontal: - result = heights.max()! + heights.max()! case .vertical: - result = heights.reduce(0, +) + heights.reduce(0, +) } if case let .intrinsic(_, minSize, maxSize) = widthTrait { diff --git a/LayoutKit/LayoutKit/Blocks/Anchor/AnchorBlockLayout.swift b/LayoutKit/LayoutKit/Blocks/Anchor/AnchorBlockLayout.swift index 55563568..0a95bb67 100644 --- a/LayoutKit/LayoutKit/Blocks/Anchor/AnchorBlockLayout.swift +++ b/LayoutKit/LayoutKit/Blocks/Anchor/AnchorBlockLayout.swift @@ -13,15 +13,14 @@ extension AnchorBlock.Layout { ) { let leadingSize = leading?.size(forResizableBlockSize: size) ?? .zero let trailingSize = trailing?.size(forResizableBlockSize: size) ?? .zero - let freeSize: CGSize - switch direction { + let freeSize = switch direction { case .horizontal: - freeSize = CGSize( + CGSize( width: max(0, size.width - leadingSize.width - trailingSize.width), height: size.height ) case .vertical: - freeSize = CGSize( + CGSize( width: size.width, height: max(0, size.height - leadingSize.height - trailingSize.height) ) @@ -32,10 +31,9 @@ extension AnchorBlock.Layout { height: min(desiredCenterSize.height, freeSize.height) ) func makeCrossOffset(contentSize: CGFloat) -> CGFloat { - let crossDimension: CGFloat - switch direction { - case .horizontal: crossDimension = size.height - case .vertical: crossDimension = size.width + let crossDimension: CGFloat = switch direction { + case .horizontal: size.height + case .vertical: size.width } return crossAlignment.offset( forAvailableSpace: crossDimension, diff --git a/LayoutKit/LayoutKit/Blocks/AnchorPoint.swift b/LayoutKit/LayoutKit/Blocks/AnchorPoint.swift index 669ed29a..76a1614a 100644 --- a/LayoutKit/LayoutKit/Blocks/AnchorPoint.swift +++ b/LayoutKit/LayoutKit/Blocks/AnchorPoint.swift @@ -19,9 +19,9 @@ public enum AnchorValue: Equatable { public func value(for length: CGFloat) -> CGFloat { switch self { case let .absolute(value): - return value / (length == 0 ? .infinity : length) + value / (length == 0 ? .infinity : length) case let .relative(value): - return value / 100 + value / 100 } } } diff --git a/LayoutKit/LayoutKit/Blocks/Block+CAAnimationRendering.swift b/LayoutKit/LayoutKit/Blocks/Block+CAAnimationRendering.swift index 6c37323f..bd77942d 100644 --- a/LayoutKit/LayoutKit/Blocks/Block+CAAnimationRendering.swift +++ b/LayoutKit/LayoutKit/Blocks/Block+CAAnimationRendering.swift @@ -19,9 +19,9 @@ extension AnimationChanges { public var keyPath: String { switch self { case .transform: - return "transform" + "transform" case .opacity: - return "opacity" + "opacity" } } } @@ -30,9 +30,9 @@ extension AnimationChanges { public var values: [NSValue] { switch self { case let .transform(values): - return values.map { NSValue(caTransform3D: $0) } + values.map { NSValue(caTransform3D: $0) } case let .opacity(values): - return values.map { NSNumber(value: $0 as Float) } + values.map { NSNumber(value: $0 as Float) } } } } @@ -41,9 +41,9 @@ extension AnimationChanges { fileprivate var isAdditive: Bool { switch self { case .opacity: - return false + false case .transform: - return true + true } } } @@ -52,13 +52,13 @@ extension CAMediaTimingFunction { fileprivate static func from(blockTimingFunction: TimingFunction) -> CAMediaTimingFunction { switch blockTimingFunction { case .linear: - return .linear + .linear case .easeIn: - return .easeIn + .easeIn case .easeOut: - return .easeOut + .easeOut case .easeInEaseOut: - return .easeInEaseOut + .easeInEaseOut } } } diff --git a/LayoutKit/LayoutKit/Blocks/Block+Debugging.swift b/LayoutKit/LayoutKit/Blocks/Block+Debugging.swift index 36adbffb..2ad5ebd3 100644 --- a/LayoutKit/LayoutKit/Blocks/Block+Debugging.swift +++ b/LayoutKit/LayoutKit/Blocks/Block+Debugging.swift @@ -7,9 +7,9 @@ extension ContainerBlock.LayoutDirection: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .horizontal: - return "Horizontal" + "Horizontal" case .vertical: - return "Vertical" + "Vertical" } } } @@ -17,9 +17,9 @@ extension ContainerBlock.LayoutDirection: CustomDebugStringConvertible { extension BlockAlignment2D: CustomDebugStringConvertible { public var debugDescription: String { if horizontal != vertical { - return "V: \(vertical) H: \(horizontal)" + "V: \(vertical) H: \(horizontal)" } else { - return horizontal.debugDescription + horizontal.debugDescription } } } @@ -179,11 +179,11 @@ extension LayoutTrait: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .intrinsic: - return "I" + "I" case let .weighted(value): - return "R(\(value.rawValue))" + "R(\(value.rawValue))" case let .fixed(value): - return "\(value)" + "\(value)" } } } @@ -192,9 +192,9 @@ extension AnimationChanges: CustomDebugStringConvertible { public var debugDescription: String { switch self { case let .transform(values): - return "transform\(values)" + "transform\(values)" case let .opacity(values): - return "opacity\(values)" + "opacity\(values)" } } } diff --git a/LayoutKit/LayoutKit/Blocks/Block.swift b/LayoutKit/LayoutKit/Blocks/Block.swift index 8c260866..67c5e3b1 100644 --- a/LayoutKit/LayoutKit/Blocks/Block.swift +++ b/LayoutKit/LayoutKit/Blocks/Block.swift @@ -157,11 +157,11 @@ public func ==(lhs: Block, rhs: Block) -> Bool { public func ==(lhs: Block?, rhs: Block?) -> Bool { switch (lhs, rhs) { case (.none, .none): - return true + true case let (.some(value1), .some(value2)): - return value1 == value2 + value1 == value2 default: - return false + false } } diff --git a/LayoutKit/LayoutKit/Blocks/BlockTooltip+Layout.swift b/LayoutKit/LayoutKit/Blocks/BlockTooltip+Layout.swift index d46a5132..046c3de2 100644 --- a/LayoutKit/LayoutKit/Blocks/BlockTooltip+Layout.swift +++ b/LayoutKit/LayoutKit/Blocks/BlockTooltip+Layout.swift @@ -15,15 +15,15 @@ extension BlockTooltip { extension CGRect { fileprivate func coordinate(of position: BlockTooltip.Position) -> CGPoint { switch position { - case .left: return CGPoint(x: minX, y: midY) - case .topLeft: return coordinate(ofCorner: .topLeft) - case .top: return CGPoint(x: midX, y: minY) - case .topRight: return coordinate(ofCorner: .topRight) - case .right: return CGPoint(x: maxX, y: midY) - case .bottomRight: return coordinate(ofCorner: .bottomRight) - case .bottom: return CGPoint(x: midX, y: maxY) - case .bottomLeft: return coordinate(ofCorner: .bottomLeft) - case .center: return CGPoint(x: midX, y: midY) + case .left: CGPoint(x: minX, y: midY) + case .topLeft: coordinate(ofCorner: .topLeft) + case .top: CGPoint(x: midX, y: minY) + case .topRight: coordinate(ofCorner: .topRight) + case .right: CGPoint(x: maxX, y: midY) + case .bottomRight: coordinate(ofCorner: .bottomRight) + case .bottom: CGPoint(x: midX, y: maxY) + case .bottomLeft: coordinate(ofCorner: .bottomLeft) + case .center: CGPoint(x: midX, y: midY) } } } @@ -31,15 +31,15 @@ extension CGRect { extension BlockTooltip.Position { fileprivate var opposite: Self { switch self { - case .left: return .right - case .topLeft: return .bottomRight - case .top: return .bottom - case .topRight: return .bottomLeft - case .right: return .left - case .bottomRight: return .topLeft - case .bottom: return .top - case .bottomLeft: return .topRight - case .center: return .center + case .left: .right + case .topLeft: .bottomRight + case .top: .bottom + case .topRight: .bottomLeft + case .right: .left + case .bottomRight: .topLeft + case .bottom: .top + case .bottomLeft: .topRight + case .center: .center } } } @@ -50,26 +50,25 @@ extension CGRect { ofPosition position: BlockTooltip.Position, size: CGSize ) { - let origin: CGPoint - switch position { + let origin: CGPoint = switch position { case .left: - origin = coordinate.movingY(by: -0.5 * size.height) + coordinate.movingY(by: -0.5 * size.height) case .topLeft: - origin = coordinate + coordinate case .top: - origin = coordinate.movingX(by: -0.5 * size.width) + coordinate.movingX(by: -0.5 * size.width) case .topRight: - origin = coordinate.movingX(by: -size.width) + coordinate.movingX(by: -size.width) case .right: - origin = coordinate.movingX(by: -size.width).movingY(by: -0.5 * size.height) + coordinate.movingX(by: -size.width).movingY(by: -0.5 * size.height) case .bottomRight: - origin = coordinate.movingX(by: -size.width).movingY(by: -size.height) + coordinate.movingX(by: -size.width).movingY(by: -size.height) case .bottom: - origin = coordinate.movingX(by: -0.5 * size.width).movingY(by: -size.height) + coordinate.movingX(by: -0.5 * size.width).movingY(by: -size.height) case .bottomLeft: - origin = coordinate.movingY(by: -size.height) + coordinate.movingY(by: -size.height) case .center: - origin = coordinate.movingX(by: -0.5 * size.width).movingY(by: -size.height / 2) + coordinate.movingX(by: -0.5 * size.width).movingY(by: -size.height / 2) } self.init(origin: origin, size: size) } diff --git a/LayoutKit/LayoutKit/Blocks/BlockWithTraits.swift b/LayoutKit/LayoutKit/Blocks/BlockWithTraits.swift index 162fd8ce..ad50cd53 100644 --- a/LayoutKit/LayoutKit/Blocks/BlockWithTraits.swift +++ b/LayoutKit/LayoutKit/Blocks/BlockWithTraits.swift @@ -34,9 +34,9 @@ extension BlockWithWidthTrait { public var minWidth: CGFloat { switch widthTrait { case .fixed, .weighted: - return 0 + 0 case .intrinsic(constrained: _, minSize: let minSize, maxSize: _): - return minSize + minSize } } } @@ -65,11 +65,11 @@ extension BlockWithHeightTrait { public var minHeight: CGFloat { switch heightTrait { case let .fixed(size): - return size + size case .weighted: - return 0 + 0 case .intrinsic(constrained: _, minSize: let minSize, maxSize: _): - return minSize + minSize } } } diff --git a/LayoutKit/LayoutKit/Blocks/BoundaryTrait.swift b/LayoutKit/LayoutKit/Blocks/BoundaryTrait.swift index 81b04e25..d4fd7c8c 100644 --- a/LayoutKit/LayoutKit/Blocks/BoundaryTrait.swift +++ b/LayoutKit/LayoutKit/Blocks/BoundaryTrait.swift @@ -35,9 +35,9 @@ extension BoundaryTrait { func allCornersAreApproximatelyEqualToZero() -> Bool { switch self { case .noClip, .clipPath: - return true + true case let .clipCorner(radii): - return radii.allCornersAreApproximatelyEqualToZero() + radii.allCornersAreApproximatelyEqualToZero() } } } diff --git a/LayoutKit/LayoutKit/Blocks/BoundaryTraitExtensions.swift b/LayoutKit/LayoutKit/Blocks/BoundaryTraitExtensions.swift index 3354b28d..7e4048a5 100644 --- a/LayoutKit/LayoutKit/Blocks/BoundaryTraitExtensions.swift +++ b/LayoutKit/LayoutKit/Blocks/BoundaryTraitExtensions.swift @@ -8,9 +8,9 @@ extension BoundaryTrait { var clipsToBounds: Bool { switch self { case .noClip: - return false + false case .clipCorner, .clipPath: - return true + true } } @@ -60,15 +60,15 @@ extension BoundaryTrait { private func makeMaskPath(for size: CGSize, inset: CGFloat) -> CGPath? { switch self { case let .clipPath(path): - return path + path case let .clipCorner(cornerRadii): - return .roundedRect( + .roundedRect( size: size, cornerRadii: cornerRadii, inset: inset ) case .noClip: - return nil + nil } } } diff --git a/LayoutKit/LayoutKit/Blocks/Container/AxialAlignmentManager.swift b/LayoutKit/LayoutKit/Blocks/Container/AxialAlignmentManager.swift index 34c6eca4..0933f2b1 100644 --- a/LayoutKit/LayoutKit/Blocks/Container/AxialAlignmentManager.swift +++ b/LayoutKit/LayoutKit/Blocks/Container/AxialAlignmentManager.swift @@ -99,9 +99,9 @@ extension CGFloat { ) -> CGPoint { switch layoutDirection { case .horizontal: - return CGPoint(x: self, y: 0) + CGPoint(x: self, y: 0) case .vertical: - return CGPoint(x: 0, y: self) + CGPoint(x: 0, y: self) } } } diff --git a/LayoutKit/LayoutKit/Blocks/Container/ContainerBlock.swift b/LayoutKit/LayoutKit/Blocks/Container/ContainerBlock.swift index 9ca31361..32118be2 100644 --- a/LayoutKit/LayoutKit/Blocks/Container/ContainerBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/Container/ContainerBlock.swift @@ -234,9 +234,9 @@ public final class ContainerBlock: BlockWithLayout { public var calculateWidthFirst: Bool { switch widthTrait { case .fixed, .weighted: - return true + true case .intrinsic: - return !(layoutDirection == .vertical && layoutMode == .wrap) + !(layoutDirection == .vertical && layoutMode == .wrap) } } @@ -252,12 +252,11 @@ public final class ContainerBlock: BlockWithLayout { return cached } - var result: CGFloat - switch layoutDirection { + var result: CGFloat = switch layoutDirection { case .horizontal: - result = (children.map(\.content.intrinsicContentWidth) + gaps).reduce(0, +) + (children.map(\.content.intrinsicContentWidth) + gaps).reduce(0, +) case .vertical: - result = children.map(\.content.intrinsicContentWidth).max() ?? 0 + children.map(\.content.intrinsicContentWidth).max() ?? 0 } if case let .intrinsic(_, minSize, maxSize) = widthTrait { @@ -328,16 +327,14 @@ public final class ContainerBlock: BlockWithLayout { return cached.width } - let result: CGFloat - - switch layoutDirection { + let result: CGFloat = switch layoutDirection { case .horizontal: - result = (children.map(\.content.widthOfHorizontallyNonResizableBlock) + gaps) + (children.map(\.content.widthOfHorizontallyNonResizableBlock) + gaps) .reduce(0, +) case .vertical: // MOBYANDEXIOS-1092: Only non-resizable children can influence the width of a container // because the widths of resizable children depend on the width of container itself - result = children.filter { !$0.content.isHorizontallyResizable } + children.filter { !$0.content.isHorizontallyResizable } .map(\.content.widthOfHorizontallyNonResizableBlock).max() ?? 0 } @@ -556,11 +553,11 @@ extension ContainerBlock.CrossAlignment { ) -> CGFloat { switch self { case .leading, .baseline: - return 0 + 0 case .center: - return ((availableSpace - contentSize) * 0.5).roundedToScreenScale + ((availableSpace - contentSize) * 0.5).roundedToScreenScale case .trailing: - return availableSpace - contentSize + availableSpace - contentSize } } } diff --git a/LayoutKit/LayoutKit/Blocks/Container/ContainerBlockExtensions.swift b/LayoutKit/LayoutKit/Blocks/Container/ContainerBlockExtensions.swift index 4da0abad..28e0947f 100644 --- a/LayoutKit/LayoutKit/Blocks/Container/ContainerBlockExtensions.swift +++ b/LayoutKit/LayoutKit/Blocks/Container/ContainerBlockExtensions.swift @@ -89,22 +89,22 @@ extension Alignment { fileprivate var crossAlignment: ContainerBlock.CrossAlignment { switch self { case .leading: - return .leading + .leading case .center: - return .center + .center case .trailing: - return .trailing + .trailing } } fileprivate var axialAlignment: ContainerBlock.AxialAlignment { switch self { case .leading: - return .leading + .leading case .center: - return .center + .center case .trailing: - return .trailing + .trailing } } } diff --git a/LayoutKit/LayoutKit/Blocks/Container/ContainerBlockLayout.swift b/LayoutKit/LayoutKit/Blocks/Container/ContainerBlockLayout.swift index 81c2acda..838c6961 100644 --- a/LayoutKit/LayoutKit/Blocks/Container/ContainerBlockLayout.swift +++ b/LayoutKit/LayoutKit/Blocks/Container/ContainerBlockLayout.swift @@ -20,9 +20,9 @@ struct ContainerBlockLayout { var insetValue: CGFloat { switch self { case .fits: - return 0 + 0 case let .doesNotFit(notFittingPartSize: inset): - return inset + inset } } } @@ -78,11 +78,11 @@ struct ContainerBlockLayout { ) -> ([ContainerBlock.Child], [CGRect], CGFloat?) { switch layoutMode { case .noWrap: - return calculateNoWrapLayoutFrames( + calculateNoWrapLayoutFrames( children: children ) case .wrap: - return calculateWrapLayoutFrames( + calculateWrapLayoutFrames( children: children, separator: separator, lineSeparator: lineSeparator @@ -205,13 +205,12 @@ struct ContainerBlockLayout { let intrinsicWidth = block.widthOfHorizontallyNonResizableBlock width = block.isHorizontallyConstrained ? min(intrinsicWidth, size.width) : intrinsicWidth } - let height: CGFloat - if block.isVerticallyResizable { - height = blockMeasure.measureNext(block.verticalMeasure) + let height: CGFloat = if block.isVerticallyResizable { + blockMeasure.measureNext(block.verticalMeasure) } else if block.isVerticallyConstrained { - height = constrainedBlockSizesIterator.next() ?? 0 + constrainedBlockSizesIterator.next() ?? 0 } else { - height = block.heightOfVerticallyNonResizableBlock(forWidth: width) + block.heightOfVerticallyNonResizableBlock(forWidth: width) } let alignmentSpace = size.width - width let x = child.crossAlignment.offset(forAvailableSpace: alignmentSpace) @@ -340,14 +339,14 @@ struct ContainerBlockLayout { ) -> CGFloat { switch layoutDirection { case .horizontal: - return group + group .map { item in item.childSize.height + item.child.baselineOffset( ascent: lineAscent, width: item.childSize.width ) } .max() ?? 0 case .vertical: - return group.map { item in item.childSize.width }.max() ?? 0 + group.map { item in item.childSize.width }.max() ?? 0 } } diff --git a/LayoutKit/LayoutKit/Blocks/Container/WrapLayoutGroups.swift b/LayoutKit/LayoutKit/Blocks/Container/WrapLayoutGroups.swift index 0534af43..dd209416 100644 --- a/LayoutKit/LayoutKit/Blocks/Container/WrapLayoutGroups.swift +++ b/LayoutKit/LayoutKit/Blocks/Container/WrapLayoutGroups.swift @@ -225,18 +225,18 @@ extension ContainerBlock.LayoutDirection { var buildingDirectionKeyPath: WritableKeyPath { switch self { case .horizontal: - return \.width + \.width case .vertical: - return \.height + \.height } } var transferDirectionKeyPath: KeyPath { switch self { case .horizontal: - return \.height + \.height case .vertical: - return \.width + \.width } } } @@ -245,18 +245,18 @@ extension ContainerBlock.Child { fileprivate func isResizable(for layoutDirection: ContainerBlock.LayoutDirection) -> Bool { switch layoutDirection { case .horizontal: - return content.isHorizontallyResizable + content.isHorizontallyResizable case .vertical: - return content.isVerticallyResizable + content.isVerticallyResizable } } fileprivate func isConstrained(for layoutDirection: ContainerBlock.LayoutDirection) -> Bool { switch layoutDirection { case .horizontal: - return content.isHorizontallyConstrained + content.isHorizontallyConstrained case .vertical: - return content.isVerticallyConstrained + content.isVerticallyConstrained } } } diff --git a/LayoutKit/LayoutKit/Blocks/Decorations/Block+Decorations.swift b/LayoutKit/LayoutKit/Blocks/Decorations/Block+Decorations.swift index 895bb291..f10fc55b 100644 --- a/LayoutKit/LayoutKit/Blocks/Decorations/Block+Decorations.swift +++ b/LayoutKit/LayoutKit/Blocks/Decorations/Block+Decorations.swift @@ -311,9 +311,9 @@ extension BoundaryTrait? { fileprivate var shouldApplyBoundary: Bool { switch self { case .noClip?, .none: - return false + false case .clipPath?, .clipCorner?: - return true + true } } } diff --git a/LayoutKit/LayoutKit/Blocks/EmptyBlock.swift b/LayoutKit/LayoutKit/Blocks/EmptyBlock.swift index b453bc75..0769127f 100644 --- a/LayoutKit/LayoutKit/Blocks/EmptyBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/EmptyBlock.swift @@ -49,11 +49,11 @@ extension LayoutTrait { fileprivate var intrinsicSize: CGFloat { switch self { case let .fixed(value): - return value + value case let .intrinsic(_, minSize, _): - return minSize + minSize case .weighted: - return 0 + 0 } } } diff --git a/LayoutKit/LayoutKit/Blocks/GestureBlock.swift b/LayoutKit/LayoutKit/Blocks/GestureBlock.swift index 8552db6a..34c28b6a 100644 --- a/LayoutKit/LayoutKit/Blocks/GestureBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/GestureBlock.swift @@ -28,7 +28,7 @@ public final class GestureBlock: WrapperBlock, LayoutCachingDefaultImpl { rightActions: rightActions ) } - + public func equals(_ other: Block) -> Bool { guard let other = other as? GestureBlock else { return false diff --git a/LayoutKit/LayoutKit/Blocks/GradientBlock.swift b/LayoutKit/LayoutKit/Blocks/GradientBlock.swift index f0d9282a..adff4c52 100644 --- a/LayoutKit/LayoutKit/Blocks/GradientBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/GradientBlock.swift @@ -18,22 +18,22 @@ public final class GradientBlock: BlockWithTraits { public var intrinsicContentWidth: CGFloat { switch widthTrait { case let .fixed(value): - return value + value case let .intrinsic(_, minSize, _): - return minSize + minSize case .weighted: - return 0 + 0 } } public func intrinsicContentHeight(forWidth _: CGFloat) -> CGFloat { switch heightTrait { case let .fixed(value): - return value + value case let .intrinsic(_, minSize, _): - return minSize + minSize case .weighted: - return 0 + 0 } } diff --git a/LayoutKit/LayoutKit/Blocks/Grid/GridLayout.swift b/LayoutKit/LayoutKit/Blocks/Grid/GridLayout.swift index fe0cad15..cd6fcd36 100644 --- a/LayoutKit/LayoutKit/Blocks/Grid/GridLayout.swift +++ b/LayoutKit/LayoutKit/Blocks/Grid/GridLayout.swift @@ -142,9 +142,9 @@ private func makeEnumeratedItems( .enumerated() .compactMap { if let element = $0.element, element.span == span { - return ($0.offset, element) + ($0.offset, element) } else { - return nil + nil } } } @@ -455,8 +455,8 @@ private struct WeightedItem { extension GridBlock.Item.Weight { fileprivate func value(at direction: Direction) -> LayoutTrait.Weight? { switch direction { - case .horizontal: return column - case .vertical: return row + case .horizontal: column + case .vertical: row } } } @@ -464,8 +464,8 @@ extension GridBlock.Item.Weight { extension GridBlock.Span { fileprivate func value(at direction: Direction) -> Int { switch direction { - case .horizontal: return columns - case .vertical: return rows + case .horizontal: columns + case .vertical: rows } } } @@ -475,8 +475,8 @@ private typealias Direction = GridBlock.Direction extension Direction { fileprivate func selectDimension(from coords: (row: Int, column: Int)) -> Int { switch self { - case .horizontal: return coords.column - case .vertical: return coords.row + case .horizontal: coords.column + case .vertical: coords.row } } } diff --git a/LayoutKit/LayoutKit/Blocks/ImageBaseBlock.swift b/LayoutKit/LayoutKit/Blocks/ImageBaseBlock.swift index f704f7b0..6b638331 100644 --- a/LayoutKit/LayoutKit/Blocks/ImageBaseBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/ImageBaseBlock.swift @@ -43,18 +43,18 @@ extension ImageBaseBlock { public var isVerticallyResizable: Bool { switch height { case let .trait(trait): - return trait.isResizable + trait.isResizable case .ratio: - return false + false } } public var isVerticallyConstrained: Bool { switch height { case let .trait(trait): - return trait.isConstrained + trait.isConstrained case .ratio: - return false + false } } diff --git a/LayoutKit/LayoutKit/Blocks/IntrincisHeights.swift b/LayoutKit/LayoutKit/Blocks/IntrincisHeights.swift index ec281c77..3e746fa7 100644 --- a/LayoutKit/LayoutKit/Blocks/IntrincisHeights.swift +++ b/LayoutKit/LayoutKit/Blocks/IntrincisHeights.swift @@ -3,13 +3,12 @@ import CoreGraphics extension [Block] { func intrinsicHeights(forWidth width: CGFloat) -> [CGFloat] { map { - let blockWidth: CGFloat - if $0.isHorizontallyResizable { - blockWidth = width + let blockWidth: CGFloat = if $0.isHorizontallyResizable { + width } else if $0.isHorizontallyConstrained { - blockWidth = Swift.min($0.widthOfHorizontallyNonResizableBlock, width) + Swift.min($0.widthOfHorizontallyNonResizableBlock, width) } else { - blockWidth = $0.widthOfHorizontallyNonResizableBlock + $0.widthOfHorizontallyNonResizableBlock } return $0.intrinsicContentHeight(forWidth: blockWidth) } diff --git a/LayoutKit/LayoutKit/Blocks/LayoutTrait.swift b/LayoutKit/LayoutKit/Blocks/LayoutTrait.swift index 8054f9c9..a35b3ad1 100644 --- a/LayoutKit/LayoutKit/Blocks/LayoutTrait.swift +++ b/LayoutKit/LayoutKit/Blocks/LayoutTrait.swift @@ -65,9 +65,9 @@ extension LayoutTrait { public var isConstrained: Bool { switch self { case let .intrinsic(constrained, _, _): - return constrained + constrained case .fixed, .weighted: - return false + false } } } diff --git a/LayoutKit/LayoutKit/Blocks/PageControlBlock.swift b/LayoutKit/LayoutKit/Blocks/PageControlBlock.swift index 5505b666..5a17f7da 100644 --- a/LayoutKit/LayoutKit/Blocks/PageControlBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/PageControlBlock.swift @@ -38,12 +38,11 @@ public final class PageControlBlock: BlockWithTraits { case let .fixed(value): return value case let .intrinsic(_, minSize, maxSize): - let width: CGFloat - switch configuration.itemPlacement { + let width: CGFloat = switch configuration.itemPlacement { case let .fixed(spaceBetweenCenters): - width = spaceBetweenCenters * CGFloat(state.numberOfPages) + spaceBetweenCenters * CGFloat(state.numberOfPages) case .stretch: - width = 0 + 0 } return clamp(width, min: minSize, max: maxSize) diff --git a/LayoutKit/LayoutKit/Blocks/PagerBlock.swift b/LayoutKit/LayoutKit/Blocks/PagerBlock.swift index 8484ae6f..ce44865e 100644 --- a/LayoutKit/LayoutKit/Blocks/PagerBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/PagerBlock.swift @@ -112,13 +112,12 @@ extension PagerBlock: ElementStateUpdating { return self } - let newModel: GalleryViewModel - if blocksAreNotEqual { - newModel = modified(gallery) { + let newModel: GalleryViewModel = if blocksAreNotEqual { + modified(gallery) { $0.items.apply(contents: newBlocks) } } else { - newModel = gallery + gallery } return try PagerBlock( diff --git a/LayoutKit/LayoutKit/Blocks/SeparatorBlock.swift b/LayoutKit/LayoutKit/Blocks/SeparatorBlock.swift index f038c3c9..a6a95cf4 100644 --- a/LayoutKit/LayoutKit/Blocks/SeparatorBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/SeparatorBlock.swift @@ -75,11 +75,11 @@ extension LayoutTrait { fileprivate var intrinsicSize: CGFloat { switch self { case let .fixed(value): - return value + value case let .intrinsic(_, minSize, _): - return minSize + minSize case .weighted: - return 0 + 0 } } } diff --git a/LayoutKit/LayoutKit/Blocks/SwipeContainerBlock.swift b/LayoutKit/LayoutKit/Blocks/SwipeContainerBlock.swift index 4bed1926..a4d966ae 100644 --- a/LayoutKit/LayoutKit/Blocks/SwipeContainerBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/SwipeContainerBlock.swift @@ -32,9 +32,9 @@ public final class SwipeContainerBlock: WrapperBlock { public func intrinsicContentHeight(forWidth: CGFloat) -> CGFloat { switch state { case .normal: - return child.intrinsicContentHeight(forWidth: forWidth) + child.intrinsicContentHeight(forWidth: forWidth) case .left, .right: - return 0 + 0 } } diff --git a/LayoutKit/LayoutKit/Blocks/TextFieldBlock.swift b/LayoutKit/LayoutKit/Blocks/TextFieldBlock.swift index 6f10de5d..53ff7cd6 100644 --- a/LayoutKit/LayoutKit/Blocks/TextFieldBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/TextFieldBlock.swift @@ -195,29 +195,29 @@ public final class TextFieldBlock: Block { public var intrinsicContentWidth: CGFloat { switch widthTrait { case let .fixed(value): - return value + value case let .intrinsic(_, minSize, _): - return minSize + minSize case .weighted: - return 0 + 0 } } private var gap: CGFloat { switch placeholders { case let .separate(placeholders): - return placeholders.gap + placeholders.gap case .fieldOnly, .none: - return 0 + 0 } } private func getHeaderHeight(forWidth _: CGFloat) -> CGFloat { switch placeholders { case let .separate(placeholders): - return placeholders.headerAttributes.height.rawValue + placeholders.headerAttributes.height.rawValue case .fieldOnly, .none: - return 0 + 0 } } @@ -334,11 +334,11 @@ extension TextFieldBlock.ToolbarType { ) -> Bool { switch (lhs, rhs) { case let (.default(lhs), .default(rhs)): - return lhs == rhs + lhs == rhs case let (.custom(lhs), .custom(rhs)): - return lhs == rhs + lhs == rhs default: - return false + false } } } diff --git a/LayoutKit/LayoutKit/Blocks/TextInputBlock.swift b/LayoutKit/LayoutKit/Blocks/TextInputBlock.swift index 23315679..3db60a9e 100644 --- a/LayoutKit/LayoutKit/Blocks/TextInputBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/TextInputBlock.swift @@ -124,11 +124,11 @@ public final class TextInputBlock: BlockWithTraits { public var intrinsicContentWidth: CGFloat { switch widthTrait { case let .fixed(value): - return value + value case let .intrinsic(_, minSize, _): - return minSize + minSize case .weighted: - return 0 + 0 } } diff --git a/LayoutKit/LayoutKit/Blocks/Video/DefaultPlayer/DefaultPlayer.swift b/LayoutKit/LayoutKit/Blocks/Video/DefaultPlayer/DefaultPlayer.swift index 04b7fdde..6f99f323 100644 --- a/LayoutKit/LayoutKit/Blocks/Video/DefaultPlayer/DefaultPlayer.swift +++ b/LayoutKit/LayoutKit/Blocks/Video/DefaultPlayer/DefaultPlayer.swift @@ -76,11 +76,11 @@ final class DefaultPlayer: Player { .map { playbackStatus -> PlayerEvent in switch playbackStatus { case .playing: - return .play + .play case .paused: - return .pause + .pause case .buffering: - return .buffering + .buffering } } .addObserver { weakSelf?.eventPipe.send($0) } diff --git a/LayoutKit/LayoutKit/Blocks/Video/DefaultPlayer/DefaultPlayerView.swift b/LayoutKit/LayoutKit/Blocks/Video/DefaultPlayer/DefaultPlayerView.swift index 0e08ccf6..98cde0d7 100644 --- a/LayoutKit/LayoutKit/Blocks/Video/DefaultPlayer/DefaultPlayerView.swift +++ b/LayoutKit/LayoutKit/Blocks/Video/DefaultPlayer/DefaultPlayerView.swift @@ -40,11 +40,11 @@ extension VideoScale { fileprivate var videoGravity: AVLayerVideoGravity? { switch self { case .fill: - return .resizeAspectFill + .resizeAspectFill case .noScale: - return nil + nil case .fit: - return .resizeAspect + .resizeAspect } } } diff --git a/LayoutKit/LayoutKit/Blocks/Video/VideoBlock.swift b/LayoutKit/LayoutKit/Blocks/Video/VideoBlock.swift index 64f78626..649e6a22 100644 --- a/LayoutKit/LayoutKit/Blocks/Video/VideoBlock.swift +++ b/LayoutKit/LayoutKit/Blocks/Video/VideoBlock.swift @@ -27,18 +27,18 @@ public final class VideoBlock: BlockWithTraits { public var intrinsicContentWidth: CGFloat { switch widthTrait { case let .fixed(value): - return value + value case .intrinsic, .weighted: - return 0 + 0 } } public func intrinsicContentHeight(forWidth _: CGFloat) -> CGFloat { switch heightTrait { case let .fixed(value): - return value + value case .intrinsic, .weighted: - return 0 + 0 } } diff --git a/LayoutKit/LayoutKit/Blocks/Visibility.swift b/LayoutKit/LayoutKit/Blocks/Visibility.swift index 9731e26a..fc66f825 100644 --- a/LayoutKit/LayoutKit/Blocks/Visibility.swift +++ b/LayoutKit/LayoutKit/Blocks/Visibility.swift @@ -6,8 +6,8 @@ public enum Visibility { extension Visibility { public var isVisible: Bool { switch self { - case .visible: return true - case .notVisible: return false + case .visible: true + case .notVisible: false } } } diff --git a/LayoutKit/LayoutKit/GenericViewBlock.swift b/LayoutKit/LayoutKit/GenericViewBlock.swift index f9b71742..3c82a619 100644 --- a/LayoutKit/LayoutKit/GenericViewBlock.swift +++ b/LayoutKit/LayoutKit/GenericViewBlock.swift @@ -84,17 +84,17 @@ public final class GenericViewBlock: BlockWithTraits { public var intrinsicContentWidth: CGFloat { switch width { - case .resizable: return 0 - case let .fixed(width): return width - case let .intrinsic(calculator): return calculator.calculateWidth() + case .resizable: 0 + case let .fixed(width): width + case let .intrinsic(calculator): calculator.calculateWidth() } } public func intrinsicContentHeight(forWidth width: CGFloat) -> CGFloat { switch height { - case .resizable: return 0 - case let .fixed(height): return height - case let .intrinsic(calculator): return calculator.calculateHeight(width: width) + case .resizable: 0 + case let .fixed(height): height + case let .intrinsic(calculator): calculator.calculateHeight(width: width) } } @@ -120,9 +120,9 @@ extension GenericViewBlock: ElementStateUpdatingDefaultImpl {} extension GenericViewBlock.Content { static func ===(lhs: GenericViewBlock.Content, rhs: GenericViewBlock.Content) -> Bool { switch (lhs, rhs) { - case let (.view(lView), .view(rView)): return lView === rView - case let (.layer(lView), .layer(rView)): return lView === rView - case (.view, _), (.layer, _): return false + case let (.view(lView), .view(rView)): lView === rView + case let (.layer(lView), .layer(rView)): lView === rView + case (.view, _), (.layer, _): false } } } @@ -130,10 +130,10 @@ extension GenericViewBlock.Content { extension GenericViewBlock.Trait { public static func ==(lhs: GenericViewBlock.Trait, rhs: GenericViewBlock.Trait) -> Bool { switch (lhs, rhs) { - case (.resizable, .resizable): return true - case let (.fixed(lhs), .fixed(rhs)): return lhs == rhs - case let (.intrinsic(lhs), .intrinsic(rhs)): return lhs === rhs - case (.resizable, _), (.fixed, _), (.intrinsic, _): return false + case (.resizable, .resizable): true + case let (.fixed(lhs), .fixed(rhs)): lhs == rhs + case let (.intrinsic(lhs), .intrinsic(rhs)): lhs === rhs + case (.resizable, _), (.fixed, _), (.intrinsic, _): false } } } @@ -147,9 +147,9 @@ extension CGFloat? { extension GenericViewBlock.Trait { fileprivate var layoutTrait: LayoutTrait { switch self { - case .resizable: return .resizable - case .intrinsic: return .intrinsic - case let .fixed(size): return .fixed(size) + case .resizable: .resizable + case .intrinsic: .intrinsic + case let .fixed(size): .fixed(size) } } } @@ -157,9 +157,9 @@ extension GenericViewBlock.Trait { extension GenericViewBlock.Content? { static func !==(lhs: GenericViewBlock.Content?, rhs: GenericViewBlock.Content?) -> Bool { switch (lhs, rhs) { - case let (lValue?, rValue?): return !(lValue === rValue) - case (nil, nil): return false - case (nil, _), (.some, _): return true + case let (lValue?, rValue?): !(lValue === rValue) + case (nil, nil): false + case (nil, _), (.some, _): true } } diff --git a/LayoutKit/LayoutKit/Tooltips/TooltipFactory.swift b/LayoutKit/LayoutKit/Tooltips/TooltipFactory.swift index f8a523bf..dbc1307f 100644 --- a/LayoutKit/LayoutKit/Tooltips/TooltipFactory.swift +++ b/LayoutKit/LayoutKit/Tooltips/TooltipFactory.swift @@ -24,50 +24,49 @@ public enum TooltipFactory { extension BlockTooltip.Position { private func makeTail(color: Color) -> Block { - let imageHolder: ImageHolder? - switch self { + let imageHolder: ImageHolder? = switch self { case .left: - imageHolder = Image.imageOfSize( + Image.imageOfSize( middleTailSize, drawingHandler: { drawMiddleTail(style: .right, color: color, context: $0) } ) case .topLeft: - imageHolder = Image.imageOfSize( + Image.imageOfSize( cornerTailSize, drawingHandler: { drawCornerTail(style: .bottomRight, color: color, context: $0) } ) case .top: - imageHolder = Image.imageOfSize( + Image.imageOfSize( middleTailSize.flipDimensions(), drawingHandler: { drawMiddleTail(style: .bottom, color: color, context: $0) } ) case .topRight: - imageHolder = Image.imageOfSize( + Image.imageOfSize( cornerTailSize, drawingHandler: { drawCornerTail(style: .bottomLeft, color: color, context: $0) } ) case .right: - imageHolder = Image.imageOfSize( + Image.imageOfSize( middleTailSize, drawingHandler: { drawMiddleTail(style: .left, color: color, context: $0) } ) case .bottomRight: - imageHolder = Image.imageOfSize( + Image.imageOfSize( cornerTailSize, drawingHandler: { drawCornerTail(style: .topLeft, color: color, context: $0) } ) case .bottom: - imageHolder = Image.imageOfSize( + Image.imageOfSize( middleTailSize.flipDimensions(), drawingHandler: { drawMiddleTail(style: .top, color: color, context: $0) } ) case .bottomLeft: - imageHolder = Image.imageOfSize( + Image.imageOfSize( cornerTailSize, drawingHandler: { drawCornerTail(style: .topRight, color: color, context: $0) } ) case .center: - imageHolder = Image.imageOfSize( + Image.imageOfSize( cornerTailSize, drawingHandler: { _ in } ) @@ -78,14 +77,14 @@ extension BlockTooltip.Position { fileprivate func makeContainer(child: Block, theme: Theme) -> Block { switch self { case .left: - return try! ContainerBlock( + try! ContainerBlock( layoutDirection: .horizontal, verticalChildrenAlignment: .center, gaps: [0, -1, 0], children: [child, makeTail(color: theme.backgroundColor)] ) case .topLeft: - return LayeredBlock( + LayeredBlock( horizontalChildrenAlignment: .trailing, verticalChildrenAlignment: .trailing, children: [ @@ -94,14 +93,14 @@ extension BlockTooltip.Position { ] ) case .top: - return try! ContainerBlock( + try! ContainerBlock( layoutDirection: .vertical, horizontalChildrenAlignment: .center, gaps: [0, -1, 0], children: [child, makeTail(color: theme.backgroundColor)] ) case .topRight: - return LayeredBlock( + LayeredBlock( verticalChildrenAlignment: .trailing, children: [ makeTail(color: theme.backgroundColor), @@ -109,26 +108,26 @@ extension BlockTooltip.Position { ] ) case .right: - return try! ContainerBlock( + try! ContainerBlock( layoutDirection: .horizontal, verticalChildrenAlignment: .center, gaps: [0, -1, 0], children: [makeTail(color: theme.backgroundColor), child] ) case .bottomRight: - return LayeredBlock(children: [ + LayeredBlock(children: [ child.addingEdgeInsets(EdgeInsets(top: 5, left: 1, bottom: 0, right: 0)), makeTail(color: theme.backgroundColor), ]) case .bottom: - return try! ContainerBlock( + try! ContainerBlock( layoutDirection: .vertical, horizontalChildrenAlignment: .center, gaps: [0, -1, 0], children: [makeTail(color: theme.backgroundColor), child] ) case .bottomLeft: - return LayeredBlock( + LayeredBlock( horizontalChildrenAlignment: .trailing, children: [ child.addingEdgeInsets(EdgeInsets(top: 5, left: 0, bottom: 0, right: 1)), @@ -136,7 +135,7 @@ extension BlockTooltip.Position { ] ) case .center: - return try! ContainerBlock( + try! ContainerBlock( layoutDirection: .vertical, horizontalChildrenAlignment: .center, gaps: [0, -1, 0], @@ -150,18 +149,18 @@ extension Theme { fileprivate var textColor: Color { switch self { case .light: - return .colorWithHexCode(0xFF_FF_FF_FC) + .colorWithHexCode(0xFF_FF_FF_FC) case .dark: - return .black + .black } } fileprivate var backgroundColor: Color { switch self { case .light: - return .colorWithHexCode(0x2E_2F_34_FF) + .colorWithHexCode(0x2E_2F_34_FF) case .dark: - return .white + .white } } } @@ -183,22 +182,21 @@ private func drawCornerTail( color: Color, context: CGContext ) { - let transform: CGAffineTransform - switch style { + let transform: CGAffineTransform = switch style { case .topLeft: - transform = .identity + .identity .translatedBy(x: 0, y: cornerTailSize.height) .scaledBy(x: 1, y: -1) case .topRight: - transform = .identity + .identity .translatedBy(x: cornerTailSize.width, y: cornerTailSize.height) .scaled(by: -1) case .bottomRight: - transform = .identity + .identity .translatedBy(x: cornerTailSize.width, y: 0) .scaledBy(x: -1, y: 1) case .bottomLeft: - transform = .identity + .identity } context.saveGState() @@ -239,22 +237,21 @@ private func drawMiddleTail( color: Color, context: CGContext ) { - let transform: CGAffineTransform - switch style { + let transform: CGAffineTransform = switch style { case .left: - transform = .identity + .identity .translatedBy(x: 0, y: middleTailSize.height) .scaledBy(x: 1, y: -1) case .top: - transform = .identity + .identity .rotated(by: 3 * .pi / 2) .scaledBy(x: -1, y: 1) case .right: - transform = .identity + .identity .translatedBy(x: middleTailSize.width, y: 0) .scaledBy(x: -1, y: 1) case .bottom: - transform = .identity + .identity .translatedBy(x: middleTailSize.height, y: middleTailSize.width) .scaledBy(x: -1, y: 1) .rotated(by: 3 * .pi / 2) diff --git a/LayoutKit/LayoutKit/Tooltips/TooltipManager.swift b/LayoutKit/LayoutKit/Tooltips/TooltipManager.swift index 3c41b816..802737d3 100644 --- a/LayoutKit/LayoutKit/Tooltips/TooltipManager.swift +++ b/LayoutKit/LayoutKit/Tooltips/TooltipManager.swift @@ -84,11 +84,10 @@ public final class DefaultTooltipManager: TooltipManager { let tooltip = existingAnchorViews.compactMap({ $0?.makeTooltip(id: info.id) }).first else { return } - let window: UIWindow? - if #available(iOS 13.0, *) { - window = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first + let window: UIWindow? = if #available(iOS 13.0, *) { + (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first } else { - window = UIApplication.shared.windows.first + UIApplication.shared.windows.first } let view = TooltipContainerView( diff --git a/LayoutKit/LayoutKit/UI/Base/PageIndicator/IndicatorState/IndicatorStateAnimator.swift b/LayoutKit/LayoutKit/UI/Base/PageIndicator/IndicatorState/IndicatorStateAnimator.swift index b9e47072..1f2b5eee 100644 --- a/LayoutKit/LayoutKit/UI/Base/PageIndicator/IndicatorState/IndicatorStateAnimator.swift +++ b/LayoutKit/LayoutKit/UI/Base/PageIndicator/IndicatorState/IndicatorStateAnimator.swift @@ -45,14 +45,14 @@ struct IndicatorStateAnimator { func highlightedIndicatorScale(for state: IndicatorState, borderScale: Scale) -> Scale { switch configuration.animation { case .scale: - return ( + ( configuration.highlightedWidthScale .interpolated(to: 1, progress: 1 - state.progress) * borderScale.x, configuration.highlightedHeightScale .interpolated(to: 1, progress: 1 - state.progress) * borderScale.y ) case .worm, .slider: - return (1, 1) + (1, 1) } } diff --git a/LayoutKit/LayoutKit/UI/Base/PageIndicator/PageIndicatorLayer.swift b/LayoutKit/LayoutKit/UI/Base/PageIndicator/PageIndicatorLayer.swift index 6d063057..f30d43d6 100644 --- a/LayoutKit/LayoutKit/UI/Base/PageIndicator/PageIndicatorLayer.swift +++ b/LayoutKit/LayoutKit/UI/Base/PageIndicator/PageIndicatorLayer.swift @@ -164,11 +164,10 @@ extension ScrollPageIndicatorLayer { let x = xPosition * params.itemWidth + params.offsetX let y = params.visibleRect.center.y let center = CGPoint(x: x, y: y) - let width: CGFloat - if case let .stretch(spacing, _) = configuration.itemPlacement { - width = params.itemWidth - spacing + let width: CGFloat = if case let .stretch(spacing, _) = configuration.itemPlacement { + params.itemWidth - spacing } else { - width = configuration.pageSize.width + configuration.pageSize.width } return CGRect(center: center, size: CGSize(width: width, height: configuration.pageSize.height)) } @@ -180,14 +179,14 @@ extension ScrollPageIndicatorLayer { ) -> Scale { switch state.kind { case .normal: - return ( + ( configuration.disappearingWidthScale .interpolated(to: 1, progress: state.progress) * borderScale.x, configuration.disappearingHeightScale .interpolated(to: 1, progress: state.progress) * borderScale.y ) case .highlighted: - return animator.highlightedIndicatorScale( + animator.highlightedIndicatorScale( for: state, borderScale: (borderScale.x, borderScale.y) ) diff --git a/LayoutKit/LayoutKit/UI/Blocks/DecoratingBlock+UIViewRenderableBlock.swift b/LayoutKit/LayoutKit/UI/Blocks/DecoratingBlock+UIViewRenderableBlock.swift index dc8f0e89..6a5f902a 100644 --- a/LayoutKit/LayoutKit/UI/Blocks/DecoratingBlock+UIViewRenderableBlock.swift +++ b/LayoutKit/LayoutKit/UI/Blocks/DecoratingBlock+UIViewRenderableBlock.swift @@ -57,9 +57,9 @@ extension NonEmpty<[UserInterfaceAction]>? { fileprivate var hasPayload: Bool { switch self { case let .some(actions): - return !actions.filter { $0.payload != .empty }.isEmpty + !actions.filter { $0.payload != .empty }.isEmpty case .none: - return false + false } } } @@ -74,9 +74,9 @@ extension LongTapActions { fileprivate var hasPayload: Bool { switch self { case let .actions(actions): - return !actions.filter { $0.payload != .empty }.isEmpty + !actions.filter { $0.payload != .empty }.isEmpty case .contextMenu: - return false + false } } } @@ -496,8 +496,8 @@ extension DecoratingView: TooltipAnchorView { extension DecoratingView.HighlightState { var alpha: CGFloat { switch self { - case .normal: return 1 - case .highlighted: return 0.5 + case .normal: 1 + case .highlighted: 0.5 } } } @@ -507,8 +507,8 @@ extension DecoratingView.Model { for highlightState: DecoratingView.HighlightState ) -> Color { switch highlightState { - case .normal: return backgroundColor - case .highlighted: return highlightedBackgroundColor ?? backgroundColor + case .normal: backgroundColor + case .highlighted: highlightedBackgroundColor ?? backgroundColor } } @@ -517,10 +517,10 @@ extension DecoratingView.Model { ) -> [TransitioningAnimation]? { switch highlightState { case .normal: - return actionAnimation?.touchUp + actionAnimation?.touchUp .map { $0.modifyingFade(childAlpha: childAlpha) } case .highlighted: - return actionAnimation?.touchDown + actionAnimation?.touchDown .map { $0.modifyingFade(childAlpha: childAlpha) } } } @@ -530,7 +530,7 @@ extension TransitioningAnimation { fileprivate func modifyingFade(childAlpha: CGFloat) -> Self { switch kind { case .fade: - return TransitioningAnimation( + TransitioningAnimation( kind: .fade, start: start * childAlpha, end: end * childAlpha, @@ -539,7 +539,7 @@ extension TransitioningAnimation { timingFunction: timingFunction ) case .scaleXY, .translationX, .translationY: - return self + self } } } @@ -571,8 +571,8 @@ extension ContextMenu { extension BlurEffect { fileprivate func cast() -> UIBlurEffect.Style { switch self { - case .light: return .light - case .dark: return .dark + case .light: .light + case .dark: .dark } } } diff --git a/LayoutKit/LayoutKit/UI/Blocks/PagerBlock+UIViewRenderableBlock.swift b/LayoutKit/LayoutKit/UI/Blocks/PagerBlock+UIViewRenderableBlock.swift index 61c0b650..b59459a3 100644 --- a/LayoutKit/LayoutKit/UI/Blocks/PagerBlock+UIViewRenderableBlock.swift +++ b/LayoutKit/LayoutKit/UI/Blocks/PagerBlock+UIViewRenderableBlock.swift @@ -164,8 +164,7 @@ private func makeGalleryViewState( ) -> GalleryViewState { let pagerPosition = state.currentPage + CGFloat(model.infiniteCorrection) let position: GalleryViewState.Position - if let oldState, oldState.isScrolling, case let .paging(galleryPage) = oldState.contentPosition, - abs(galleryPage - pagerPosition) < 1 { + if let oldState, oldState.isScrolling { position = oldState.contentPosition } else { position = .paging(index: CGFloat(pagerPosition)) @@ -174,6 +173,7 @@ private func makeGalleryViewState( return GalleryViewState( contentPosition: position, itemsCount: model.items.count, - isScrolling: oldState?.isScrolling ?? false + isScrolling: oldState?.isScrolling ?? false, + scrollRange: oldState?.scrollRange ) } diff --git a/LayoutKit/LayoutKit/UI/Blocks/SwipeContainerBlock+UIViewRenderable.swift b/LayoutKit/LayoutKit/UI/Blocks/SwipeContainerBlock+UIViewRenderable.swift index 830632f3..a795a7e1 100644 --- a/LayoutKit/LayoutKit/UI/Blocks/SwipeContainerBlock+UIViewRenderable.swift +++ b/LayoutKit/LayoutKit/UI/Blocks/SwipeContainerBlock+UIViewRenderable.swift @@ -142,14 +142,13 @@ private final class SwipeContainerView: UIScrollView, UIScrollViewDelegate { } private func updateContentOffset() { - let x: CGFloat - switch state { + let x: CGFloat = switch state { case .left: - x = 0 + 0 case .normal: - x = bounds.width + bounds.width case .right: - x = bounds.width * 2 + bounds.width * 2 } contentOffset = CGPoint(x: x, y: 0) } diff --git a/LayoutKit/LayoutKit/UI/Blocks/SwitchableContainerBlock+UIViewRenderableBlock.swift b/LayoutKit/LayoutKit/UI/Blocks/SwitchableContainerBlock+UIViewRenderableBlock.swift index c6218089..fa33a604 100644 --- a/LayoutKit/LayoutKit/UI/Blocks/SwitchableContainerBlock+UIViewRenderableBlock.swift +++ b/LayoutKit/LayoutKit/UI/Blocks/SwitchableContainerBlock+UIViewRenderableBlock.swift @@ -263,8 +263,8 @@ private final class SegmentedSelectorView: UIView { extension SwitchableContainerBlock.Selection { fileprivate var toggled: SwitchableContainerBlock.Selection { switch self { - case .left: return .right - case .right: return .left + case .left: .right + case .right: .left } } } diff --git a/LayoutKit/LayoutKit/UI/Blocks/TextBlock+UIViewRenderableBlock.swift b/LayoutKit/LayoutKit/UI/Blocks/TextBlock+UIViewRenderableBlock.swift index 5c42761e..4feacec3 100644 --- a/LayoutKit/LayoutKit/UI/Blocks/TextBlock+UIViewRenderableBlock.swift +++ b/LayoutKit/LayoutKit/UI/Blocks/TextBlock+UIViewRenderableBlock.swift @@ -466,9 +466,9 @@ extension TextBlockView: UIGestureRecognizerDelegate { override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == panSelectionRecognizer, selectedRange == nil { - return false + false } else { - return super.gestureRecognizerShouldBegin(gestureRecognizer) + super.gestureRecognizerShouldBegin(gestureRecognizer) } } } @@ -483,9 +483,9 @@ extension Image { extension Alignment { fileprivate var position: NSAttributedString.VerticalPosition { switch self { - case .leading: return .top - case .center: return .center - case .trailing: return .bottom + case .leading: .top + case .center: .center + case .trailing: .bottom } } } @@ -538,11 +538,11 @@ extension Gradient { fileprivate var uiView: UIView { switch self { case let .linear(gradient): - return LinearGradientView(gradient) + LinearGradientView(gradient) case let .radial(gradient): - return RadialGradientView(gradient) + RadialGradientView(gradient) case let .box(color): - return BoxShadowView(shadowColor: color) + BoxShadowView(shadowColor: color) } } } diff --git a/LayoutKit/LayoutKit/UI/Blocks/TextFieldBlock+UIViewRenderableBlock.swift b/LayoutKit/LayoutKit/UI/Blocks/TextFieldBlock+UIViewRenderableBlock.swift index 930cd56b..feb9b50b 100644 --- a/LayoutKit/LayoutKit/UI/Blocks/TextFieldBlock+UIViewRenderableBlock.swift +++ b/LayoutKit/LayoutKit/UI/Blocks/TextFieldBlock+UIViewRenderableBlock.swift @@ -503,9 +503,9 @@ extension TextFieldBlock.Placeholders.Separate { ) -> CGFloat { switch field.position { case .center: - return (blockSize.height - height) / 2 + (blockSize.height - height) / 2 case .normal: - return blockSize.height - (heightTextField + height) / 2 + blockSize.height - (heightTextField + height) / 2 } } } @@ -514,11 +514,11 @@ extension TextFieldBlock.KeyboardAppearance { fileprivate var uiValue: UIKeyboardAppearance { switch self { case .default: - return .default + .default case .light: - return .light + .light case .dark: - return .dark + .dark } } } @@ -556,13 +556,13 @@ extension TextFieldBlock.TextAutocapitalizationType { fileprivate var uiType: UITextAutocapitalizationType { switch self { case .none: - return .none + .none case .words: - return .words + .words case .sentences: - return .sentences + .sentences case .allCharacters: - return .allCharacters + .allCharacters } } } @@ -571,11 +571,11 @@ extension TextFieldBlock.TextAutocorrectionType { fileprivate var uiType: UITextAutocorrectionType { switch self { case .default: - return .default + .default case .no: - return .no + .no case .yes: - return .yes + .yes } } } @@ -584,29 +584,29 @@ extension TextFieldBlock.KeyboardType { fileprivate var uiType: UIKeyboardType { switch self { case .default: - return .default + .default case .asciiCapable: - return .asciiCapable + .asciiCapable case .numbersAndPunctuation: - return .numbersAndPunctuation + .numbersAndPunctuation case .URL: - return .URL + .URL case .numberPad: - return .numberPad + .numberPad case .phonePad: - return .phonePad + .phonePad case .namePhonePad: - return .namePhonePad + .namePhonePad case .emailAddress: - return .emailAddress + .emailAddress case .decimalPad: - return .decimalPad + .decimalPad case .twitter: - return .twitter + .twitter case .webSearch: - return .webSearch + .webSearch case .asciiCapableNumberPad: - return .asciiCapableNumberPad + .asciiCapableNumberPad } } } diff --git a/LayoutKit/LayoutKit/UI/Blocks/TextInputBlock+UIViewRenderableBlock.swift b/LayoutKit/LayoutKit/UI/Blocks/TextInputBlock+UIViewRenderableBlock.swift index 93bcdbaa..a67e3ca9 100644 --- a/LayoutKit/LayoutKit/UI/Blocks/TextInputBlock+UIViewRenderableBlock.swift +++ b/LayoutKit/LayoutKit/UI/Blocks/TextInputBlock+UIViewRenderableBlock.swift @@ -231,11 +231,10 @@ private final class TextInputBlockView: BlockView, VisibleBoundsTrackingLeaf { setupMaskedViewModelIfNeeded(mask: mask, rawTextValue: rawTextValue) } else { self.textValue = textValue - let text: String - if let selectionItems = self.selectionItems { - text = selectionItems.first { $0.value == textValue.value }?.text ?? "" + let text: String = if let selectionItems = self.selectionItems { + selectionItems.first { $0.value == textValue.value }?.text ?? "" } else { - text = textValue.value + textValue.value } setTextData(text) } @@ -471,7 +470,11 @@ extension TextInputBlockView { observer?.focusedElementChanged(isFocused: false, forPath: path) } - private func inputViewReplaceTextIn(view _: UIView, range: Range, text: String) -> Bool { + private func inputViewReplaceTextIn( + view _: UIView, + range: Range, + text: String + ) -> Bool { if maskedViewModel != nil { if text == "" { if range.isEmpty { @@ -543,7 +546,7 @@ extension TextInputBlockView: UITextFieldDelegate { } else { nsRange = range } - + guard let range = Range(nsRange, in: currentText) else { return false } @@ -596,9 +599,9 @@ extension TextInputBlockView { private var cusorOffset: CGFloat { if singleLineInput.isHidden { - return multiLineCusorOffset + multiLineCusorOffset } else { - return singleLineCusorOffset + singleLineCusorOffset } } } @@ -627,29 +630,29 @@ extension TextInputBlock.InputType.KeyboardType { fileprivate var uiType: UIKeyboardType { switch self { case .default: - return .default + .default case .asciiCapable: - return .asciiCapable + .asciiCapable case .numbersAndPunctuation: - return .numbersAndPunctuation + .numbersAndPunctuation case .URL: - return .URL + .URL case .numberPad: - return .numberPad + .numberPad case .phonePad: - return .phonePad + .phonePad case .namePhonePad: - return .namePhonePad + .namePhonePad case .emailAddress: - return .emailAddress + .emailAddress case .decimalPad: - return .decimalPad + .decimalPad case .twitter: - return .twitter + .twitter case .webSearch: - return .webSearch + .webSearch case .asciiCapableNumberPad: - return .asciiCapableNumberPad + .asciiCapableNumberPad } } } @@ -658,15 +661,15 @@ extension TextInputBlockView { fileprivate var textAlignment: TextAlignment { switch textAlignmentHorizontal { case .left: - return .left + .left case .center: - return .center + .center case .right: - return .right + .right case .start: - return layoutDirection == .rightToLeft ? .right : .left + layoutDirection == .rightToLeft ? .right : .left case .end: - return layoutDirection == .rightToLeft ? .left : .right + layoutDirection == .rightToLeft ? .left : .right } } } @@ -675,11 +678,11 @@ extension TextInputBlock.TextAlignmentVertical { fileprivate var contentAlignment: UIControl.ContentVerticalAlignment { switch self { case .top: - return .top + .top case .center: - return .center + .center case .bottom: - return .bottom + .bottom } } } diff --git a/LayoutKit/LayoutKit/UI/Blocks/UIView+TransitioningAnimation.swift b/LayoutKit/LayoutKit/UI/Blocks/UIView+TransitioningAnimation.swift index cfb72e55..66faae90 100644 --- a/LayoutKit/LayoutKit/UI/Blocks/UIView+TransitioningAnimation.swift +++ b/LayoutKit/LayoutKit/UI/Blocks/UIView+TransitioningAnimation.swift @@ -61,23 +61,21 @@ extension UIView { let nonZeroValue = value.isZero ? .ulpOfOne : value transform = CGAffineTransform(scale: nonZeroValue) case .translationX: - let x: CGFloat - if value == TransitioningAnimation.defaultLeadingSlideDistance { - x = -bounds.width + let x: CGFloat = if value == TransitioningAnimation.defaultLeadingSlideDistance { + -bounds.width } else if value == TransitioningAnimation.defaultTrailingSlideDistance { - x = bounds.width + bounds.width } else { - x = value + value } transform = CGAffineTransform(translationX: x, y: 0) case .translationY: - let y: CGFloat - if value == TransitioningAnimation.defaultLeadingSlideDistance { - y = -bounds.height + let y: CGFloat = if value == TransitioningAnimation.defaultLeadingSlideDistance { + -bounds.height } else if value == TransitioningAnimation.defaultTrailingSlideDistance { - y = bounds.height + bounds.height } else { - y = value + value } transform = CGAffineTransform(translationX: 0, y: y) } @@ -110,10 +108,10 @@ private typealias AnimationParams = ( extension TimingFunction { func cast() -> UIView.AnimationOptions { switch self { - case .linear: return .curveLinear - case .easeIn: return .curveEaseIn - case .easeOut: return .curveEaseOut - case .easeInEaseOut: return .curveEaseInOut + case .linear: .curveLinear + case .easeIn: .curveEaseIn + case .easeOut: .curveEaseOut + case .easeInEaseOut: .curveEaseInOut } } } diff --git a/LayoutKit/LayoutKit/UI/Views/Background+UIViewRendering.swift b/LayoutKit/LayoutKit/UI/Views/Background+UIViewRendering.swift index 6c864409..80271b95 100644 --- a/LayoutKit/LayoutKit/UI/Views/Background+UIViewRendering.swift +++ b/LayoutKit/LayoutKit/UI/Views/Background+UIViewRendering.swift @@ -293,13 +293,13 @@ extension Background { .gradient, .ninePatchImage, .block: - return false + false case .transparentAction: - return true + true case let .composite(lhs, rhs, _): - return lhs.isUserInteractionEnabled || rhs.isUserInteractionEnabled + lhs.isUserInteractionEnabled || rhs.isUserInteractionEnabled case let .withInsets(background, _): - return background.isUserInteractionEnabled + background.isUserInteractionEnabled } } } diff --git a/LayoutKit/LayoutKit/UI/Views/GalleryView.swift b/LayoutKit/LayoutKit/UI/Views/GalleryView.swift index f7c08c6e..a138ca00 100644 --- a/LayoutKit/LayoutKit/UI/Views/GalleryView.swift +++ b/LayoutKit/LayoutKit/UI/Views/GalleryView.swift @@ -234,6 +234,7 @@ public final class GalleryView: BlockView { if let model, layout?.isEqual(to: model, boundsSize: bounds.size) != true { updateLayout(to: model) + setState(stateWithScrollRange, notifyingObservers: true) } if case let .pending(state) = deferredStateSetting { collectionView.performWithDetachedDelegate { @@ -257,12 +258,11 @@ public final class GalleryView: BlockView { } private func setContentOffset(_ offset: CGFloat, animated: Bool) { - let contentOffset: CGPoint - switch model.direction { + let contentOffset = switch model.direction { case .vertical: - contentOffset = CGPoint(x: 0, y: offset) + CGPoint(x: 0, y: offset) case .horizontal: - contentOffset = CGPoint(x: offset, y: 0) + CGPoint(x: offset, y: 0) } if collectionView.contentOffset != contentOffset { collectionView.setContentOffset(contentOffset, animated: animated) @@ -306,7 +306,8 @@ extension GalleryView: ScrollDelegate { let newState = GalleryViewState( contentPosition: contentPosition, itemsCount: model.items.count, - isScrolling: true + isScrolling: true, + scrollRange: state.scrollRange ) setState(newState, notifyingObservers: true) updatesDelegate?.onContentOffsetChanged(offset, in: model) @@ -324,9 +325,7 @@ extension GalleryView: ScrollDelegate { } public func onDidEndScrollingAnimation(_ scrollView: ScrollView) { - if model.infiniteScroll { - onDidEndScroll(scrollView) - } + onDidEndScroll(scrollView) } private func getOffset(_ scrollView: ScrollView) -> CGFloat { @@ -339,7 +338,8 @@ extension GalleryView: ScrollDelegate { let newState = GalleryViewState( contentPosition: state.contentPosition, itemsCount: model.items.count, - isScrolling: false + isScrolling: false, + scrollRange: state.scrollRange ) setState(newState, notifyingObservers: true) visibilityDelegate?.onGalleryVisibilityChanged() @@ -409,9 +409,9 @@ extension GalleryViewModel.ScrollMode { fileprivate var decelerationRate: UIScrollView.DecelerationRate { switch self { case .default: - return .normal + .normal case .autoPaging, .fixedPaging: - return .fast + .fast } } } @@ -424,3 +424,16 @@ extension GenericCollectionViewLayout { } extension GalleryView: VisibleBoundsTrackingContainer {} + +extension GalleryView { + var stateWithScrollRange: GalleryViewState { + GalleryViewState( + contentPosition: state.contentPosition, + itemsCount: state.itemsCount, + isScrolling: state.isScrolling, + scrollRange: model.direction.isHorizontal ? + layout.contentSize.width - bounds.width : + layout.contentSize.height - bounds.height + ) + } +} diff --git a/LayoutKit/LayoutKit/UI/Views/TabbedPages/TabListViewDelegate.swift b/LayoutKit/LayoutKit/UI/Views/TabbedPages/TabListViewDelegate.swift index 9583864e..0ca21782 100644 --- a/LayoutKit/LayoutKit/UI/Views/TabbedPages/TabListViewDelegate.swift +++ b/LayoutKit/LayoutKit/UI/Views/TabbedPages/TabListViewDelegate.swift @@ -244,9 +244,9 @@ extension UICollectionView { ($0, layoutAttributesForItem(at: $0)?.frame) }.compactMap { indexPath, frame in if let frame { - return (indexPath, frame) + (indexPath, frame) } else { - return nil + nil } } } diff --git a/LayoutKit/LayoutKit/ViewModels/Background.swift b/LayoutKit/LayoutKit/ViewModels/Background.swift index 7d87f0e3..dd2324ab 100644 --- a/LayoutKit/LayoutKit/ViewModels/Background.swift +++ b/LayoutKit/LayoutKit/ViewModels/Background.swift @@ -30,27 +30,27 @@ public func +=(lhs: inout Background, rhs: Background) { public func ==(lhs: Background, rhs: Background) -> Bool { switch (lhs, rhs) { case let (.solidColor(color1), .solidColor(color2)): - return color1 == color2 + color1 == color2 case let (.tiledImage(image1), .tiledImage(image2)): - return imagesDataAreEqual(image1, image2) + imagesDataAreEqual(image1, image2) case let (.image(image1), .image(image2)): - return image1 == image2 + image1 == image2 case let (.ninePatchImage(image1), .ninePatchImage(image2)): - return image1 == image2 + image1 == image2 case let (.gradient(gradient1), .gradient(gradient2)): - return gradient1 == gradient2 + gradient1 == gradient2 case let (.transparentAction(action1), .transparentAction(action2)): - return action1 == action2 + action1 == action2 case let (.block(block1), .block(block2)): - return block1 == block2 + block1 == block2 case let ( .composite(background11, background12, blendingCoefficient1), .composite(background21, background22, blendingCoefficient2) ): - return background11 == background21 && background12 == background22 && blendingCoefficient1 == + background11 == background21 && background12 == background22 && blendingCoefficient1 == blendingCoefficient2 case let (.withInsets(background1, insets1), .withInsets(background2, insets2)): - return background1 == background2 && insets1 == insets2 + background1 == background2 && insets1 == insets2 case (.solidColor, _), (.tiledImage, _), (.image, _), @@ -60,7 +60,7 @@ public func ==(lhs: Background, rhs: Background) -> Bool { (.composite, _), (.withInsets, _), (.ninePatchImage, _): - return false + false } } @@ -107,20 +107,20 @@ extension Background: ImageContaining { public func getImageHolders() -> [ImageHolder] { switch self { case let .composite(first, second, _): - return first.getImageHolders() + second.getImageHolders() + first.getImageHolders() + second.getImageHolders() case let .image(image): - return [image.imageHolder] + [image.imageHolder] case let .ninePatchImage(image): - return [image.imageHolder] + [image.imageHolder] case let .withInsets(background, _): - return background.getImageHolders() + background.getImageHolders() case let .block(block): - return block.getImageHolders() + block.getImageHolders() case .solidColor, .tiledImage, .gradient, .transparentAction: - return [] + [] } } } diff --git a/LayoutKit/LayoutKit/ViewModels/GalleryViewLayout.swift b/LayoutKit/LayoutKit/ViewModels/GalleryViewLayout.swift index 37ead44e..b452ad97 100644 --- a/LayoutKit/LayoutKit/ViewModels/GalleryViewLayout.swift +++ b/LayoutKit/LayoutKit/ViewModels/GalleryViewLayout.swift @@ -53,12 +53,11 @@ public struct GalleryViewLayout: GalleryViewLayouting, Equatable { let page = blockPages[integralIndex] let fractionalIndex = pageIndex.truncatingRemainder(dividingBy: 1) - let maxOffset: CGFloat - switch model.direction { + let maxOffset: CGFloat = switch model.direction { case .horizontal: - maxOffset = max(0, contentSize.width - boundsSize.width) + max(0, contentSize.width - boundsSize.width) case .vertical: - maxOffset = max(0, contentSize.height - boundsSize.height) + max(0, contentSize.height - boundsSize.height) } return min(maxOffset, page.origin + page.size * fractionalIndex) } @@ -91,9 +90,9 @@ extension GalleryViewModel { fileprivate func frames(fitting size: CGSize?) -> [CGRect] { switch direction { case .horizontal: - return horizontallyOrientedFrames(fitting: size) + horizontallyOrientedFrames(fitting: size) case .vertical: - return verticallyOrientedFrames(fitting: size) + verticallyOrientedFrames(fitting: size) } } @@ -152,11 +151,11 @@ extension GalleryViewModel { fileprivate func pageSize(fitting size: CGSize?) -> CGFloat { switch scrollMode { case .default: - return 0 + 0 case .autoPaging: - return size?.dimension(in: direction) ?? 0 + size?.dimension(in: direction) ?? 0 case let .fixedPaging(pageSize: value): - return value + value } } @@ -169,15 +168,14 @@ extension GalleryViewModel { } let crossInsets = self.crossInsets(forSize: size) let crossSpacing = metrics.crossSpacing - let maxItemHeight: CGFloat - if let size { - maxItemHeight = (size.height - crossInsets.sum - crossSpacing * CGFloat(columnCount - 1)) / + let maxItemHeight: CGFloat = if let size { + (size.height - crossInsets.sum - crossSpacing * CGFloat(columnCount - 1)) / CGFloat(columnCount) } else if let maxNonResizableHeight = blocks .maxHeightOfVerticallyNonResizableBlocks(for: widths) { - maxItemHeight = maxNonResizableHeight + maxNonResizableHeight } else { - maxItemHeight = 0 + 0 } let gaps = self.gaps(forSize: size) @@ -266,11 +264,11 @@ extension Alignment { fileprivate func origin(of dimension: CGFloat, minimum: CGFloat, maximum: CGFloat) -> CGFloat { switch self { case .leading: - return minimum + minimum case .center: - return floor((minimum + maximum - dimension) / 2) + floor((minimum + maximum - dimension) / 2) case .trailing: - return maximum - dimension + maximum - dimension } } } @@ -279,9 +277,9 @@ extension CGPoint { fileprivate func dimension(in direction: GalleryViewModel.Direction) -> CGFloat { switch direction { case .horizontal: - return x + x case .vertical: - return y + y } } } @@ -290,9 +288,9 @@ extension CGSize { fileprivate func dimension(in direction: GalleryViewModel.Direction) -> CGFloat { switch direction { case .horizontal: - return width + width case .vertical: - return height + height } } } diff --git a/LayoutKit/LayoutKit/ViewModels/GalleryViewModel.swift b/LayoutKit/LayoutKit/ViewModels/GalleryViewModel.swift index 3f2d89a9..03553217 100644 --- a/LayoutKit/LayoutKit/ViewModels/GalleryViewModel.swift +++ b/LayoutKit/LayoutKit/ViewModels/GalleryViewModel.swift @@ -23,9 +23,9 @@ public struct GalleryViewModel: Equatable { public var isHorizontal: Bool { switch self { case .horizontal: - return true + true case .vertical: - return false + false } } } @@ -47,9 +47,9 @@ public struct GalleryViewModel: Equatable { public var show: Bool { switch self { case .none: - return false + false case .auto: - return true + true } } } diff --git a/LayoutKit/LayoutKit/ViewModels/GalleryViewState.swift b/LayoutKit/LayoutKit/ViewModels/GalleryViewState.swift index e76b8f73..54d26323 100644 --- a/LayoutKit/LayoutKit/ViewModels/GalleryViewState.swift +++ b/LayoutKit/LayoutKit/ViewModels/GalleryViewState.swift @@ -12,27 +12,27 @@ public struct GalleryViewState: ElementState, Equatable { public var offset: CGFloat? { switch self { case let .offset(value, _): - return value + value case .paging: - return nil + nil } } public var pageIndex: CGFloat? { switch self { case .offset: - return nil + nil case let .paging(index: index): - return index + index } } public var isPaging: Bool { switch self { case .paging: - return true + true case .offset: - return false + false } } @@ -58,6 +58,7 @@ public struct GalleryViewState: ElementState, Equatable { public let contentPosition: Position public let itemsCount: Int public let isScrolling: Bool + public let scrollRange: CGFloat? public init( contentOffset: CGFloat, @@ -66,6 +67,7 @@ public struct GalleryViewState: ElementState, Equatable { self.contentPosition = .offset(contentOffset) self.itemsCount = itemsCount self.isScrolling = false + self.scrollRange = nil } public init( @@ -75,16 +77,19 @@ public struct GalleryViewState: ElementState, Equatable { self.contentPosition = .paging(index: contentPageIndex) self.itemsCount = itemsCount self.isScrolling = false + self.scrollRange = nil } public init( contentPosition: Position, itemsCount: Int, - isScrolling: Bool + isScrolling: Bool, + scrollRange: CGFloat? = nil ) { self.contentPosition = contentPosition self.itemsCount = itemsCount self.isScrolling = isScrolling + self.scrollRange = scrollRange } } @@ -110,7 +115,8 @@ extension GalleryViewState { return GalleryViewState( contentPosition: newContentPosition, itemsCount: itemsCount, - isScrolling: isScrolling + isScrolling: isScrolling, + scrollRange: scrollRange ) } } diff --git a/LayoutKit/LayoutKit/ViewModels/PagerViewLayout.swift b/LayoutKit/LayoutKit/ViewModels/PagerViewLayout.swift index 4abf498d..1bc64fb5 100644 --- a/LayoutKit/LayoutKit/ViewModels/PagerViewLayout.swift +++ b/LayoutKit/LayoutKit/ViewModels/PagerViewLayout.swift @@ -95,9 +95,9 @@ extension GalleryViewModel { fileprivate func frames(fitting size: CGSize?, layoutMode: PagerBlock.LayoutMode) -> [CGRect] { switch direction { case .horizontal: - return horizontallyOrientedFrames(fitting: size, layoutMode: layoutMode) + horizontallyOrientedFrames(fitting: size, layoutMode: layoutMode) case .vertical: - return verticallyOrientedFrames(fitting: size, layoutMode: layoutMode) + verticallyOrientedFrames(fitting: size, layoutMode: layoutMode) } } @@ -253,11 +253,11 @@ extension Alignment { fileprivate func origin(of dimension: CGFloat, minimum: CGFloat, maximum: CGFloat) -> CGFloat { switch self { case .leading: - return minimum + minimum case .center: - return floor((minimum + maximum - dimension) / 2) + floor((minimum + maximum - dimension) / 2) case .trailing: - return maximum - dimension + maximum - dimension } } } @@ -266,9 +266,9 @@ extension CGPoint { fileprivate func dimension(in direction: GalleryViewModel.Direction) -> CGFloat { switch direction { case .horizontal: - return x + x case .vertical: - return y + y } } } @@ -277,9 +277,9 @@ extension CGSize { fileprivate func dimension(in direction: GalleryViewModel.Direction) -> CGFloat { switch direction { case .horizontal: - return width + width case .vertical: - return height + height } } } diff --git a/LayoutKit/LayoutKit/ViewModels/TabbedPages/TabContentsViewLayout.swift b/LayoutKit/LayoutKit/ViewModels/TabbedPages/TabContentsViewLayout.swift index 878dd434..941bc48d 100644 --- a/LayoutKit/LayoutKit/ViewModels/TabbedPages/TabContentsViewLayout.swift +++ b/LayoutKit/LayoutKit/ViewModels/TabbedPages/TabContentsViewLayout.swift @@ -48,12 +48,11 @@ struct TabContentsViewLayout: Equatable { pagesInsets: EdgeInsets ) -> CGFloat { let itemWidth = width - pagesInsets.horizontalInsets.sum - let listHeight: CGFloat - switch pagesHeightMode { + let listHeight: CGFloat = switch pagesHeightMode { case .byHighestPage: - listHeight = pages.map { $0.intrinsicContentHeight(forWidth: itemWidth) }.max()! + pages.map { $0.intrinsicContentHeight(forWidth: itemWidth) }.max()! case .bySelectedPage: - listHeight = pages.intrinsicContentHeight( + pages.intrinsicContentHeight( forWidth: itemWidth, selectedPageIndex: selectedPageIndex ) diff --git a/LayoutKit/LayoutKit/ViewModels/TabbedPages/TabViewLayout.swift b/LayoutKit/LayoutKit/ViewModels/TabbedPages/TabViewLayout.swift index 7ea8bc7b..dc74a802 100644 --- a/LayoutKit/LayoutKit/ViewModels/TabbedPages/TabViewLayout.swift +++ b/LayoutKit/LayoutKit/ViewModels/TabbedPages/TabViewLayout.swift @@ -31,12 +31,11 @@ public struct TabViewLayout: Equatable { let newWidth = width ?? max(contentsModel.intrinsicWidth, separatorInsets.horizontalInsets.sum) - let height: CGFloat? - switch contentsModel.pagesHeight { + let height: CGFloat? = switch contentsModel.pagesHeight { case .byHighestPage: - height = oldHeight + oldHeight case .bySelectedPage: - height = nil + nil } let newHeight = height ?? contentsModel.intrinsicHeight( diff --git a/Serialization/DeserializationError.swift b/Serialization/DeserializationError.swift index 9f43f0bc..fa4eacdc 100644 --- a/Serialization/DeserializationError.swift +++ b/Serialization/DeserializationError.swift @@ -25,44 +25,44 @@ public indirect enum DeserializationError: Error, CustomStringConvertible { private func getDescription(path: [String]) -> String { switch self { case let .composite(error, causes): - return "[\(path.joined(separator: "/"))]: \(error)," + + "[\(path.joined(separator: "/"))]: \(error)," + " caused by " + "\(causes.map { $0.getDescription(path: path) }.joined(separator: "; "))" case let .nestedObjectError(field, error): - return error.getDescription(path: path + [field]) + error.getDescription(path: path + [field]) default: - return "[\(path.joined(separator: "/"))]: \(errorMessage)" + "[\(path.joined(separator: "/"))]: \(errorMessage)" } } public var errorMessage: String { switch self { case .generic: - return "Deserialization error" + "Deserialization error" case .nonUTF8String: - return "Non-UTF8 string" + "Non-UTF8 string" case .invalidJSONData: - return "Invalid JSON" + "Invalid JSON" case let .missingType(representation): - return "Missing type: \(representation)" + "Missing type: \(representation)" case let .unknownType(type): - return "Unknown type: \(type)" + "Unknown type: \(type)" case let .invalidFieldRepresentation(field, representation): - return "Invalid '\(field)' value: \(dbgStrLimited(representation))" + "Invalid '\(field)' value: \(dbgStrLimited(representation))" case let .typeMismatch(expected, representation): - return "Type mismatch: \(dbgStrLimited(representation)), but '\(expected)' expected" + "Type mismatch: \(dbgStrLimited(representation)), but '\(expected)' expected" case let .invalidValue(result, value): - return "Invalid value: '\(dbgStrLimited(result))', from '\(dbgStrLimited(value))'" + "Invalid value: '\(dbgStrLimited(result))', from '\(dbgStrLimited(value))'" case let .requiredFieldIsMissing(field): - return "Required field is missing: \(field)" + "Required field is missing: \(field)" case let .nestedObjectError(_, error): - return error.errorMessage + error.errorMessage case .noData: - return "No data" + "No data" case let .composite(error, _): - return "\(error)" + "\(error)" case let .unexpectedError(message): - return "Unexpected error: \(message)" + "Unexpected error: \(message)" } } @@ -93,29 +93,29 @@ public indirect enum DeserializationError: Error, CustomStringConvertible { public var rootCauses: [DeserializationError] { switch self { case let .composite(_, causes): - return causes.flatMap(\.rootCauses) + causes.flatMap(\.rootCauses) case let .nestedObjectError(field, error): - return error.rootCauses.map { .nestedObjectError(field: field, error: $0) } + error.rootCauses.map { .nestedObjectError(field: field, error: $0) } default: - return [self] + [self] } } private var subkind: String { switch self { - case .generic: return "generic" - case .invalidFieldRepresentation: return "invalidFieldRepresentation" - case .invalidJSONData: return "invalidJSONData" - case .invalidValue: return "invalidValue" - case .missingType: return "missingType" - case let .nestedObjectError(_, error): return error.subkind - case .noData: return "noData" - case .nonUTF8String: return "nonUTF8String" - case .requiredFieldIsMissing: return "requiredFieldIsMissing" - case .typeMismatch: return "typeMismatch" - case .unexpectedError: return "unexpectedError" - case .unknownType: return "unknownType" - case .composite: return "composite" + case .generic: "generic" + case .invalidFieldRepresentation: "invalidFieldRepresentation" + case .invalidJSONData: "invalidJSONData" + case .invalidValue: "invalidValue" + case .missingType: "missingType" + case let .nestedObjectError(_, error): error.subkind + case .noData: "noData" + case .nonUTF8String: "nonUTF8String" + case .requiredFieldIsMissing: "requiredFieldIsMissing" + case .typeMismatch: "typeMismatch" + case .unexpectedError: "unexpectedError" + case .unknownType: "unknownType" + case .composite: "composite" } } @@ -125,7 +125,7 @@ public indirect enum DeserializationError: Error, CustomStringConvertible { public var description: String { switch self { case let .invalidValue(result, value): - return "Invalid value: '\(dbgStrLimited(result))', from: '\(dbgStrLimited(value))'" + "Invalid value: '\(dbgStrLimited(result))', from: '\(dbgStrLimited(value))'" } } } @@ -138,9 +138,9 @@ fileprivate func dbgStrLimited(_ val: (some Any)?, limit: UInt = 100) -> String extension String { fileprivate func crop(_ limit: UInt) -> String { if self.count <= limit { - return self + self } else { - return "\(self.prefix(Int(limit)))..." + "\(self.prefix(Int(limit)))..." } } } diff --git a/Serialization/DeserializationResult.swift b/Serialization/DeserializationResult.swift index a1559635..c61098f4 100644 --- a/Serialization/DeserializationResult.swift +++ b/Serialization/DeserializationResult.swift @@ -14,9 +14,9 @@ extension DeserializationResult { public var value: T? { switch self { case let .success(value), let .partialSuccess(value, _): - return value + value case .failure, .noValue: - return nil + nil } } @@ -25,27 +25,27 @@ extension DeserializationResult { public var warnings: NonEmptyArray? { switch self { case let .partialSuccess(_, warnings): - return warnings + warnings case .success, .failure, .noValue: - return nil + nil } } public var errors: NonEmptyArray? { switch self { case let .failure(errors): - return errors + errors case .partialSuccess, .success, .noValue: - return nil + nil } } public var errorsOrWarnings: NonEmptyArray? { switch self { case let .partialSuccess(_, errors), let .failure(errors): - return errors + errors case .success, .noValue: - return nil + nil } } diff --git a/Specs/DivKit/29.9.0/DivKit.podspec b/Specs/DivKit/29.9.0/DivKit.podspec new file mode 100644 index 00000000..e4d8bbc0 --- /dev/null +++ b/Specs/DivKit/29.9.0/DivKit.podspec @@ -0,0 +1,25 @@ +Pod::Spec.new do |s| + s.name = 'DivKit' + s.version = '29.9.0' + s.summary = 'DivKit framework' + s.description = 'DivKit is a backend-driven UI framework' + s.homepage = 'https://divkit.tech' + + s.license = { :type => 'Apache License, Version 2.0', :file => 'LICENSE' } + s.author = { 'divkit' => 'divkit@yandex-team.ru' } + s.source = { :git => 'https://github.com/divkit/divkit-ios.git', :tag => s.version.to_s } + + s.swift_version = '5.9' + s.requires_arc = true + s.prefix_header_file = false + s.platforms = { :ios => '11.0' } + + s.dependency 'DivKit_LayoutKit', s.version.to_s + s.dependency 'DivKit_Serialization', s.version.to_s + s.dependency 'VGSLCommonCore', '~> 3.0' + s.dependency 'VGSLNetworking', '~> 3.0' + + s.source_files = [ + 'DivKit/**/*' + ] +end diff --git a/Specs/DivKitExtensions/29.9.0/DivKitExtensions.podspec b/Specs/DivKitExtensions/29.9.0/DivKitExtensions.podspec new file mode 100644 index 00000000..8bfaf4f5 --- /dev/null +++ b/Specs/DivKitExtensions/29.9.0/DivKitExtensions.podspec @@ -0,0 +1,22 @@ +Pod::Spec.new do |s| + s.name = 'DivKitExtensions' + s.version = '29.9.0' + s.summary = 'DivKit framework extensions' + s.description = 'Part of DivKit framework' + s.homepage = 'https://divkit.tech' + + s.license = { :type => 'Apache License, Version 2.0', :file => 'LICENSE' } + s.author = { 'divkit' => 'divkit@yandex-team.ru' } + s.source = { :git => 'https://github.com/divkit/divkit-ios.git', :tag => s.version.to_s } + + s.swift_version = '5.9' + s.requires_arc = true + s.prefix_header_file = false + s.platforms = { :ios => '11.0' } + + s.dependency 'DivKit', s.version.to_s + + s.source_files = [ + 'DivKitExtensions/**/*' + ] +end diff --git a/Specs/DivKit_LayoutKit/29.9.0/DivKit_LayoutKit.podspec b/Specs/DivKit_LayoutKit/29.9.0/DivKit_LayoutKit.podspec new file mode 100644 index 00000000..50e9166a --- /dev/null +++ b/Specs/DivKit_LayoutKit/29.9.0/DivKit_LayoutKit.podspec @@ -0,0 +1,25 @@ +Pod::Spec.new do |s| + s.name = 'DivKit_LayoutKit' + s.module_name = 'LayoutKit' + s.version = '29.9.0' + s.summary = 'Part of DivKit framework' + s.description = 'Part of DivKit framework' + s.homepage = 'https://divkit.tech' + + s.license = { :type => 'Apache License, Version 2.0', :file => 'LICENSE' } + s.author = { 'divkit' => 'divkit@yandex-team.ru' } + s.source = { :git => 'https://github.com/divkit/divkit-ios.git', :tag => s.version.to_s } + + s.swift_version = '5.9' + s.requires_arc = true + s.prefix_header_file = false + s.platforms = { :ios => '11.0' } + + s.dependency 'DivKit_LayoutKitInterface', s.version.to_s + s.dependency 'VGSLCommonCore', '~> 3.0' + s.dependency 'VGSLNetworking', '~> 3.0' + + s.source_files = [ + 'LayoutKit/LayoutKit/**/*' + ] +end diff --git a/Specs/DivKit_LayoutKitInterface/29.9.0/DivKit_LayoutKitInterface.podspec b/Specs/DivKit_LayoutKitInterface/29.9.0/DivKit_LayoutKitInterface.podspec new file mode 100644 index 00000000..435f9ef0 --- /dev/null +++ b/Specs/DivKit_LayoutKitInterface/29.9.0/DivKit_LayoutKitInterface.podspec @@ -0,0 +1,25 @@ +Pod::Spec.new do |s| + s.name = 'DivKit_LayoutKitInterface' + s.module_name = 'LayoutKitInterface' + s.version = '29.9.0' + s.summary = 'Part of DivKit framework' + s.description = 'Part of DivKit framework' + s.homepage = 'https://divkit.tech' + + s.license = { :type => 'Apache License, Version 2.0', :file => 'LICENSE' } + s.author = { 'divkit' => 'divkit@yandex-team.ru' } + s.source = { :git => 'https://github.com/divkit/divkit-ios.git', :tag => s.version.to_s } + + s.swift_version = '5.9' + s.requires_arc = true + s.prefix_header_file = false + s.platforms = { :ios => '11.0' } + + s.dependency 'VGSLBase', '~> 3.0' + s.dependency 'VGSLBaseTiny', '~> 3.0' + s.dependency 'VGSLBaseUI', '~> 3.0' + + s.source_files = [ + 'LayoutKit/Interface/**/*' + ] +end diff --git a/Specs/DivKit_Serialization/29.9.0/DivKit_Serialization.podspec b/Specs/DivKit_Serialization/29.9.0/DivKit_Serialization.podspec new file mode 100644 index 00000000..9a53c445 --- /dev/null +++ b/Specs/DivKit_Serialization/29.9.0/DivKit_Serialization.podspec @@ -0,0 +1,23 @@ +Pod::Spec.new do |s| + s.name = 'DivKit_Serialization' + s.module_name = 'Serialization' + s.version = '29.9.0' + s.summary = 'Part of DivKit framework' + s.description = 'Part of DivKit framework' + s.homepage = 'https://divkit.tech' + + s.license = { :type => 'Apache License, Version 2.0', :file => 'LICENSE' } + s.author = { 'divkit' => 'divkit@yandex-team.ru' } + s.source = { :git => 'https://github.com/divkit/divkit-ios.git', :tag => s.version.to_s } + + s.swift_version = '5.9' + s.requires_arc = true + s.prefix_header_file = false + s.platforms = { :ios => '11.0' } + + s.dependency 'VGSLCommonCore', '~> 3.0' + + s.source_files = [ + 'Serialization/**/*' + ] +end