diff --git a/docs/architecture/render/ios/native-render.md b/docs/architecture/render/ios/native-render.md index b07a5f1e91d..de0a6d12efc 100644 --- a/docs/architecture/render/ios/native-render.md +++ b/docs/architecture/render/ios/native-render.md @@ -4,9 +4,9 @@ Hippy抽象了RenderManager的接口,允许接入方自行实现RenderManager接口,并实现上屏操作。其中Native Renderer由Hippy默认实现,通过Native组件构建出整个Hippy界面。 -NativeRenderManager负责实现Hippy::RenderManager的抽象接口,并将Render树的构建与UI上屏的行为交由NativeRenderImpl处理。 +NativeRenderManager负责实现Hippy::RenderManager的抽象接口,并将Render树的构建与UI上屏的行为交由HippyUIManager处理。 -NativeRenderImpl负责处理以下行为: +HippyUIManager负责处理以下行为: - Render节点的创建与管理 - RooView与RootNode绑定与管理(不持有) @@ -58,7 +58,7 @@ NativeRenderImpl负责处理以下行为: 为此,需要设定render节点的懒加载属性,以保证UI的懒创建。 -在iOS中,此能力由`[NativeRenderObjectView creationType:NativeRenderCreationType]`属性控制。 +在iOS中,此能力由`[HippyShadowView creationType:NativeRenderCreationType]`属性控制。 ![image](../../../assets/img/lazy_load1.png) 对于懒加载组件,需要手动调用创建方法才会创建。 ![image](../../../assets/img/lazy_load2.png) @@ -141,13 +141,13 @@ Text组件算是一个比较特殊的组件,相对于其他组件,其有两 各业务会选择不同的图片格式就计入,而iOS api默认支持的图片格式有限。这种情况下,需要提供接口,处理默认不支持的图片格式解码。 -为此我们声明了一份协议HPImageProviderProtocol,专门处理各类型Image的解码工作。 +为此我们声明了一份协议HippyImageProviderProtocol,专门处理各类型Image的解码工作。 接入方如果有自定义格式,需要实现一份protocol。 -#### HPImageProviderProtocol +#### HippyImageProviderProtocol -`HPImageProviderProtocol`包含有两类方法:必须实现的和可选实现的。 +`HippyImageProviderProtocol`包含有两类方法:必须实现的和可选实现的。 必须实现的方法负责处理图片解码的基本操作,而可选实现的用于处理动图。 接入方可同时添加多个解码器,HippySDK 在需要时,会按照解码器添加反序询问各解码器能否处理当前数据。如果不能,则会询问下个解码器,直至获取了对应的解码器,或者使用默认解码器。 @@ -167,7 +167,7 @@ Text组件算是一个比较特殊的组件,相对于其他组件,其有两 | -(NSUIneger)loopCount | 返回动图循环次数 | | -(double)delayTimeAtFrame:(NSUInteger)frame | 返回指定帧延迟时长 | -#### HPDefaultImageProvider +#### HippyDefaultImageProvider Hippy3.0默认实现了一套decoder作为默认decoder,实现对系统支持的格式进行解码操作。任何没有decoder处理的数据,最终都会由HippyDefaultImageProvider调用系统API CGImageSource进行处理。 @@ -178,6 +178,6 @@ Hippy3.0默认实现了一套decoder作为默认decoder,实现对系统支持 - Hipp3.0SDK的动图逻辑由NativeRenderAnimatedImage和NativeRenderAnimatedImageView负责。 - 这是一个生产者-消费者模型。NativeRenderAnimatedImage负责生产,NativeRenderAnimatedImageView负责消费。 - NativeRenderAnimatedImageView实现一个vsync回调,每次回调向NativeRenderAnimatedImage询问当前帧对应的Image -- NativeRenderAnimatedImage持有HPImageProviderProtocol实例,负责解析动图,并返回对应帧的Image +- NativeRenderAnimatedImage持有HippyImageProviderProtocol实例,负责解析动图,并返回对应帧的Image ![image](../../../assets/img/animated_image.png) diff --git a/docs/development/native-component.md b/docs/development/native-component.md index 36bc31d7110..adb9e21db34 100644 --- a/docs/development/native-component.md +++ b/docs/development/native-component.md @@ -183,13 +183,13 @@ protected void onAttachedToWindow() { ## 创建对应的ViewManager > ViewManager 是对应的视图管理组件,负责前端视图和终端视图直接进行属性、方法的调用。 -> SDK 中最基础的 `ViewManager` 是 `NativeRenderViewManager`,封装了基本的方法,负责管理 `NativeRenderView`。 -> 用户自定的 `ViewManager` 必须继承自 `NativeRenderViewManager`。 +> SDK 中最基础的 `ViewManager` 是 `HippyViewManager`,封装了基本的方法,负责管理 `NativeRenderView`。 +> 用户自定的 `ViewManager` 必须继承自 `HippyViewManager`。 NativeRenderMyViewManager.h ```objectivec -@interface NativeRenderMyViewManager:NativeRenderViewManager +@interface NativeRenderMyViewManager:HippyViewManager @end ``` @@ -198,15 +198,15 @@ NativeRenderMyViewManager.m ```objectivec @implementation NativeRenderMyViewManager -NATIVE_RENDER_EXPORT_VIEW(MyView) +HIPPY_EXPORT_MODULE(MyView) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(backgroundColor, UIColor) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(opacity, alpha, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(backgroundColor, UIColor) +HIPPY_REMAP_VIEW_PROPERTY(opacity, alpha, CGFloat) -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(overflow, CSSOverflow, NativeRenderView) +HIPPY_CUSTOM_VIEW_PROPERTY(overflow, CSSOverflow, HippyView) { if (json) { - view.clipsToBounds = [HPConvert CSSOverflow:json] != CSSOverflowVisible; + view.clipsToBounds = [HippyConvert CSSOverflow:json] != CSSOverflowVisible; } else { view.clipsToBounds = defaultView.clipsToBounds; } @@ -216,15 +216,15 @@ NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(overflow, CSSOverflow, NativeRenderView) return [[NativeRenderMyView alloc] init]; } -- (NativeRenderObjectView *)shadowView { - return [[NativeRenderObjectView alloc] init]; +- (HippyShadowView *)shadowView { + return [[HippyShadowView alloc] init]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(focus:(nonnull NSNumber *)reactTag) { +HIPPY_EXPORT_METHOD(focus:(nonnull NSNumber *)reactTag) { // do sth } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(focus:(nonnull NSNumber *)reactTag callback:(RenderUIResponseSenderBlock)callback) { +HIPPY_EXPORT_METHOD(focus:(nonnull NSNumber *)reactTag callback:(HippyPromiseResolveBlock)callback) { // do sth NSArray *result = xxx; callback(result); @@ -233,42 +233,42 @@ NATIVE_RENDER_COMPONENT_EXPORT_METHOD(focus:(nonnull NSNumber *)reactTag callbac ## 类型导出 -`NATIVE_RENDER_EXPORT_VIEW()` 将`NativeRenderMyViewManager` 类注册,前端在对 `MyView` 进行操作时会通过 `NativeRenderMyViewManager` 进行实例对象指派。 +`HIPPY_EXPORT_MODULE()` 将`NativeRenderMyViewManager` 类注册,前端在对 `MyView` 进行操作时会通过 `NativeRenderMyViewManager` 进行实例对象指派。 -`NATIVE_RENDER_EXPORT_VIEW()`中的参数可选。代表的是 `ViewManager` 对应的View名称。 +`HIPPY_EXPORT_MODULE()`中的参数可选。代表的是 `ViewManager` 对应的View名称。 若用户不填写,则默认使用类名称。 ## 参数导出 -`NATIVE_RENDER_EXPORT_VIEW_PROPERTY` 将终端View的参数和前端参数绑定。当前端设定参数值时,会自动调用 setter 方法设置到终端对应的参数。 +`HIPPY_EXPORT_VIEW_PROPERTY` 将终端View的参数和前端参数绑定。当前端设定参数值时,会自动调用 setter 方法设置到终端对应的参数。 -`NATIVE_RENDER_REMAP_VIEW_PROPERTY()` 负责将前端对应的参数名和终端对应的参数名对应起来。以上述代码为例,前端的`opacity` 参数对应终端的`alpha`参数。此宏一共包含三个参数,第一个为前端参数名,第二个为对应的终端参数名称,第三个为参数类型。另外,此宏在设置终端参数时使用的是`keyPath`方法,即终端可以使用`keyPath`参数。 +`HIPPY_REMAP_VIEW_PROPERTY()` 负责将前端对应的参数名和终端对应的参数名对应起来。以上述代码为例,前端的`opacity` 参数对应终端的`alpha`参数。此宏一共包含三个参数,第一个为前端参数名,第二个为对应的终端参数名称,第三个为参数类型。另外,此宏在设置终端参数时使用的是`keyPath`方法,即终端可以使用`keyPath`参数。 -`NATIVE_RENDER_CUSTOM_VIEW_PROPERTY()` 允许终端自行解析前端参数。SDK将前端传递过来的原始json类型数据传递给函数体(用户可以使用`HPConvert`类中的方法解析对应的数据),用户获取后自行解析。 +`HIPPY_CUSTOM_VIEW_PROPERTY()` 允许终端自行解析前端参数。SDK将前端传递过来的原始json类型数据传递给函数体(用户可以使用`HippyConvert`类中的方法解析对应的数据),用户获取后自行解析。 >这个方法带有两个隐藏参数-`view`, `defaultView`。`view`是指当前前端要求渲染的view。`defaultView`指当前端渲染参数为nil时创建的一个临时view,使用其默认参数赋值。 ## 方法导出 -`NATIVE_RENDER_COMPONENT_EXPORT_METHOD` 能够使前端随时调用终端对应的方法。前端通过三种模式调用,分别是 `callNative`, `callNativeWithCallbackId`。终端调用这三种方式时,函数体写法可以参照上面的示例。 +`HIPPY_EXPORT_METHOD` 能够使前端随时调用终端对应的方法。前端通过三种模式调用,分别是 `callNative`, `callNativeWithCallbackId`。终端调用这三种方式时,函数体写法可以参照上面的示例。 - callNative:此方法不需要终端返回任何值。 -- callNativeWithCallbackId: 此方法需要终端在函数体中以单个block形式返回数据。block类型为 `RenderUIResponseSenderBlock`,参数为一个`id`变量。 +- callNativeWithCallbackId: 此方法需要终端在函数体中以单个block形式返回数据。block类型为 `HippyPromiseResolveBlock`,参数为一个`id`变量。 一个`ViewManager`可以管理一种类型的多个实例,为了在ViewManager中区分当前操作的是哪个View,每一个导出方法对应的第一个参数都是View对应的tag值,用户可根据这个tag值找到对应操作的view。 -> 由于导出方法并不会在主线程中调用,因此如果用户需要进行UI操作,则必须将其分配至主线程。推荐在导出方法中使用[NativeRenderImpl addUIBlock:]方法。其中的block类型为`NativeRenderRenderUIBlock`。 +> 由于导出方法并不会在主线程中调用,因此如果用户需要进行UI操作,则必须将其分配至主线程。推荐在导出方法中使用[HippyUIManager addUIBlock:]方法。其中的block类型为`HippyViewManagerUIBlock`。 -> `typedef void (^NativeRenderRenderUIBlock)(NativeRenderImpl *renderContext, NSDictionary *viewRegistry)`。第二个参数为字典,其中的key就是对应的view tag值,value就是对应的view。 +> `typedef void (^HippyViewManagerUIBlock)(HippyUIManager *uiManager, NSDictionary *viewRegistry)`。第二个参数为字典,其中的key就是对应的view tag值,value就是对应的view。 ## 创建RenderObject和View -在OC层,`NativeRenderImpl`负责构建Render树,对应的每一个节点都是一个RenderObjectView。Render树结构不保证与dom树一致,因为Render可能有自己的渲染逻辑。 +在OC层,`HippyUIManager`负责构建Render树,对应的每一个节点都是一个RenderObjectView。Render树结构不保证与dom树一致,因为Render可能有自己的渲染逻辑。 ->`NativeRenderView`会根据`NativeRenderObjectView`的映射结果构建真正的View视图。因此对于大多数情况下的自定义view manager来说,直接创建一个`NativeRenderObjectView`即可。 +>`NativeRenderView`会根据`HippyShadowView`的映射结果构建真正的View视图。因此对于大多数情况下的自定义view manager来说,直接创建一个`HippyShadowView`即可。 -`NativeRenderImpl`将调用[NativeRenderMyViewManager view]方法去创建一个真正的view,用户需要实现这个方法并返回自己所需要的`NativeRenderMyView`。 +`HippyUIManager`将调用[NativeRenderMyViewManager view]方法去创建一个真正的view,用户需要实现这个方法并返回自己所需要的`NativeRenderMyView`。 到此,一个简单的`NativeRenderMyViewManager`与`NativeRenderMyView`创建完成。 diff --git a/docs/development/native-integration.md b/docs/development/native-integration.md index 0604d28112b..b8bda19ed27 100644 --- a/docs/development/native-integration.md +++ b/docs/development/native-integration.md @@ -236,7 +236,7 @@ HippyBridge中有些必须属性,需要调用方设置。如果不设置,将 @property(nonatomic, assign)std::weak_ptr VFSUriLoader; //添加Image -- (void)addImageProviderClass:(Class)cls; +- (void)addImageProviderClass:(Class)cls; //调用方代码 _bridge.moduleName = @"Demo" @@ -253,7 +253,7 @@ demoLoader->RegisterConvenientUriHandler(@"hpfile", fileHandler); _bridge.VFSUriLoader = demoLoader; //使用Hippy默认的vfs //使用系统默认的image解码器 -[_bridge addImageProviderClass:[HPDefaultImageProvider class]]; +[_bridge addImageProviderClass:[HippyDefaultImageProvider class]]; ``` @@ -279,7 +279,7 @@ auto nativeRenderManager = std::make_shared(); nativeRenderManager->SetDomManager(domManager); //设置Image解码类 -nativeRenderManager->AddImageProviderClass([HPDefaultImageProvider class]); +nativeRenderManager->AddImageProviderClass([HippyDefaultImageProvider class]); //设置额外的自定义组件 nativeRenderManager->RegisterExtraComponent(_extraComponents); //设置vfs系统 diff --git a/framework/examples/ios-demo/HippyDemo/HippyConvenientBridge.h b/framework/examples/ios-demo/HippyDemo/HippyConvenientBridge.h deleted file mode 100644 index 9f118269048..00000000000 --- a/framework/examples/ios-demo/HippyDemo/HippyConvenientBridge.h +++ /dev/null @@ -1,87 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * Hippy available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import -#import - -#import "HippyModulesSetup.h" - -NS_ASSUME_NONNULL_BEGIN - -typedef void(^_Nullable HippyBridgeBundleLoadCompletion)(NSURL *_Nullable, NSError *_Nullable); - -@protocol HippyBridgeDelegate, HPImageProviderProtocol, HippyMethodInterceptorProtocol; - -/** - * Convenient class for adative 2.0 interface - */ -@interface HippyConvenientBridge : NSObject - -@property(nonatomic, readonly) HippyBridge *bridge; -//Properties that must be set -@property(nonatomic, copy) NSString *moduleName; -@property(nonatomic, copy) NSString *contextName; -@property(nonatomic, strong) NSURL *sandboxDirectory; - -//Optional properties -@property(nonatomic, weak) id methodInterceptor; -@property(nonatomic, readonly, weak) id delegate; - -//Methods that must be called -- (instancetype)initWithDelegate:(id _Nullable)delegate - moduleProvider:(HippyBridgeModuleProviderBlock _Nullable)block - extraComponents:(NSArray * _Nullable)extraComponents - launchOptions:(NSDictionary * _Nullable)launchOptions - engineKey:(NSString *_Nullable)engineKey; - -- (void)loadBundleURL:(NSURL *)bundleURL completion:(HippyBridgeBundleLoadCompletion)completion; - -//Load debug url specified by [HippyBundleURLProvider sharedInstance] -//and `_debugMode` variable in HippyBridge will be set to YES -- (void)loadDebugBundleCompletion:(HippyBridgeBundleLoadCompletion)completion; - -- (void)setRootView:(UIView *)rootView; - -- (void)resetRootSize:(CGSize)size; - -- (void)loadInstanceForRootViewTag:(NSNumber *)tag props:(NSDictionary *)props; - -- (void)unloadRootViewByTag:(NSNumber *)tag; - -- (void)addExtraComponents:(NSArray *)components; - -- (void)setInspectable:(BOOL)inspectable; - -//Optianl properties set -- (void)addImageProviderClass:(Class)cls; - -#pragma mark event -- (void)sendEvent:(NSString *)eventName params:(NSDictionary *_Nullable)params; - -#pragma mark snap shot -- (NSData *)snapShotData; - -- (void)setSnapShotData:(NSData *)data; - -@end - -NS_ASSUME_NONNULL_END diff --git a/framework/examples/ios-demo/HippyDemo/HippyConvenientBridge.mm b/framework/examples/ios-demo/HippyDemo/HippyConvenientBridge.mm deleted file mode 100644 index f18342484a1..00000000000 --- a/framework/examples/ios-demo/HippyDemo/HippyConvenientBridge.mm +++ /dev/null @@ -1,284 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * Hippy available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import "HippyConvenientBridge.h" - -#import "HippyBridge.h" -#import "HippyBundleURLProvider.h" -#import "HippyJSEnginesMapper.h" -#import "HippyFileHandler.h" -#import "HippyMethodInterceptorProtocol.h" -#import "NativeRenderManager.h" -#import "HPDefaultImageProvider.h" -#import "HPLog.h" -#import "UIView+NativeRender.h" -#import "VFSUriLoader.h" - -#include -#include - -#include "dom/root_node.h" - -@interface HippyConvenientBridge () { - HippyBridge *_bridge; - std::shared_ptr _nativeRenderManager; - std::shared_ptr _rootNode; - std::shared_ptr _demoLoader; - NSString *_engineKey; - NSArray *_extraComponents; -} - -@end - -@implementation HippyConvenientBridge - -@synthesize bridge = _bridge; - -- (instancetype)initWithDelegate:(id _Nullable)delegate - moduleProvider:(HippyBridgeModuleProviderBlock _Nullable)block - extraComponents:(NSArray * _Nullable)extraComponents - launchOptions:(NSDictionary * _Nullable)launchOptions - engineKey:(NSString *_Nullable)engineKey { - self = [super init]; - if (self) { - _delegate = delegate; - _bridge = [[HippyBridge alloc] initWithDelegate:self moduleProvider:block - launchOptions:launchOptions engineKey:engineKey]; - _engineKey = engineKey; - _extraComponents = extraComponents; - [_bridge addImageProviderClass:[HPDefaultImageProvider class]]; - [_bridge setVFSUriLoader:[self URILoader]]; - [self setUpNativeRenderManager]; - } - return self; -} - -- (NSString *)engineKey { - return _engineKey ?: [NSString stringWithFormat:@"%p", self]; -} - -- (void)setUpNativeRenderManager { - auto engineResource = [[HippyJSEnginesMapper defaultInstance] JSEngineResourceForKey:[self engineKey]]; - auto domManager = engineResource->GetDomManager(); - //Create NativeRenderManager - _nativeRenderManager = std::make_shared(); - _nativeRenderManager->Initialize(); - //set dom manager - _nativeRenderManager->SetDomManager(domManager); - //set image provider for native render manager - _nativeRenderManager->AddImageProviderClass([HPDefaultImageProvider class]); - _nativeRenderManager->RegisterExtraComponent(_extraComponents); - _nativeRenderManager->SetVFSUriLoader([self URILoader]); - _bridge.renderManager = _nativeRenderManager; -} - -- (std::shared_ptr)URILoader { - if (!_demoLoader) { - auto demoHandler = std::make_shared(); - _demoLoader = std::make_shared(); - _demoLoader->PushDefaultHandler(demoHandler); - _demoLoader->AddConvenientDefaultHandler(demoHandler); - auto fileHandler = std::make_shared(_bridge); - _demoLoader->RegisterConvenientUriHandler(@"hpfile", fileHandler); - } - return _demoLoader; -} - -- (void)setModuleName:(NSString *)moduleName { - _bridge.moduleName = moduleName; -} - -- (NSString *)moduleName { - return _bridge.moduleName; -} - -- (void)setContextName:(NSString *)contextName { - _bridge.contextName = contextName; -} - -- (NSString *)contextName { - return _bridge.contextName; -} - -- (void)setSandboxDirectory:(NSURL *)sandboxDirectory { - _bridge.sandboxDirectory = sandboxDirectory; -} - -- (NSURL *)sandboxDirectory { - return _bridge.sandboxDirectory; -} - -- (void)setMethodInterceptor:(id)methodInterceptor { - _bridge.methodInterceptor = methodInterceptor; -} - -- (id)methodInterceptor { - return _bridge.methodInterceptor; -} - -- (void)loadBundleURL:(NSURL *)bundleURL completion:(HippyBridgeBundleLoadCompletion)completion { - [_bridge loadBundleURL:bundleURL completion:completion]; -} - -- (void)loadDebugBundleCompletion:(HippyBridgeBundleLoadCompletion)completion { - _bridge.debugMode = YES; - NSString *bundleStr = [HippyBundleURLProvider sharedInstance].bundleURLString; - NSURL *bundleUrl = [NSURL URLWithString:bundleStr]; - [_bridge loadBundleURL:bundleUrl completion:completion]; -} - -- (void)setRootView:(UIView *)rootView { - auto engineResource = [[HippyJSEnginesMapper defaultInstance] JSEngineResourceForKey:[self engineKey]]; - auto domManager = engineResource->GetDomManager(); - NSNumber *rootTag = [rootView componentTag]; - //Create a RootNode instance with a root tag - _rootNode = std::make_shared([rootTag unsignedIntValue]); - //Set RootNode for AnimationManager in RootNode - _rootNode->GetAnimationManager()->SetRootNode(_rootNode); - //Set DomManager for RootNode - _rootNode->SetDomManager(domManager); - //Set screen scale factor and size for Layout system in RooNode - _rootNode->GetLayoutNode()->SetScaleFactor([UIScreen mainScreen].scale); - _rootNode->SetRootSize(rootView.frame.size.width, rootView.frame.size.height); - _rootNode->SetRootOrigin(rootView.frame.origin.x, rootView.frame.origin.y); - - //set rendermanager for dommanager - if (!domManager->GetRenderManager().lock()) { - domManager->SetRenderManager(_nativeRenderManager); - } - //bind rootview and root node - _nativeRenderManager->RegisterRootView(rootView, _rootNode); - - __weak HippyBridge *weakBridge = _bridge; - auto cb = [weakBridge](int32_t tag, NSDictionary *params){ - HippyBridge *strongBridge = weakBridge; - if (strongBridge) { - [strongBridge rootViewSizeChangedEvent:@(tag) params:params]; - } - }; - _nativeRenderManager->SetRootViewSizeChangedEvent(cb); - //setup necessary params for bridge - [_bridge setupDomManager:domManager rootNode:_rootNode]; -} - -- (void)resetRootSize:(CGSize)size { - auto engineResource = [[HippyJSEnginesMapper defaultInstance] JSEngineResourceForKey:[self engineKey]]; - std::weak_ptr rootNode = _rootNode; - auto domManager = engineResource->GetDomManager(); - std::weak_ptr weakDomManager = domManager; - std::vector> ops = {[rootNode, weakDomManager, size](){ - auto strongRootNode = rootNode.lock(); - auto strongDomManager = weakDomManager.lock(); - if (strongRootNode && strongDomManager) { - strongRootNode->SetRootSize(size.width, size.height); - strongDomManager->DoLayout(strongRootNode); - strongDomManager->EndBatch(strongRootNode); - } - }}; - domManager->PostTask(hippy::dom::Scene(std::move(ops))); -} - -- (void)addExtraComponents:(NSArray *)components { - _nativeRenderManager->RegisterExtraComponent(components); -} - -- (void)loadInstanceForRootViewTag:(NSNumber *)tag props:(NSDictionary *)props { - [_bridge loadInstanceForRootView:tag withProperties:props]; -} - -- (void)unloadRootViewByTag:(NSNumber *)tag { - [_bridge unloadInstanceForRootView:tag]; - _nativeRenderManager->UnregisterRootView([tag intValue]); - if (_rootNode) { - _rootNode->ReleaseResources(); - _rootNode = nullptr; - } -} - -- (void)addImageProviderClass:(Class)cls { - [_bridge addImageProviderClass:cls]; - _nativeRenderManager->AddImageProviderClass([HPDefaultImageProvider class]); -} - -- (void)setInspectable:(BOOL)inspectable { - [_bridge setInspectable:inspectable]; -} - -#pragma mark HippyBridge Delegate - -static BOOL SelectorBelongsToProtocol(SEL selector, Protocol *protocol) { - if (!selector || !protocol) { - return NO; - } - struct objc_method_description methodDesc = protocol_getMethodDescription(protocol, selector, NO, YES); - return selector == methodDesc.name; -} - -- (BOOL)respondsToSelector:(SEL)aSelector { - if (aSelector == @selector(invalidateForReason:bridge:)) { - return YES; - } - return [_delegate respondsToSelector:aSelector]; -} - -- (id)forwardingTargetForSelector:(SEL)aSelector { - if (SelectorBelongsToProtocol(aSelector, @protocol(HippyBridgeDelegate))) { - return _delegate; - } - return [super forwardingTargetForSelector:aSelector]; -} - -- (void)invalidateForReason:(HPInvalidateReason)reason bridge:(HippyBridge *)bridge { - [_nativeRenderManager->rootViews() enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { - if ([obj respondsToSelector:@selector(invalidate)]) { - [obj performSelector:@selector(invalidate)]; - } - [self unloadRootViewByTag:[obj componentTag]]; - }]; - if ([_delegate respondsToSelector:@selector(invalidateForReason:bridge:)]) { - [_delegate invalidateForReason:reason bridge:bridge]; - } -} - -- (void)sendEvent:(NSString *)eventName params:(NSDictionary *_Nullable)params { - [self.bridge sendEvent:eventName params:params]; -} - -- (NSData *)snapShotData { - return [_bridge snapShotData]; -} - -- (void)setSnapShotData:(NSData *)data { - [_bridge setSnapShotData:data]; -} - -- (void)dealloc { - if (_demoLoader) { - _demoLoader->Terminate(); - } - if (_rootNode) { - _nativeRenderManager->RemoveVSyncEventListener(_rootNode); - _rootNode->ReleaseResources(); - } -} - -@end diff --git a/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCache.h b/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCache.h index 4d96db45398..3aa05d6be61 100644 --- a/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCache.h +++ b/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCache.h @@ -34,7 +34,7 @@ typedef NS_ENUM(NSUInteger, RenderType) { RenderTypeNative, }; -@class HippyConvenientBridge; +@class HippyBridge, HippyRootView; @class HippyPageCacheManager, HippyPageCache; @protocol HippyPageCacheManagerObserverProtocol @@ -55,8 +55,8 @@ typedef NS_ENUM(NSUInteger, RenderType) { @interface HippyPageCache : NSObject -@property(nonatomic, strong) HippyConvenientBridge *convenientBridge; -@property(nonatomic, strong) UIView *rootView; +@property(nonatomic, strong) HippyBridge *hippyBridge; +@property(nonatomic, strong) HippyRootView *rootView; @property(nonatomic, strong, nullable) UIImage *snapshot; @property(nonatomic, assign) DriverType driverType; diff --git a/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCache.m b/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCache.m index 1456217141e..ab32189dbf7 100644 --- a/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCache.m +++ b/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCache.m @@ -21,6 +21,7 @@ */ #import "HippyPageCache.h" +#import @implementation HippyPageCache @@ -28,11 +29,11 @@ - (BOOL)isEqual:(id)object { if (![object isKindOfClass:[self class]]) { return NO; } - return _convenientBridge == [object convenientBridge]; + return _hippyBridge == [object hippyBridge]; } - (NSUInteger)hash { - return [(NSObject *)_convenientBridge hash] + [_rootView hash]; + return [(NSObject *)_hippyBridge hash] + [_rootView hash]; } @end diff --git a/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCacheContainerView.m b/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCacheContainerView.m index 2f61cde46e2..068a4796c54 100644 --- a/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCacheContainerView.m +++ b/framework/examples/ios-demo/HippyDemo/PageManager/HippyPageCacheContainerView.m @@ -24,7 +24,7 @@ #import "HippyPageCacheContainerView.h" #import "HippyPageCacheView.h" #import "HippyPageCache.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" @interface HippyPageCacheContainerView () { __weak UIView *_lastPageCacheView; //never removed from superview diff --git a/framework/examples/ios-demo/HippyDemo/PageManager/PageCreationViewController.m b/framework/examples/ios-demo/HippyDemo/PageManager/PageCreationViewController.m index 1b97b430f00..52cf8226b02 100644 --- a/framework/examples/ios-demo/HippyDemo/PageManager/PageCreationViewController.m +++ b/framework/examples/ios-demo/HippyDemo/PageManager/PageCreationViewController.m @@ -24,7 +24,7 @@ #import "PageCreationCell.h" #import "DebugCell.h" #import "IconUtils.h" -#import "NativeRenderViewController.h" +#import "HippyDemoViewController.h" #import "HippyBundleURLProvider.h" #import "UIViewController+Title.h" @@ -262,7 +262,7 @@ - (void)createDemoAction { NSString *debugString = [cell2 debugURLString]; debugURL = [NSURL URLWithString:debugString]; } - NativeRenderViewController *vc = [[NativeRenderViewController alloc] initWithDriverType:driverType renderType:renderType debugURL:debugURL isDebugMode:_debugMode]; + HippyDemoViewController *vc = [[HippyDemoViewController alloc] initWithDriverType:driverType renderType:renderType debugURL:debugURL isDebugMode:_debugMode]; NSMutableArray<__kindof UIViewController *> *viewControllers = [[self.navigationController viewControllers] mutableCopy]; [viewControllers removeLastObject]; [viewControllers addObject:vc]; diff --git a/framework/examples/ios-demo/HippyDemo/PageManager/PageManagerViewController.m b/framework/examples/ios-demo/HippyDemo/PageManager/PageManagerViewController.m index fbe1a8882cb..a18810c06c8 100644 --- a/framework/examples/ios-demo/HippyDemo/PageManager/PageManagerViewController.m +++ b/framework/examples/ios-demo/HippyDemo/PageManager/PageManagerViewController.m @@ -24,7 +24,7 @@ #import "HippyPageCache.h" #import "PageCreationViewController.h" #import "HippyPageCacheContainerView.h" -#import "NativeRenderViewController.h" +#import "HippyDemoViewController.h" #import "UIViewController+Title.h" @interface PageManagerViewController () { @@ -85,7 +85,7 @@ - (void)deleteAction:(HippyPageCache *)pageCache { } - (void)clickAction:(HippyPageCache *)pageCache { - NativeRenderViewController *vc = [[NativeRenderViewController alloc] initWithPageCache:pageCache]; + HippyDemoViewController *vc = [[HippyDemoViewController alloc] initWithPageCache:pageCache]; self.navigationItem.backButtonTitle = @" "; [self.navigationController pushViewController:vc animated:YES]; } diff --git a/framework/examples/ios-demo/HippyDemo/RenderPage/NativeRenderViewController.h b/framework/examples/ios-demo/HippyDemo/RenderPage/HippyDemoViewController.h similarity index 95% rename from framework/examples/ios-demo/HippyDemo/RenderPage/NativeRenderViewController.h rename to framework/examples/ios-demo/HippyDemo/RenderPage/HippyDemoViewController.h index 306b321b198..9abca85f258 100644 --- a/framework/examples/ios-demo/HippyDemo/RenderPage/NativeRenderViewController.h +++ b/framework/examples/ios-demo/HippyDemo/RenderPage/HippyDemoViewController.h @@ -28,7 +28,7 @@ NS_ASSUME_NONNULL_BEGIN @class HippyPageCache; -@interface NativeRenderViewController : DemoBaseViewController +@interface HippyDemoViewController : DemoBaseViewController @property(nonatomic, assign, readonly) DriverType driverType; @property(nonatomic, assign, readonly) RenderType renderType; diff --git a/framework/examples/ios-demo/HippyDemo/RenderPage/NativeRenderViewController.mm b/framework/examples/ios-demo/HippyDemo/RenderPage/HippyDemoViewController.mm similarity index 56% rename from framework/examples/ios-demo/HippyDemo/RenderPage/NativeRenderViewController.mm rename to framework/examples/ios-demo/HippyDemo/RenderPage/HippyDemoViewController.mm index f3cc7d97c94..d4a82cc453c 100644 --- a/framework/examples/ios-demo/HippyDemo/RenderPage/NativeRenderViewController.mm +++ b/framework/examples/ios-demo/HippyDemo/RenderPage/HippyDemoViewController.mm @@ -20,33 +20,35 @@ * limitations under the License. */ -#import "NativeRenderViewController.h" -#import "HPLog.h" -#import "HippyBridge.h" -#import "HippyConvenientBridge.h" +#import "HippyDemoViewController.h" +#import "UIViewController+Title.h" +#import "HippyPageCache.h" #import "DemoConfigs.h" -#import "HPAsserts.h" + #import "HippyMethodInterceptorProtocol.h" -#import "NativeRenderRootView.h" -#import "UIView+NativeRender.h" -#import "HippyPageCache.h" -#import "UIViewController+Title.h" + +#import +#import +#import +#import +#import static NSString *const engineKey = @"Demo"; -@interface NativeRenderViewController () { +@interface HippyDemoViewController () { DriverType _driverType; RenderType _renderType; BOOL _isDebugMode; - HippyConvenientBridge *_convenientBridge; NSURL *_debugURL; - UIView *_rootView; + + HippyBridge *_hippyBridge; + HippyRootView *_hippyRootView; BOOL _fromCache; } @end -@implementation NativeRenderViewController +@implementation HippyDemoViewController - (instancetype)initWithDriverType:(DriverType)driverType renderType:(RenderType)renderType @@ -69,94 +71,130 @@ - (instancetype)initWithPageCache:(HippyPageCache *)pageCache { _renderType = pageCache.renderType; _debugURL = pageCache.debugURL; _isDebugMode = pageCache.isDebugMode; - _rootView = pageCache.rootView; - [_rootView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:NULL]; - _convenientBridge = pageCache.convenientBridge; + _hippyRootView = pageCache.rootView; + [_hippyRootView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:NULL]; + _hippyBridge = pageCache.hippyBridge; _fromCache = YES; } return self; } +- (void)dealloc { + [_hippyRootView removeObserver:self forKeyPath:@"frame"]; + [[HippyPageCacheManager defaultPageCacheManager] addPageCache:[self toPageCache]]; + NSLog(@"%@ dealloc", self.class); +} + - (void)viewDidLoad { [super viewDidLoad]; - // Do any additional setup after loading the view. [self setNavigationAreaBackground:[UIColor whiteColor]]; [self setNavigationItemTitle:@"Demo"]; + [self registerLogFunction]; + if (_fromCache) { [self runHippyCache]; - } - else { + } else { [self runHippyDemo]; } } - (void)registerLogFunction { - HPSetLogFunction(^(HPLogLevel level, NSString *fileName, NSNumber *lineNumber, - NSString *message, NSArray *stack, NSDictionary *userInfo) { - if (HPLogLevelError <= level && userInfo) { - } + HippySetLogFunction(^(HippyLogLevel level, HippyLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { NSLog(@"hippy says:%@ in file %@ at line %@", message, fileName, lineNumber); }); } - (void)runHippyCache { - _rootView.frame = self.contentAreaView.bounds; - [self.contentAreaView addSubview:_rootView]; + _hippyRootView.frame = self.contentAreaView.bounds; + [self.contentAreaView addSubview:_hippyRootView]; } - (void)runHippyDemo { NSDictionary *launchOptions = @{@"EnableTurbo": @(DEMO_ENABLE_TURBO), @"DebugMode": @(_isDebugMode)}; - NSString *key = [NSString stringWithFormat:@"%@_%u", engineKey, arc4random()]; - - _convenientBridge = [[HippyConvenientBridge alloc] initWithDelegate:self - moduleProvider:nil - extraComponents:nil - launchOptions:launchOptions - engineKey:key]; - [_convenientBridge setInspectable:YES]; - _convenientBridge.contextName = key; - _convenientBridge.moduleName = @"Demo"; - _convenientBridge.methodInterceptor = self; - [self mountConnector:_convenientBridge]; + NSString *uniqueEngineKey = [NSString stringWithFormat:@"%@_%u", engineKey, arc4random()]; + + _hippyBridge = [[HippyBridge alloc] initWithDelegate:self + moduleProvider:nil + launchOptions:launchOptions + executorKey:uniqueEngineKey]; + _hippyBridge.contextName = uniqueEngineKey; + _hippyBridge.moduleName = @"Demo"; + _hippyBridge.methodInterceptor = self; + + [_hippyBridge setInspectable:YES]; + + [self mountConnector:_hippyBridge]; } -- (void)mountConnector:(HippyConvenientBridge *)convenientBridge { +- (void)mountConnector:(HippyBridge *)hippyBridge { BOOL isSimulator = NO; #if TARGET_IPHONE_SIMULATOR - isSimulator = YES; + isSimulator = YES; #endif - NativeRenderRootView *rootView = [[NativeRenderRootView alloc] initWithFrame:self.contentAreaView.bounds]; - rootView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; - [convenientBridge setRootView:rootView]; - NSNumber *rootTag = [rootView componentTag]; + +#if USE_NEW_LOAD + HippyRootView *rootView = [[HippyRootView alloc] initWithBridge:hippyBridge + moduleName:@"Demo" + initialProperties:@{@"isSimulator": @(isSimulator)} + delegate:self]; + if (_isDebugMode) { - convenientBridge.sandboxDirectory = [_debugURL URLByDeletingLastPathComponent]; - [convenientBridge loadBundleURL:_debugURL completion:^(NSURL * _Nullable, NSError * _Nullable) { - [convenientBridge loadInstanceForRootViewTag:rootTag props:@{@"isSimulator": @(isSimulator)}]; + hippyBridge.sandboxDirectory = [_debugURL URLByDeletingLastPathComponent]; + [hippyBridge loadBundleURL:_debugURL completion:^(NSURL * _Nullable, NSError * _Nullable) { + [rootView runHippyApplication]; }]; - } - else { + } else { NSURL *vendorBundleURL = [self vendorBundleURL]; - [convenientBridge loadBundleURL:vendorBundleURL completion:^(NSURL * _Nullable, NSError * _Nullable) { + [hippyBridge loadBundleURL:vendorBundleURL completion:^(NSURL * _Nullable, NSError * _Nullable) { NSLog(@"url %@ load finish", vendorBundleURL); }]; NSURL *indexBundleURL = [self indexBundleURL]; - convenientBridge.sandboxDirectory = [indexBundleURL URLByDeletingLastPathComponent]; - [convenientBridge loadBundleURL:indexBundleURL completion:^(NSURL * _Nullable, NSError * _Nullable) { + hippyBridge.sandboxDirectory = [indexBundleURL URLByDeletingLastPathComponent]; + [hippyBridge loadBundleURL:indexBundleURL completion:^(NSURL * _Nullable, NSError * _Nullable) { NSLog(@"url %@ load finish", indexBundleURL); - [convenientBridge loadInstanceForRootViewTag:rootTag props:@{@"isSimulator": @(isSimulator)}]; + [rootView runHippyApplication]; }]; } + +#else + HippyRootView *rootView = nil; + + if (_isDebugMode) { + hippyBridge.sandboxDirectory = [_debugURL URLByDeletingLastPathComponent]; + rootView = [[HippyRootView alloc] initWithBridge:hippyBridge + businessURL:_debugURL + moduleName:@"Demo" + initialProperties:@{@"isSimulator": @(isSimulator)} + delegate:self]; + } else { + NSURL *vendorBundleURL = [self vendorBundleURL]; + NSURL *indexBundleURL = [self indexBundleURL]; + [hippyBridge loadBundleURL:vendorBundleURL completion:^(NSURL * _Nullable, NSError * _Nullable) { + NSLog(@"url %@ load finish", vendorBundleURL); + }]; + hippyBridge.sandboxDirectory = [indexBundleURL URLByDeletingLastPathComponent]; + rootView = [[HippyRootView alloc] initWithBridge:hippyBridge + businessURL:indexBundleURL + moduleName:@"Demo" + initialProperties:@{@"isSimulator": @(isSimulator)} + delegate:self]; + } + +#endif + + rootView.frame = self.contentAreaView.bounds; + rootView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; + [self.contentAreaView addSubview:rootView]; - if (_rootView) { - [_rootView removeObserver:self forKeyPath:@"frame" context:NULL]; + if (_hippyRootView) { + [_hippyRootView removeObserver:self forKeyPath:@"frame" context:NULL]; } [rootView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL]; - _rootView = rootView; + _hippyRootView = rootView; } - (void)observeValueForKeyPath:(NSString *)keyPath @@ -164,18 +202,18 @@ - (void)observeValueForKeyPath:(NSString *)keyPath change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"frame"] && - object == _rootView) { + object == _hippyRootView) { CGRect frame = [change[NSKeyValueChangeNewKey] CGRectValue]; CGRect oldFrame = [change[NSKeyValueChangeOldKey] CGRectValue]; if (!CGRectEqualToRect(frame, oldFrame)) { - [_convenientBridge resetRootSize:frame.size]; + [_hippyBridge resetRootSize:frame.size]; } } } - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; - _rootView.frame = self.contentAreaView.bounds; + _hippyRootView.frame = self.contentAreaView.bounds; } - (NSURL *)vendorBundleURL { @@ -217,46 +255,23 @@ - (BOOL)isDebugMode { } - (void)reload:(HippyBridge *)bridge { - [self mountConnector:_convenientBridge]; + [self mountConnector:_hippyBridge]; } - (void)removeRootView:(NSNumber *)rootTag bridge:(HippyBridge *)bridge { [[[self.contentAreaView subviews] firstObject] removeFromSuperview]; } -- (BOOL)shouldStartInspector:(HippyBridge *)bridge { - return bridge.debugMode; -} - -- (BOOL)shouldInvokeWithModuleName:(NSString *)moduleName - methodName:(NSString *)methodName - arguments:(NSArray> *)arguments - argumentsValues:(NSArray *)argumentsValue - containCallback:(BOOL)containCallback { - HPAssert(moduleName, @"module name must not be null"); - HPAssert(methodName, @"method name must not be null"); - return YES; -} - -- (BOOL)shouldCallbackBeInvokedWithModuleName:(NSString *)moduleName - methodName:(NSString *)methodName - callbackId:(NSNumber *)cbId - arguments:(id)arguments { - HPAssert(moduleName, @"module name must not be null"); - HPAssert(methodName, @"method name must not be null"); - return YES; -} - - (HippyPageCache *)toPageCache { HippyPageCache *pageCache = [[HippyPageCache alloc] init]; - pageCache.convenientBridge = _convenientBridge; - pageCache.rootView = _rootView; + pageCache.hippyBridge = _hippyBridge; + pageCache.rootView = _hippyRootView; pageCache.driverType = _driverType; pageCache.renderType = _renderType; pageCache.debugURL = _debugURL; pageCache.debugMode = _isDebugMode; - UIGraphicsBeginImageContextWithOptions(_rootView.bounds.size, NO, [UIScreen mainScreen].scale); - [_rootView drawViewHierarchyInRect:_rootView.bounds afterScreenUpdates:YES]; + UIGraphicsBeginImageContextWithOptions(_hippyRootView.bounds.size, NO, [UIScreen mainScreen].scale); + [_hippyRootView drawViewHierarchyInRect:_hippyRootView.bounds afterScreenUpdates:YES]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); pageCache.snapshot = image; @@ -271,13 +286,33 @@ - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAllButUpsideDown; } -- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { - return UIInterfaceOrientationPortrait; + +#pragma mark - HippyBridgeDelegate + +- (BOOL)shouldStartInspector:(HippyBridge *)bridge { + return bridge.debugMode; } -- (void)dealloc { - [_rootView removeObserver:self forKeyPath:@"frame"]; - [[HippyPageCacheManager defaultPageCacheManager] addPageCache:[self toPageCache]]; + +#pragma mark - HippyMethodInterceptorProtocol + +- (BOOL)shouldInvokeWithModuleName:(NSString *)moduleName + methodName:(NSString *)methodName + arguments:(NSArray> *)arguments + argumentsValues:(NSArray *)argumentsValue + containCallback:(BOOL)containCallback { + HippyAssert(moduleName, @"module name must not be null"); + HippyAssert(methodName, @"method name must not be null"); + return YES; +} + +- (BOOL)shouldCallbackBeInvokedWithModuleName:(NSString *)moduleName + methodName:(NSString *)methodName + callbackId:(NSNumber *)cbId + arguments:(id)arguments { + HippyAssert(moduleName, @"module name must not be null"); + HippyAssert(methodName, @"method name must not be null"); + return YES; } @end diff --git a/framework/examples/ios-demo/HippyDemo/TestModule.mm b/framework/examples/ios-demo/HippyDemo/TestModule.mm index b97d09d3431..d76134a9089 100644 --- a/framework/examples/ios-demo/HippyDemo/TestModule.mm +++ b/framework/examples/ios-demo/HippyDemo/TestModule.mm @@ -25,19 +25,18 @@ #import "HippyBundleURLProvider.h" #import "HippyDemoLoader.h" #import "HippyJSEnginesMapper.h" -#import "NativeRenderRootView.h" -#import "UIView+NativeRender.h" -#import "HippyConvenientBridge.h" -#import "HPLog.h" +#import "HippyRootView.h" +#import "UIView+Hippy.h" +#import "HippyLog.h" #import "HippyRedBox.h" #import "DemoConfigs.h" #import "HippyMethodInterceptorProtocol.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" static NSString *const engineKey = @"Demo"; -@interface TestModule () { - HippyConvenientBridge *_connector; +@interface TestModule () { + HippyBridge *_connector; } @end @@ -69,7 +68,10 @@ - (void)runCommonDemo:(nonnull NSString *)bundleUrl { NSURL *url = [NSURL URLWithString:bundleUrl]; NSDictionary *launchOptions = @{@"EnableTurbo": @(DEMO_ENABLE_TURBO), @"DebugMode": @(YES), @"DebugURL": url}; NSURL *sandboxDirectory = [url URLByDeletingLastPathComponent]; - _connector = [[HippyConvenientBridge alloc] initWithDelegate:self moduleProvider:nil extraComponents:nil launchOptions:launchOptions engineKey:engineKey]; + _connector = [[HippyBridge alloc] initWithDelegate:self + moduleProvider:nil + launchOptions:launchOptions + executorKey:engineKey]; [_connector setInspectable:YES]; //set custom vfs loader _connector.sandboxDirectory = sandboxDirectory; @@ -81,7 +83,7 @@ - (void)runCommonDemo:(nonnull NSString *)bundleUrl { [rootViewController presentViewController:vc animated:YES completion:NULL]; } -- (void)mountConnector:(HippyConvenientBridge *)connector onView:(UIView *)view { +- (void)mountConnector:(HippyBridge *)connector onView:(UIView *)view { BOOL isSimulator = NO; #if TARGET_IPHONE_SIMULATOR isSimulator = YES; @@ -90,13 +92,13 @@ - (void)mountConnector:(HippyConvenientBridge *)connector onView:(UIView *)view NSString *bundleStr = [HippyBundleURLProvider sharedInstance].bundleURLString; NSURL *bundleUrl = [NSURL URLWithString:bundleStr]; - NativeRenderRootView *rootView = [[NativeRenderRootView alloc] initWithFrame:view.bounds]; + HippyRootView *rootView = [[HippyRootView alloc] initWithFrame:view.bounds]; rootView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; [_connector setRootView:rootView]; - NSNumber *rootTag = [rootView componentTag]; + NSNumber *rootTag = [rootView hippyTag]; [connector loadBundleURL:bundleUrl completion:^(NSURL * _Nullable, NSError * _Nullable) { NSLog(@"url %@ load finish", bundleStr); - [connector loadInstanceForRootViewTag:rootTag props:@{@"isSimulator": @(isSimulator)}]; + [connector loadInstanceForRootView:rootTag withProperties:@{@"isSimulator": @(isSimulator)}]; }]; [view addSubview:rootView]; } @@ -120,14 +122,14 @@ - (BOOL)shouldStartInspector:(HippyBridge *)bridge { } - (BOOL)shouldInvokeWithModuleName:(NSString *)moduleName methodName:(NSString *)methodName arguments:(NSArray> *)arguments argumentsValues:(NSArray *)argumentsValue containCallback:(BOOL)containCallback { - HPAssert(moduleName, @"module name must not be null"); - HPAssert(methodName, @"method name must not be null"); + HippyAssert(moduleName, @"module name must not be null"); + HippyAssert(methodName, @"method name must not be null"); return YES; } - (BOOL)shouldCallbackBeInvokedWithModuleName:(NSString *)moduleName methodName:(NSString *)methodName callbackId:(NSNumber *)cbId arguments:(id)arguments { - HPAssert(moduleName, @"module name must not be null"); - HPAssert(methodName, @"method name must not be null"); + HippyAssert(moduleName, @"module name must not be null"); + HippyAssert(methodName, @"method name must not be null"); return YES; } @end diff --git a/framework/examples/ios-demo/HippyDemo/myview/MyViewManager.h b/framework/examples/ios-demo/HippyDemo/myview/MyViewManager.h index 94d32ac8f93..5383ee26109 100644 --- a/framework/examples/ios-demo/HippyDemo/myview/MyViewManager.h +++ b/framework/examples/ios-demo/HippyDemo/myview/MyViewManager.h @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" NS_ASSUME_NONNULL_BEGIN -@interface MyViewManager : NativeRenderViewManager +@interface MyViewManager : HippyViewManager @end diff --git a/framework/examples/ios-demo/HippyDemo/myview/MyViewManager.mm b/framework/examples/ios-demo/HippyDemo/myview/MyViewManager.mm index 0f2ef7bbd72..6e39b85f4e4 100644 --- a/framework/examples/ios-demo/HippyDemo/myview/MyViewManager.mm +++ b/framework/examples/ios-demo/HippyDemo/myview/MyViewManager.mm @@ -22,21 +22,21 @@ #import "MyViewManager.h" #import "MyView.h" -#import "UIView+NativeRender.h" -#import "NativeRenderImpl.h" +#import "UIView+Hippy.h" +#import "HippyUIManager.h" @implementation MyViewManager -NATIVE_RENDER_EXPORT_VIEW(MyView) +HIPPY_EXPORT_MODULE(MyView) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(text, NSString) +HIPPY_EXPORT_VIEW_PROPERTY(text, NSString) -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(changeColor:(nonnull NSNumber *)reactTag - color:(NSString *)color) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ +HIPPY_EXPORT_METHOD(changeColor:(nonnull NSNumber *)reactTag + color:(NSString *)color) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ UIView *view = viewRegistry[reactTag]; if (view == nil || ![view isKindOfClass:[MyView class]]) { - HPLogError(@"tried to setPage: on an error viewPager %@ " + HippyLogError(@"tried to setPage: on an error viewPager %@ " "with tag #%@", view, reactTag); } [(MyView *)view setBackgroundColor:[self colorWithHexString:color alpha:1] ]; diff --git a/framework/examples/ios-demo/HippyDemo/turbomodule/TurboConfig.m b/framework/examples/ios-demo/HippyDemo/turbomodule/TurboConfig.m index d9ef2bc6869..088a7d96e81 100644 --- a/framework/examples/ios-demo/HippyDemo/turbomodule/TurboConfig.m +++ b/framework/examples/ios-demo/HippyDemo/turbomodule/TurboConfig.m @@ -22,7 +22,7 @@ #import "TurboConfig.h" #import "HippyDefines.h" -#import "MacroDefines.h" +#import "HippyDefines.h" @interface TurboConfig () diff --git a/framework/examples/ios-demo/HippyDemo/vfsloader/HippyDemoLoader.h b/framework/examples/ios-demo/HippyDemo/vfsloader/HippyDemoLoader.h index d7aa70719ab..eb35e4bd5c3 100644 --- a/framework/examples/ios-demo/HippyDemo/vfsloader/HippyDemoLoader.h +++ b/framework/examples/ios-demo/HippyDemo/vfsloader/HippyDemoLoader.h @@ -18,7 +18,7 @@ * limitations under the License. */ -#import "MacroDefines.h" +#import "HippyDefines.h" #import "VFSUriHandler.h" #import "VFSUriLoader.h" diff --git a/framework/examples/ios-demo/podfile b/framework/examples/ios-demo/podfile index 9fcf344c618..87be121cf7b 100644 --- a/framework/examples/ios-demo/podfile +++ b/framework/examples/ios-demo/podfile @@ -1,5 +1,6 @@ -ENV["layout_engine"]="Taitank" +# ENV["layout_engine"]="Taitank" # ENV["js_engine"] = "v8" + install! 'cocoapods', :deterministic_uuids => false, :generate_multiple_pod_projects => true @@ -11,31 +12,3 @@ target "HippyDemo" do pod 'hippy', :path => '../../..' end -def rewriteConfigFile(path, originString, targetString) - File.open("#{path}", "r+") do |file| - originContents = file.read - if originContents.include?("#{originString}") - buffer = originContents.gsub("#{originString}", "#{targetString}") - File.open("#{path}", "w") do |line| - line.write(buffer) - end - end - end -end - -post_install do |installer| - _base_dir_ = File.dirname(__FILE__) - _pod_debug_config_dir_ = File.join("#{_base_dir_}", "Pods/Target Support Files", "Pods-HippyDemo", "Pods-HippyDemo.debug.xcconfig") - _pod_release_config_dir_ = File.join("#{_base_dir_}", "Pods/Target Support Files", "Pods-HippyDemo", "Pods-HippyDemo.release.xcconfig") - _hippy_dir_ = File.expand_path("../../../.", "#{_base_dir_}") - - - _target_debug_config_dir_ = File.join("#{_base_dir_}", "Pods/Target Support Files", "Hippy", "Hippy.debug.xcconfig") - _target_release_config_dir_ = File.join("#{_base_dir_}", "Pods/Target Support Files", "Hippy", "Hippy.release.xcconfig") - rewriteConfigFile("#{_target_debug_config_dir_}", "${PODS_ROOT}/hippy", "#{_hippy_dir_}") - rewriteConfigFile("#{_target_release_config_dir_}", "${PODS_ROOT}/hippy", "#{_hippy_dir_}") - - #change search path for HippyDemo - rewriteConfigFile("#{_pod_debug_config_dir_}", "${PODS_ROOT}/hippy", "#{_hippy_dir_}") - rewriteConfigFile("#{_pod_release_config_dir_}", "${PODS_ROOT}/hippy", "#{_hippy_dir_}") -end \ No newline at end of file diff --git a/framework/ios/base/HippyDeviceBaseInfo.h b/framework/ios/base/HippyDeviceBaseInfo.h index 00287cdc2ac..4a8bb80f49f 100644 --- a/framework/ios/base/HippyDeviceBaseInfo.h +++ b/framework/ios/base/HippyDeviceBaseInfo.h @@ -25,10 +25,15 @@ NS_ASSUME_NONNULL_BEGIN -HP_EXTERN NSDictionary *HippyExportedDimensions(void); +HIPPY_EXTERN NSDictionary *hippyExportedDimensions(HippyBridge *); +HIPPY_EXTERN NSString *const HippyDimensionsShouldUpdateNotification; +/// A Helper class that collects `Dimensions` info @interface HippyDeviceBaseInfo : NSObject +/// Whether is UIScreen in system dark mode. ++ (BOOL)isUIScreenInOSDarkMode; + @end NS_ASSUME_NONNULL_END diff --git a/framework/ios/base/HippyDeviceBaseInfo.mm b/framework/ios/base/HippyDeviceBaseInfo.mm index 69d5d8f5c11..3e7fbcd18e9 100644 --- a/framework/ios/base/HippyDeviceBaseInfo.mm +++ b/framework/ios/base/HippyDeviceBaseInfo.mm @@ -21,53 +21,40 @@ */ #import - -#import "HPAsserts.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" #import "HippyDeviceBaseInfo.h" #import "HippyEventDispatcher.h" -static BOOL IsiPhoneX() { - if (@available(iOS 11.0, *)) { - CGFloat height = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom; - return (height > 0); - } else { - return NO; - } -} - -static NSDictionary *gDimensions = nil; -static dispatch_semaphore_t DimesionSemaphore(void) { - static dispatch_semaphore_t semaphore = nil; +NSDictionary *hippyExportedDimensions(HippyBridge *bridge) { + NSCAssert([NSThread mainThread], @"this function can only be called in main thread"); + CGSize screenSize = [UIScreen mainScreen].bounds.size; + CGSize windowSize = HippyKeyWindow() ? HippyKeyWindow().bounds.size : screenSize; + // To be replace by HippyKeyWindow().windowScene.statusBarManager.statusBarFrame; + CGFloat statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height; + if (statusBarHeight == 0) { + // Since different devices have different statusbar height values, + // It is not recommended to use it for layout, + // but, it has been used in some scenarios, + // To reduce the impact of the problem, provide a default value when not available. + if ([bridge.delegate respondsToSelector:@selector(defaultStatusBarHeightNoMatterHiddenOrNot)]) { + statusBarHeight = bridge.delegate.defaultStatusBarHeightNoMatterHiddenOrNot ?: 0.0; + } + } + static NSNumber *screenScale = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - semaphore = dispatch_semaphore_create(1); - }); - return semaphore; -} - -static NSDictionary *InitializeDimesions(void) { - __block CGSize screenSize = CGSizeZero; - __block CGSize windowSize = CGSizeZero; - __block CGFloat statusBarHeight = 0.f; - __block NSNumber *screenScale = nil; - - dispatch_block_t block = ^(void){ - screenSize = [UIScreen mainScreen].bounds.size; - windowSize = HPKeyWindow() ? HPKeyWindow().bounds.size : screenSize; - statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height; - if (statusBarHeight == 0) { - statusBarHeight = IsiPhoneX() ? 44 : 20; - } screenScale = @([UIScreen mainScreen].scale); - }; - HPExecuteOnMainThread(block, YES); - gDimensions = @{ - // 备注,window和screen的区别在于有没有底bar虚拟导航栏,而iOS没有这个东西,所以window和screen是一样的 - @"window": - @ { @"width": @(windowSize.width), @"height": @(windowSize.height), @"scale": screenScale, @"statusBarHeight": @(statusBarHeight) }, - @"screen": @ { + }); + NSDictionary *dimensions = @{ + @"window" : @{ + @"width": @(windowSize.width), + @"height": @(windowSize.height), + @"scale": screenScale, + @"statusBarHeight": @(statusBarHeight) + }, + @"screen" : @{ @"width": @(screenSize.width), @"height": @(screenSize.height), @"scale": screenScale, @@ -75,113 +62,96 @@ static dispatch_semaphore_t DimesionSemaphore(void) { @"statusBarHeight": @(statusBarHeight) } }; - return gDimensions; -} - -static void DisposeDimesions(void) { - dispatch_semaphore_wait(DimesionSemaphore(), DISPATCH_TIME_FOREVER); - gDimensions = nil; - dispatch_semaphore_signal(DimesionSemaphore()); -} - -NSDictionary *HippyExportedDimensions(void) { - NSDictionary *dic = nil; - dispatch_semaphore_wait(DimesionSemaphore(), DISPATCH_TIME_FOREVER); - if (gDimensions) { - dic = [gDimensions copy]; - } - else { - dic = [InitializeDimesions() copy]; - } - dispatch_semaphore_signal(DimesionSemaphore()); - return dic; + return dimensions; } -@protocol HippyStatusBarOrientationChangedProtocol -@required -- (void)statusBarOrientationChanged; -@end +#pragma mark - -@interface HippyBaseInfoInternal : NSObject { - NSHashTable> *_observers; +@interface HippyDeviceBaseInfo () { + id _statusBarOrientationNotificationObserver; + id _applicationDidBecomeActiveNotificationObserver; + UIInterfaceOrientation _currentInterfaceOrientation; } -+ (instancetype)sharedInstance; +@end -- (void)addObserver:(id)observer; +@implementation HippyDeviceBaseInfo -- (void)removeObserver:(id)observer; +HIPPY_EXPORT_MODULE(DeviceBaseInfo) -@end +NSString *const HippyDimensionsShouldUpdateNotification = @"HippyDimensionsShouldUpdateNotification"; -@implementation HippyBaseInfoInternal +@synthesize bridge = _bridge; -+ (instancetype)sharedInstance { - static HippyBaseInfoInternal *instance = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - instance = [[HippyBaseInfoInternal alloc] init]; - }); - return instance; +static UIInterfaceOrientation getStatusBarOrientation(void) { + return [[UIApplication sharedApplication] statusBarOrientation]; } - (instancetype)init { self = [super init]; if (self) { - _observers = [NSHashTable weakObjectsHashTable]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(statusBarOrientationChanged) - name:UIApplicationDidChangeStatusBarOrientationNotification - object:nil]; + __weak HippyDeviceBaseInfo *devInfo = self; + NSString *notificationName; + if ([_bridge.delegate respondsToSelector:@selector(shouldUseViewWillTransitionMethodToMonitorOrientation)] + && _bridge.delegate.shouldUseViewWillTransitionMethodToMonitorOrientation) { + notificationName = HippyDimensionsShouldUpdateNotification; + } else { + notificationName = UIApplicationDidChangeStatusBarOrientationNotification; + } + _statusBarOrientationNotificationObserver = [[NSNotificationCenter defaultCenter] + addObserverForName:notificationName + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification *_Nonnull note) { + if (devInfo) { + HippyDeviceBaseInfo *strongSelf = devInfo; + UIInterfaceOrientation previousInterfaceOrientation = strongSelf->_currentInterfaceOrientation; + UIInterfaceOrientation currentInterfaceOrientation = getStatusBarOrientation(); + if (previousInterfaceOrientation != currentInterfaceOrientation) { + NSDictionary *dim = hippyExportedDimensions(strongSelf->_bridge); + [strongSelf->_bridge.eventDispatcher dispatchEvent:@"Dimensions" methodName:@"set" args:dim]; + } + strongSelf->_currentInterfaceOrientation = currentInterfaceOrientation; + } + }]; + + _applicationDidBecomeActiveNotificationObserver = [[NSNotificationCenter defaultCenter] + addObserverForName:UIApplicationDidBecomeActiveNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification *_Nonnull note) { + if (devInfo) { + HippyDeviceBaseInfo *strongSelf = devInfo; + UIInterfaceOrientation currentInterfaceOrientation = strongSelf->_currentInterfaceOrientation; + UIInterfaceOrientation activeStatusBarOrientation = getStatusBarOrientation(); + if (currentInterfaceOrientation != activeStatusBarOrientation) { + NSDictionary *dim = hippyExportedDimensions(strongSelf->_bridge); + [strongSelf->_bridge.eventDispatcher dispatchEvent:@"Dimensions" methodName:@"set" args:dim]; + } + strongSelf->_currentInterfaceOrientation = activeStatusBarOrientation; + } + }]; } return self; } - (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; -} - -- (void)addObserver:(id)observer { - [_observers addObject:observer]; -} - -- (void)removeObserver:(id)observer { - [_observers removeObject:observer]; -} - -- (void)statusBarOrientationChanged { - DisposeDimesions(); - for (id observer in _observers) { - [observer statusBarOrientationChanged]; - } -} - -@end - -@interface HippyDeviceBaseInfo () { + [[NSNotificationCenter defaultCenter] removeObserver:_statusBarOrientationNotificationObserver]; + [[NSNotificationCenter defaultCenter] removeObserver:_applicationDidBecomeActiveNotificationObserver]; } -@end - -@implementation HippyDeviceBaseInfo -HIPPY_EXPORT_MODULE(DeviceBaseInfo) - -@synthesize bridge = _bridge; +#pragma mark - Uitls -- (instancetype)init { - self = [super init]; - if (self) { - [[HippyBaseInfoInternal sharedInstance] addObserver:self]; ++ (BOOL)isUIScreenInOSDarkMode { + if (@available(iOS 12.0, *)) { + return (UIUserInterfaceStyleDark == [UIScreen mainScreen].traitCollection.userInterfaceStyle); + } else { + return NO; } - return self; } -- (void)statusBarOrientationChanged { - NSDictionary *dim = HippyExportedDimensions(); - [[self bridge].eventDispatcher dispatchEvent:@"Dimensions" methodName:@"set" args:dim]; -} @end diff --git a/framework/ios/base/HippyDisplayLink.m b/framework/ios/base/HippyDisplayLink.m index 9309eab25c1..ca12b232eb5 100644 --- a/framework/ios/base/HippyDisplayLink.m +++ b/framework/ios/base/HippyDisplayLink.m @@ -25,12 +25,12 @@ #import #import -#import "HPAsserts.h" +#import "HippyAsserts.h" #import "HippyBridgeModule.h" #import "HippyFrameUpdate.h" #import "HippyModuleData.h" -#define HPAssertRunLoop() HPAssert(_runLoop == [NSRunLoop currentRunLoop], @"This method must be called on the CADisplayLink run loop") +#define HippyAssertRunLoop() HippyAssert(_runLoop == [NSRunLoop currentRunLoop], @"This method must be called on the CADisplayLink run loop") @implementation HippyDisplayLink { CADisplayLink *_jsDisplayLink; @@ -107,7 +107,7 @@ - (void)dispatchBlock:(dispatch_block_t)block queue:(dispatch_queue_t)queue { } - (void)_jsThreadUpdate:(CADisplayLink *)displayLink { - HPAssertRunLoop(); + HippyAssertRunLoop(); HippyFrameUpdate *frameUpdate = [[HippyFrameUpdate alloc] initWithDisplayLink:displayLink]; for (HippyModuleData *moduleData in _frameUpdateObservers) { @@ -123,7 +123,7 @@ - (void)_jsThreadUpdate:(CADisplayLink *)displayLink { } - (void)updateJSDisplayLinkState { - HPAssertRunLoop(); + HippyAssertRunLoop(); BOOL pauseDisplayLink = YES; for (HippyModuleData *moduleData in _frameUpdateObservers) { diff --git a/framework/ios/base/HippyFrameUpdate.m b/framework/ios/base/HippyFrameUpdate.m index abe88a29a02..1ace892f58a 100644 --- a/framework/ios/base/HippyFrameUpdate.m +++ b/framework/ios/base/HippyFrameUpdate.m @@ -22,8 +22,8 @@ #import #import "HippyFrameUpdate.h" -#import "HPToolUtils.h" -#import "MacroDefines.h" +#import "HippyUtils.h" +#import "HippyDefines.h" @implementation HippyFrameUpdate diff --git a/framework/ios/base/HippyKeyCommands.m b/framework/ios/base/HippyKeyCommands.m index 11648dfae97..7314fa61368 100644 --- a/framework/ios/base/HippyKeyCommands.m +++ b/framework/ios/base/HippyKeyCommands.m @@ -22,11 +22,11 @@ #import "HippyKeyCommands.h" #import -#import "HPAsserts.h" -#import "MacroDefines.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyDefines.h" +#import "HippyUtils.h" -#if HP_DEV +#if HIPPY_DEV static BOOL HippyIsIOS8OrEarlier() { return [UIDevice currentDevice].systemVersion.floatValue < 9; @@ -198,12 +198,12 @@ @implementation HippyKeyCommands + (void)initialize { if (HippyIsIOS8OrEarlier()) { // swizzle UIApplication - HPSwapInstanceMethods([UIApplication class], @selector(keyCommands), @selector(hippy_keyCommands)); + HippySwapInstanceMethods([UIApplication class], @selector(keyCommands), @selector(hippy_keyCommands)); - HPSwapInstanceMethods([UIApplication class], @selector(sendAction:to:from:forEvent:), @selector(hippy_sendAction:to:from:forEvent:)); + HippySwapInstanceMethods([UIApplication class], @selector(sendAction:to:from:forEvent:), @selector(hippy_sendAction:to:from:forEvent:)); } else { // swizzle UIResponder - HPSwapInstanceMethods([UIResponder class], @selector(keyCommands), @selector(hippy_keyCommands)); + HippySwapInstanceMethods([UIResponder class], @selector(keyCommands), @selector(hippy_keyCommands)); } } @@ -225,7 +225,7 @@ - (instancetype)init { } - (void)registerKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags action:(void (^)(UIKeyCommand *))block { - HPAssertMainQueue(); + HippyAssertMainQueue(); if (input.length && flags && HippyIsIOS8OrEarlier()) { // Workaround around the first cmd not working: http://openradar.appspot.com/19613391 @@ -243,7 +243,7 @@ - (void)registerKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifi } - (void)unregisterKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { - HPAssertMainQueue(); + HippyAssertMainQueue(); for (HippyKeyCommand *command in _commands.allObjects) { if ([command matchesInput:input flags:flags]) { @@ -254,7 +254,7 @@ - (void)unregisterKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModi } - (BOOL)isKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { - HPAssertMainQueue(); + HippyAssertMainQueue(); for (HippyKeyCommand *command in _commands.allObjects) { // add by stockGroup if ([command matchesInput:input flags:flags]) { @@ -265,7 +265,7 @@ - (BOOL)isKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyMod } - (void)registerDoublePressKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags action:(void (^)(UIKeyCommand *))block { - HPAssertMainQueue(); + HippyAssertMainQueue(); if (input.length && flags && HippyIsIOS8OrEarlier()) { // Workaround around the first cmd not working: http://openradar.appspot.com/19613391 @@ -283,7 +283,7 @@ - (void)registerDoublePressKeyCommandWithInput:(NSString *)input modifierFlags:( } - (void)unregisterDoublePressKeyCommandWithInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { - HPAssertMainQueue(); + HippyAssertMainQueue(); for (HippyKeyCommand *command in _commands.allObjects) { if ([command matchesInput:input flags:flags]) { @@ -294,7 +294,7 @@ - (void)unregisterDoublePressKeyCommandWithInput:(NSString *)input modifierFlags } - (BOOL)isDoublePressKeyCommandRegisteredForInput:(NSString *)input modifierFlags:(UIKeyModifierFlags)flags { - HPAssertMainQueue(); + HippyAssertMainQueue(); for (HippyKeyCommand *command in _commands.allObjects) { // add by stockGroup if ([command matchesInput:input flags:flags]) { diff --git a/framework/ios/base/bridge/HippyBridge.h b/framework/ios/base/bridge/HippyBridge.h index 1bfe678c6cc..4be77018336 100644 --- a/framework/ios/base/bridge/HippyBridge.h +++ b/framework/ios/base/bridge/HippyBridge.h @@ -21,21 +21,25 @@ */ #import - #import "HippyBridgeDelegate.h" #import "HippyBridgeModule.h" #import "HippyMethodInterceptorProtocol.h" #import "HippyModulesSetup.h" -#import "HPImageProviderProtocol.h" -#import "HPInvalidating.h" -#import "MacroDefines.h" +#import "HippyImageProviderProtocol.h" +#import "HippyInvalidating.h" +#import "HippyDefines.h" +#ifdef __cplusplus #include +#endif @class HippyJSExecutor; @class HippyModuleData; +@class HippyRootView; +#ifdef __cplusplus class VFSUriLoader; +class NativeRenderManager; namespace hippy { inline namespace dom { @@ -44,29 +48,30 @@ class RootNode; class RenderManager; }; }; +#endif NS_ASSUME_NONNULL_BEGIN /** * Indicate hippy sdk version */ -HP_EXTERN NSString *const HippySDKVersion; +HIPPY_EXTERN NSString *const HippySDKVersion; /** * This notification triggers a reload of all bridges currently running. * Deprecated, use HippyBridge::requestReload instead. */ -HP_EXTERN NSString *const HippyReloadNotification; +HIPPY_EXTERN NSString *const HippyReloadNotification; /** * This notification fires when the bridge has finished loading the JS bundle. */ -HP_EXTERN NSString *const HippyJavaScriptDidLoadNotification; +HIPPY_EXTERN NSString *const HippyJavaScriptDidLoadNotification; /** * This notification fires when the bridge failed to load the JS bundle. The * `error` key can be used to determine the error that occured. */ -HP_EXTERN NSString *const HippyJavaScriptDidFailToLoadNotification; +HIPPY_EXTERN NSString *const HippyJavaScriptDidFailToLoadNotification; /** * This notification fires each time a native module is instantiated. The @@ -74,37 +79,58 @@ HP_EXTERN NSString *const HippyJavaScriptDidFailToLoadNotification; * Note that this notification may be fired before the module is available via * the `[bridge moduleForClass:]` method. */ -HP_EXTERN NSString *const HippyDidInitializeModuleNotification; +HIPPY_EXTERN NSString *const HippyDidInitializeModuleNotification; /** * This function returns the module name for a given class. */ -HP_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); +HIPPY_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); -/** - * Async batched bridge used to communicate with the JavaScript application. - */ -@interface HippyBridge : NSObject + +/// Async bridge used to communicate with the JavaScript application. +@interface HippyBridge : NSObject + +/// The bridge delegate @property (nonatomic, weak, readonly) id delegate; +/// SDK launch config +/// TODO: 优化 launchOptions 参数 @property (nonatomic, copy, readonly) NSDictionary *launchOptions; -@property (nonatomic, assign) std::weak_ptr renderManager; -/** - * Create A HippyBridge instance - * - * @param delegate bridge delegate - * @param block for user-defined module - * @param launchOptions launch options, will not be sent to frontend - * @param engineKey key to engine instance. HippyBridge with same engine key will share same engine intance - * @return A HippyBridge instance - */ +/// Create A HippyBridge instance, without load/execute any js bundle. +/// +/// @param delegate bridge delegate +/// @param block for user-defined module +/// @param launchOptions launch options, will not be sent to frontend +/// @param executorKey key to engine instance. HippyBridge with same engine key will share same engine intance. +/// +/// Note: 多个bridge使用相同的共享engineKey时,只有全部bridge实例销毁时engine资源才将释放,因此,请注意合理使用,避免出现意外的内存泄漏。 +/// 传空时默认不共享,SDK内部默认分配一随机key。 +- (instancetype)initWithDelegate:(id)delegate + moduleProvider:(nullable HippyBridgeModuleProviderBlock)block + launchOptions:(nullable NSDictionary *)launchOptions + executorKey:(nullable NSString *)executorKey; + + +/// Create A HippyBridge instance with a common js bundle. +/// +/// This method is compatible with the Hippy2 initializer function. +/// +/// @param delegate bridge delegate +/// @param bundleURL the +/// @param block for user-defined module +/// @param launchOptions launch options, will not be sent to frontend +/// @param executorKey key to engine instance. HippyBridge with same engine key will share same engine intance. +/// +/// Note: 多个bridge使用相同的共享engineKey时,只有全部bridge实例销毁时engine资源才将释放,因此,请注意合理使用,避免出现意外的内存泄漏。 +/// 传空时默认不共享,SDK内部默认分配一随机key。 - (instancetype)initWithDelegate:(id)delegate - moduleProvider:(HippyBridgeModuleProviderBlock)block - launchOptions:(NSDictionary *)launchOptions - engineKey:(NSString *)engineKey; + bundleURL:(nullable NSURL *)bundleURL + moduleProvider:(nullable HippyBridgeModuleProviderBlock)block + launchOptions:(nullable NSDictionary *)launchOptions + executorKey:(nullable NSString *)executorKey; /** * Context name for HippyBridge @@ -140,15 +166,18 @@ HP_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); - (void)loadBundleURL:(NSURL *)bundleURL completion:(void (^_Nullable)(NSURL * _Nullable, NSError * _Nullable))completion; +#ifdef __cplusplus @property(nonatomic, assign)std::weak_ptr VFSUriLoader; +#endif /** * Image provider method * Users adds or obtains image providers in the following methods */ -- (void)addImageProviderClass:(Class)cls; -- (NSArray> *)imageProviderClasses; +- (void)addImageProviderClass:(Class)cls; +- (NSArray> *)imageProviderClasses; +#ifdef __cplusplus /** * Set basic configuration for native render * @param domManager DomManager @@ -156,6 +185,7 @@ HP_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); */ - (void)setupDomManager:(std::shared_ptr)domManager rootNode:(std::weak_ptr)rootNode; +#endif /** * Load instance for root view and show views @@ -175,6 +205,13 @@ HP_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); */ @property (nonatomic, readonly) HippyJSExecutor *javaScriptExecutor; + +#ifdef __cplusplus +/// The C++ version of RenderManager instance, bridge holds +@property (nonatomic, assign) std::shared_ptr renderManager; +#endif + + /** * JS invocation methods */ @@ -189,11 +226,13 @@ HP_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); - (void)handleBuffer:(id _Nullable)buffer batchEnded:(BOOL)batchEnded; + +/// <#Description#> +/// - Parameter isInspectable: <#isInspectable description#> - (void)setInspectable:(BOOL)isInspectable; -/** - * All registered bridge module classes. - */ + +/// All registered bridge module classes. @property (nonatomic, copy, readonly) NSArray *moduleClasses; - (NSString *)moduleConfig; @@ -225,15 +264,10 @@ HP_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); - (BOOL)moduleIsInitialized:(Class)moduleClass; /** A red box will show when error occurs by default - * only work on HP_DEBUG mode + * only work on HIPPY_DEBUG mode */ - (void)setRedBoxShowEnabled:(BOOL)enabled; -/** - * just for debugger - */ -- (void)bindKeys; - /** * Use this to check if the bridge has been invalidated. */ @@ -253,9 +287,9 @@ HP_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); @property (nonatomic, assign) BOOL debugMode; -@property (nonatomic, strong) NSString *appVerson; // +@property (nonatomic, strong) NSString *appVerson; -@property (nonatomic, assign) HPInvalidateReason invalidateReason; +@property (nonatomic, assign) HippyInvalidateReason invalidateReason; @property (nonatomic, weak) id methodInterceptor; @@ -281,23 +315,30 @@ HP_EXTERN NSString *HippyBridgeModuleNameForClass(Class bridgeModuleClass); - (void)setSnapShotData:(NSData *)data; -@end -@interface HippyBridge (RedBoxDebug) +- (void)setRootView:(UIView *)rootView; + +- (void)resetRootSize:(CGSize)size; + + +#pragma mark - App UI State Related + +/// NightMode or not, default is NO. +/// Updated by HippyRootView +@property (atomic, assign, readonly) BOOL isOSNightMode; -/// The last current active bridge instance. -+ (instancetype)currentBridge; +/// update `NightMode` state when changed +/// - Parameter isOSNightMode: bool +/// - Parameter rootViewTag: rootView's hippyTag +- (void)setOSNightMode:(BOOL)isOSNightMode withRootViewTag:(NSNumber *)rootViewTag; -/// Record the last active bridge instance. -/// - Parameter currentBridge: bridge instance, pass nil to reset. -+ (void)setCurrentBridge:(nullable HippyBridge *)currentBridge; @end -HP_EXTERN void HippyBridgeFatal(NSError *, HippyBridge *); +HIPPY_EXTERN void HippyBridgeFatal(NSError *, HippyBridge *); -HP_EXTERN void HippyBridgeHandleException(NSException *exception, HippyBridge *bridge); +HIPPY_EXTERN void HippyBridgeHandleException(NSException *exception, HippyBridge *bridge); NS_ASSUME_NONNULL_END diff --git a/framework/ios/base/bridge/HippyBridge.mm b/framework/ios/base/bridge/HippyBridge.mm index f9a934e5cee..eaa4c2433bc 100644 --- a/framework/ios/base/bridge/HippyBridge.mm +++ b/framework/ios/base/bridge/HippyBridge.mm @@ -39,14 +39,14 @@ #import "HippyRedBox.h" #import "HippyTurboModule.h" #import "HippyUtils.h" -#import "HPAsserts.h" -#import "HPConvert.h" -#import "HPDefaultImageProvider.h" -#import "HPI18nUtils.h" -#import "HPInvalidating.h" -#import "HPLog.h" -#import "HPOCToHippyValue.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyConvert.h" +#import "HippyDefaultImageProvider.h" +#import "HippyI18nUtils.h" +#import "HippyInvalidating.h" +#import "HippyLog.h" +#import "HippyOCToHippyValue.h" +#import "HippyUtils.h" #import "NSObject+Render.h" #import "TypeConverter.h" #import "VFSUriLoader.h" @@ -65,6 +65,11 @@ #include "vfs/uri_loader.h" #include "VFSUriHandler.h" +#import "NativeRenderManager.h" +#import "HippyRootView.h" +#import "UIView+Hippy.h" + + #ifdef ENABLE_INSPECTOR #include "devtools/vfs/devtools_handler.h" #include "devtools/devtools_data_source.h" @@ -76,6 +81,17 @@ NSString *const HippyDidInitializeModuleNotification = @"HippyDidInitializeModuleNotification"; NSString *const HippySDKVersion = @"unspecified"; + +static NSString *const HippyNativeGlobalKeyOS = @"OS"; +static NSString *const HippyNativeGlobalKeyOSVersion = @"OSVersion"; +static NSString *const HippyNativeGlobalKeyDevice = @"Device"; +static NSString *const HippyNativeGlobalKeySDKVersion = @"SDKVersion"; +static NSString *const HippyNativeGlobalKeyAppVersion = @"AppVersion"; +static NSString *const HippyNativeGlobalKeyDimensions = @"Dimensions"; +static NSString *const HippyNativeGlobalKeyLocalization = @"Localization"; +static NSString *const HippyNativeGlobalKeyNightMode = @"NightMode"; + + typedef NS_ENUM(NSUInteger, HippyBridgeFields) { HippyBridgeFieldRequestModuleIDs = 0, HippyBridgeFieldMethodIDs, @@ -84,26 +100,43 @@ typedef NS_ENUM(NSUInteger, HippyBridgeFields) { }; @interface HippyBridge() { - NSMutableArray> *_imageProviders; + NSMutableArray> *_imageProviders; __weak id _methodInterceptor; HippyModulesSetup *_moduleSetup; __weak NSOperation *_lastOperation; BOOL _wasBatchActive; HippyDisplayLink *_displayLink; HippyBridgeModuleProviderBlock _moduleProvider; - NSString *_engineKey; BOOL _valid; HippyBundleOperationQueue *_bundlesQueue; NSMutableArray *_bundleURLs; NSURL *_sandboxDirectory; - std::weak_ptr _uriLoader; - std::weak_ptr _renderManager; + footstone::TimePoint _startTime; + + std::shared_ptr _uriLoader; + std::shared_ptr _rootNode; + + // 缓存的设备信息 + NSDictionary *_cachedDeviceInfo; } +/// 用于标记bridge所使用的JS引擎的Key +/// +/// 注意:传入相同值的bridge将共享底层JS引擎。 +/// 在共享情况下,只有全部bridge实例均释放,JS引擎资源才会销毁。 +/// 默认情况下对每个bridge使用独立JS引擎 +@property (nonatomic, strong) NSString *engineKey; +/// 等待加载(Load)的 Vendor bundleURL +@property (nonatomic, strong) NSURL *pendingLoadingVendorBundleURL; + @property(readwrite, strong) dispatch_semaphore_t moduleSemaphore; @property(readwrite, assign) NSInteger loadingCount; + +/// 缓存的Dimensions信息,用于传递给JS Side +@property (atomic, strong) NSDictionary *cachedDimensionsInfo; + @end @implementation HippyBridge @@ -133,36 +166,59 @@ + (void)initialize { - (instancetype)initWithDelegate:(id)delegate moduleProvider:(HippyBridgeModuleProviderBlock)block launchOptions:(NSDictionary *)launchOptions - engineKey:(NSString *)engineKey { + executorKey:(nullable NSString *)executorKey { + return [self initWithDelegate:delegate + bundleURL:nil + moduleProvider:block + launchOptions:launchOptions + executorKey:executorKey]; +} + +- (instancetype)initWithDelegate:(id)delegate + bundleURL:(NSURL *)bundleURL + moduleProvider:(HippyBridgeModuleProviderBlock)block + launchOptions:(NSDictionary *)launchOptions + executorKey:(nullable NSString *)executorKey { if (self = [super init]) { _delegate = delegate; _moduleProvider = block; - _bundleURLs = [NSMutableArray arrayWithCapacity:8]; + _pendingLoadingVendorBundleURL = bundleURL; + _bundleURLs = [NSMutableArray array]; _debugMode = [launchOptions[@"DebugMode"] boolValue]; _enableTurbo = !!launchOptions[@"EnableTurbo"] ? [launchOptions[@"EnableTurbo"] boolValue] : YES; - _engineKey = engineKey; - _invalidateReason = HPInvalidateReasonDealloc; + _engineKey = executorKey.length > 0 ? executorKey : [NSString stringWithFormat:@"%p", self]; + _invalidateReason = HippyInvalidateReasonDealloc; _valid = YES; _bundlesQueue = [[HippyBundleOperationQueue alloc] init]; _startTime = footstone::TimePoint::SystemNow(); - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rootViewContentDidAppear:) name:kRootViewDidAddContent object:nil]; - [self setUp]; - HPExecuteOnMainThread(^{ - [self bindKeys]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rootViewContentDidAppear:) + name:HippyContentDidAppearNotification object:nil]; + HippyExecuteOnMainThread(^{ + self->_isOSNightMode = [HippyDeviceBaseInfo isUIScreenInOSDarkMode]; + self.cachedDimensionsInfo = hippyExportedDimensions(self); }, YES); + + [self setUp]; + + [self addImageProviderClass:[HippyDefaultImageProvider class]]; + [self setVFSUriLoader:[self createURILoaderIfNeeded]]; + [self setUpNativeRenderManager]; + [HippyBridge setCurrentBridge:self]; - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],%@ Init %p", NSStringFromClass([self class]), self); + + [self loadPendingVendorBundleURLIfNeeded]; + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],%@ Init %p", NSStringFromClass([self class]), self); } return self; } - (void)rootViewContentDidAppear:(NSNotification *)noti { - UIView *rootView = [[noti userInfo] objectForKey:kRootViewKey]; + UIView *rootView = [noti object]; if (rootView) { auto domManager = _javaScriptExecutor.pScope->GetDomManager().lock(); if (domManager) { auto viewRenderManager = [rootView renderManager]; - if (_renderManager.lock() == viewRenderManager.lock()) { + if (_renderManager == viewRenderManager.lock()) { auto entry = _javaScriptExecutor.pScope->GetPerformance()->PerformanceNavigation("hippyInit"); entry->SetHippyDomStart(domManager->GetDomStartTimePoint()); entry->SetHippyDomEnd(domManager->GetDomEndTimePoint()); @@ -176,25 +232,47 @@ - (void)rootViewContentDidAppear:(NSNotification *)noti { - (void)dealloc { /** * This runs only on the main thread, but crashes the subclass - * HPAssertMainQueue(); + * HippyAssertMainQueue(); */ - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],%@ dealloc %p", NSStringFromClass([self class]), self); + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],%@ dealloc %p", NSStringFromClass([self class]), self); [[NSNotificationCenter defaultCenter] removeObserver:self]; - self.invalidateReason = HPInvalidateReasonDealloc; + self.invalidateReason = HippyInvalidateReasonDealloc; [self invalidate]; + + // FIXME: 检查问题 + if (_uriLoader) { + _uriLoader->Terminate(); + } + if (_rootNode) { + _renderManager->RemoveVSyncEventListener(_rootNode); + _rootNode->ReleaseResources(); + } } -- (void)bindKeys { -#if TARGET_IPHONE_SIMULATOR - HPAssertMainQueue(); - HippyKeyCommands *commands = [HippyKeyCommands sharedInstance]; - - // reload in current mode - __weak __typeof(self) weakSelf = self; - [commands registerKeyCommandWithInput:@"r" modifierFlags:UIKeyModifierCommand action:^(__unused UIKeyCommand *command) { - [weakSelf requestReload]; - }]; -#endif +- (void)setUpNativeRenderManager { + auto engineResource = [[HippyJSEnginesMapper defaultInstance] JSEngineResourceForKey:self.engineKey]; + auto domManager = engineResource->GetDomManager(); + //Create NativeRenderManager + auto nativeRenderManager = std::make_shared(); + nativeRenderManager->Initialize(); + //set dom manager + nativeRenderManager->SetDomManager(domManager); + nativeRenderManager->SetVFSUriLoader([self createURILoaderIfNeeded]); + nativeRenderManager->SetHippyBridge(self); + _renderManager = nativeRenderManager; +} + +- (std::shared_ptr)createURILoaderIfNeeded { + if (!_uriLoader) { + auto uriHandler = std::make_shared(); + auto uriLoader = std::make_shared(); + uriLoader->PushDefaultHandler(uriHandler); + uriLoader->AddConvenientDefaultHandler(uriHandler); + auto fileHandler = std::make_shared(self); + uriLoader->RegisterConvenientUriHandler(@"hpfile", fileHandler); + _uriLoader = uriLoader; + } + return _uriLoader; } - (NSArray *)moduleClasses { @@ -209,19 +287,20 @@ - (id)moduleForClass:(Class)moduleClass { return [_moduleSetup moduleForClass:moduleClass]; } -- (void)addImageProviderClass:(Class)cls { - HPAssertParam(cls); +- (void)addImageProviderClass:(Class)cls { + HippyAssertParam(cls); @synchronized (self) { if (!_imageProviders) { - _imageProviders = [NSMutableArray arrayWithCapacity:8]; + _imageProviders = [NSMutableArray array]; } [_imageProviders addObject:cls]; } } -- (NSArray> *)imageProviderClasses { + +- (NSArray> *)imageProviderClasses { @synchronized (self) { if (!_imageProviders) { - _imageProviders = [NSMutableArray arrayWithCapacity:8]; + _imageProviders = [NSMutableArray array]; } return [_imageProviders copy]; } @@ -244,13 +323,16 @@ - (BOOL)moduleIsInitialized:(Class)moduleClass { return [_moduleSetup moduleIsInitialized:moduleClass]; } + +#pragma mark - Debug Reload + - (void)reload { if ([self.delegate respondsToSelector:@selector(reload:)]) { - self.invalidateReason = HPInvalidateReasonReload; + self.invalidateReason = HippyInvalidateReasonReload; [self invalidate]; [self setUp]; [self.delegate reload:self]; - self.invalidateReason = HPInvalidateReasonDealloc; + self.invalidateReason = HippyInvalidateReasonDealloc; } } @@ -261,20 +343,23 @@ - (void)requestReload { } } + +#pragma mark - Bridge SetUp + - (void)setUp { _valid = YES; self.moduleSemaphore = dispatch_semaphore_create(0); @try { __weak HippyBridge *weakSelf = self; _moduleSetup = [[HippyModulesSetup alloc] initWithBridge:self extraProviderModulesBlock:_moduleProvider]; - _javaScriptExecutor = [[HippyJSExecutor alloc] initWithEngineKey:_engineKey bridge:self]; + _javaScriptExecutor = [[HippyJSExecutor alloc] initWithEngineKey:self.engineKey bridge:self]; _javaScriptExecutor.contextCreatedBlock = ^(id ctxWrapper){ HippyBridge *strongSelf = weakSelf; if (strongSelf) { dispatch_semaphore_wait(strongSelf.moduleSemaphore, DISPATCH_TIME_FOREVER); NSString *moduleConfig = [strongSelf moduleConfig]; [ctxWrapper createGlobalObject:@"__hpBatchedBridgeConfig" withJsonValue:moduleConfig]; -#if HP_DEV +#if HIPPY_DEV //default is yes when debug mode [strongSelf setInspectable:YES]; #endif //HIPPY_DEV @@ -285,26 +370,39 @@ - (void)setUp { _javaScriptExecutor.contextName = _contextName; } _displayLink = [[HippyDisplayLink alloc] init]; - //The caller may attempt to look up a module immediately after creating the HippyBridge, - //therefore the initialization of all modules cannot be placed in a sub-thread -// dispatch_async(HippyBridgeQueue(), ^{ - [self initWithModulesCompletion:^{ + + // Setup all extra and internal modules + [_moduleSetup setupModulesCompletion:^{ HippyBridge *strongSelf = weakSelf; if (strongSelf) { dispatch_semaphore_signal(strongSelf.moduleSemaphore); footstone::TimePoint endTime = footstone::TimePoint::SystemNow(); - auto enty = - strongSelf.javaScriptExecutor.pScope->GetPerformance()->PerformanceNavigation("hippyInit"); + auto enty = strongSelf.javaScriptExecutor.pScope->GetPerformance()->PerformanceNavigation("hippyInit"); enty->SetHippyNativeInitStart(strongSelf->_startTime); enty->SetHippyNativeInitEnd(endTime); } }]; -// }); + } @catch (NSException *exception) { HippyBridgeHandleException(exception, self); } } + +/// 加载初始化bridge时传入的Bundle URL +- (void)loadPendingVendorBundleURLIfNeeded { + if (self.pendingLoadingVendorBundleURL) { + [self loadBundleURL:self.pendingLoadingVendorBundleURL completion:^(NSURL * _Nullable url, NSError * _Nullable error) { + if (error) { + HippyLogError(@"[Hippy_OC_Log][HippyBridge], bundle loaded error:%@, %@", url, error.description); + } else { + HippyLogInfo(@"[Hippy_OC_Log][HippyBridge], bundle loaded success:%@", url); + } + }]; + } +} + + - (void)loadBundleURL:(NSURL *)bundleURL completion:(void (^_Nullable)(NSURL * _Nullable, NSError * _Nullable))completion { if (!bundleURL) { @@ -321,12 +419,6 @@ - (void)loadBundleURL:(NSURL *)bundleURL }); } - - -- (void)initWithModulesCompletion:(dispatch_block_t)completion { - [_moduleSetup setupModulesCompletion:completion]; -} - - (void)beginLoadingBundle:(NSURL *)bundleURL completion:(void (^)(NSURL * _Nullable, NSError * _Nullable))completion { dispatch_group_t group = dispatch_group_create(); @@ -397,6 +489,12 @@ - (void)unloadInstanceForRootView:(NSNumber *)rootTag { footstone::value::HippyValue value = [param toHippyValue]; std::shared_ptr domValue = std::make_shared(value); self.javaScriptExecutor.pScope->UnloadInstance(domValue); + + _renderManager->UnregisterRootView([rootTag intValue]); + if (_rootNode) { + _rootNode->ReleaseResources(); + _rootNode = nullptr; + } } } @@ -405,8 +503,8 @@ - (void)loadInstanceForRootView:(NSNumber *)rootTag withProperties:(NSDictionary } - (void)innerLoadInstanceForRootView:(NSNumber *)rootTag withProperties:(NSDictionary *)props { - HPAssert(_moduleName, @"module name must not be null"); - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],Running application %@ (%@)", _moduleName, props); + HippyAssert(_moduleName, @"module name must not be null"); + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],Running application %@ (%@)", _moduleName, props); NSDictionary *param = @{@"name": _moduleName, @"id": rootTag, @"params": props ?: @{}, @@ -423,7 +521,6 @@ - (void)rootViewSizeChangedEvent:(NSNumber *)tag params:(NSDictionary *)params { } - (void)setVFSUriLoader:(std::weak_ptr)uriLoader { - _uriLoader = uriLoader; [_javaScriptExecutor setUriLoader:uriLoader]; #ifdef ENABLE_INSPECTOR auto devtools_data_source = _javaScriptExecutor.pScope->GetDevtoolsDataSource(); @@ -449,14 +546,14 @@ - (void)executeJSCode:(NSData *)script sourceURL:(NSURL *)sourceURL onCompletion:(HippyJavaScriptCallback)completion { if (!script) { - completion(nil, HPErrorWithMessageAndModuleName(@"no valid data", _moduleName)); + completion(nil, HippyErrorWithMessageAndModuleName(@"no valid data", _moduleName)); return; } if (![self isValid] || !script || !sourceURL) { - completion(nil, HPErrorWithMessageAndModuleName(@"bridge is not valid", _moduleName)); + completion(nil, HippyErrorWithMessageAndModuleName(@"bridge is not valid", _moduleName)); return; } - HPAssert(self.javaScriptExecutor, @"js executor must not be null"); + HippyAssert(self.javaScriptExecutor, @"js executor must not be null"); __weak HippyBridge *weakSelf = self; [self.javaScriptExecutor executeApplicationScript:script sourceURL:sourceURL onComplete:^(id result ,NSError *error) { HippyBridge *strongSelf = weakSelf; @@ -471,7 +568,7 @@ - (void)executeJSCode:(NSData *)script dispatch_async(dispatch_get_main_queue(), ^{ NSDictionary *userInfo = @{@"bridge": self, sourceURL: sourceURL}; [[NSNotificationCenter defaultCenter] postNotificationName:HippyJavaScriptDidLoadNotification - object:nil + object:self userInfo:userInfo]; }); } @@ -480,7 +577,7 @@ - (void)executeJSCode:(NSData *)script } - (void)stopLoadingWithError:(NSError *)error scriptSourceURL:(NSURL *)sourceURL { - HPAssertMainQueue(); + HippyAssertMainQueue(); if (![self isValid]) { return; } @@ -495,10 +592,10 @@ - (void)stopLoadingWithError:(NSError *)error scriptSourceURL:(NSURL *)sourceURL }]; NSDictionary *userInfo = @{@"bridge": self, @"error": error, @"sourceURL": sourceURL}; [[NSNotificationCenter defaultCenter] postNotificationName:HippyJavaScriptDidFailToLoadNotification - object:nil + object:self userInfo:userInfo]; - if ([error userInfo][HPJSStackTraceKey]) { - [self.redBox showErrorMessage:[error localizedDescription] withStack:[error userInfo][HPJSStackTraceKey]]; + if ([error userInfo][HippyJSStackTraceKey]) { + [self.redBox showErrorMessage:[error localizedDescription] withStack:[error userInfo][HippyJSStackTraceKey]]; } } @@ -537,17 +634,17 @@ - (void)dispatchBlock:(dispatch_block_t)block queue:(dispatch_queue_t)queue { - (void)processResponse:(id)json error:(NSError *)error { if (error) { - if ([error userInfo][HPJSStackTraceKey]) { + if ([error userInfo][HippyJSStackTraceKey]) { if (error.localizedFailureReason) { [self.redBox showErrorMessage:[NSString stringWithFormat:@"%@ 【reason】%@:", error.localizedDescription, error.localizedFailureReason] - withStack:[error userInfo][HPJSStackTraceKey]]; + withStack:[error userInfo][HippyJSStackTraceKey]]; } else { [self.redBox showErrorMessage:[NSString stringWithFormat:@"%@", error.localizedDescription] - withStack:[error userInfo][HPJSStackTraceKey]]; + withStack:[error userInfo][HippyJSStackTraceKey]]; } } - NSError *retError = HPErrorFromErrorAndModuleName(error, self.moduleName); + NSError *retError = HippyErrorFromErrorAndModuleName(error, self.moduleName); HippyBridgeFatal(retError, self); } @@ -598,16 +695,16 @@ - (void)batchDidComplete { } - (void)handleBuffer:(NSArray *)buffer { - NSArray *requestsArray = [HPConvert NSArray:buffer]; + NSArray *requestsArray = [HippyConvert NSArray:buffer]; - if (HP_DEBUG && requestsArray.count <= HippyBridgeFieldParams) { - HPLogError(@"Buffer should contain at least %tu sub-arrays. Only found %tu", HippyBridgeFieldParams + 1, requestsArray.count); + if (HIPPY_DEBUG && requestsArray.count <= HippyBridgeFieldParams) { + HippyLogError(@"Buffer should contain at least %tu sub-arrays. Only found %tu", HippyBridgeFieldParams + 1, requestsArray.count); return; } - NSArray *moduleIDs = [HPConvert NSNumberArray:requestsArray[HippyBridgeFieldRequestModuleIDs]]; - NSArray *methodIDs = [HPConvert NSNumberArray:requestsArray[HippyBridgeFieldMethodIDs]]; - NSArray *paramsArrays = [HPConvert NSArrayArray:requestsArray[HippyBridgeFieldParams]]; + NSArray *moduleIDs = [HippyConvert NSNumberArray:requestsArray[HippyBridgeFieldRequestModuleIDs]]; + NSArray *methodIDs = [HippyConvert NSNumberArray:requestsArray[HippyBridgeFieldMethodIDs]]; + NSArray *paramsArrays = [HippyConvert NSArrayArray:requestsArray[HippyBridgeFieldParams]]; int64_t callID = -1; @@ -615,8 +712,8 @@ - (void)handleBuffer:(NSArray *)buffer { callID = [requestsArray[HippyBridgeFieldCallID] longLongValue]; } - if (HP_DEBUG && (moduleIDs.count != methodIDs.count || moduleIDs.count != paramsArrays.count)) { - HPLogError(@"Invalid data message - all must be length: %lu", (unsigned long)moduleIDs.count); + if (HIPPY_DEBUG && (moduleIDs.count != methodIDs.count || moduleIDs.count != paramsArrays.count)) { + HippyLogError(@"Invalid data message - all must be length: %lu", (unsigned long)moduleIDs.count); return; } @@ -671,14 +768,14 @@ - (id)callNativeModule:(NSUInteger)moduleID method:(NSUInteger)methodID params:( NSArray *moduleDataByID = [_moduleSetup moduleDataByID]; if (moduleID >= [moduleDataByID count]) { if (isValid) { - HPLogError(@"moduleID %lu exceed range of moduleDataByID %lu, bridge is valid %ld", moduleID, [moduleDataByID count], (long)isValid); + HippyLogError(@"moduleID %lu exceed range of moduleDataByID %lu, bridge is valid %ld", moduleID, [moduleDataByID count], (long)isValid); } return nil; } HippyModuleData *moduleData = moduleDataByID[moduleID]; - if (HP_DEBUG && !moduleData) { + if (HIPPY_DEBUG && !moduleData) { if (isValid) { - HPLogError(@"No module found for id '%lu'", (unsigned long)moduleID); + HippyLogError(@"No module found for id '%lu'", (unsigned long)moduleID); } return nil; } @@ -691,14 +788,14 @@ - (id)callNativeModule:(NSUInteger)moduleID method:(NSUInteger)methodID params:( NSArray> *methods = [moduleData.methods copy]; if (methodID >= [methods count]) { if (isValid) { - HPLogError(@"methodID %lu exceed range of moduleData.methods %lu, bridge is valid %ld", moduleID, [methods count], (long)isValid); + HippyLogError(@"methodID %lu exceed range of moduleData.methods %lu, bridge is valid %ld", moduleID, [methods count], (long)isValid); } return nil; } id method = methods[methodID]; - if (HP_DEBUG && !method) { + if (HIPPY_DEBUG && !method) { if (isValid) { - HPLogError(@"Unknown methodID: %lu for module: %lu (%@)", (unsigned long)methodID, (unsigned long)moduleID, moduleData.name); + HippyLogError(@"Unknown methodID: %lu for module: %lu (%@)", (unsigned long)methodID, (unsigned long)moduleID, moduleData.name); } return nil; } @@ -723,12 +820,12 @@ - (id)callNativeModule:(NSUInteger)moduleID method:(NSUInteger)methodID params:( } } @catch (NSException *exception) { // Pass on JS exceptions - if ([exception.name hasPrefix:HPFatalExceptionName]) { + if ([exception.name hasPrefix:HippyFatalExceptionName]) { @throw exception; } NSString *message = [NSString stringWithFormat:@"Exception '%@' was thrown while invoking %@ on target %@ with params %@", exception, method.JSMethodName, moduleData.name, params]; - NSError *error = HPErrorWithMessageAndModuleName(message, self.moduleName); + NSError *error = HippyErrorWithMessageAndModuleName(message, self.moduleName); HippyBridgeFatal(error, self); return nil; } @@ -747,12 +844,12 @@ - (id)callNativeModuleName:(NSString *)moduleName methodName:(NSString *)methodN @try { return [method invokeWithBridge:self module:module.instance arguments:params]; } @catch (NSException *exception) { - if ([exception.name hasPrefix:HPFatalExceptionName]) { + if ([exception.name hasPrefix:HippyFatalExceptionName]) { @throw exception; } NSString *message = [NSString stringWithFormat:@"Exception '%@' was thrown while invoking %@ on target %@ with params %@", exception, method.JSMethodName, module.name, params]; - NSError *error = HPErrorWithMessageAndModuleName(message, self.moduleName); + NSError *error = HippyErrorWithMessageAndModuleName(message, self.moduleName); HippyBridgeFatal(error, self); return nil; } @@ -771,12 +868,12 @@ - (void)setupDomManager:(std::shared_ptr)domManager __weak HippyBridge *weakSelf = self; dispatch_block_t block = ^(void){ HippyBridge *strongSelf = weakSelf; - HPAssertParam(domManager); + HippyAssertParam(domManager); if (!strongSelf || !domManager) { return; } - strongSelf->_javaScriptExecutor.pScope->SetDomManager(domManager); - strongSelf->_javaScriptExecutor.pScope->SetRootNode(rootNode); + strongSelf.javaScriptExecutor.pScope->SetDomManager(domManager); + strongSelf.javaScriptExecutor.pScope->SetRootNode(rootNode); #ifdef ENABLE_INSPECTOR auto devtools_data_source = strongSelf->_javaScriptExecutor.pScope->GetDevtoolsDataSource(); if (devtools_data_source) { @@ -802,7 +899,7 @@ - (BOOL)moduleSetupComplete { } - (void)invalidate { - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],%@ invalide %p", NSStringFromClass([self class]), self); + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],%@ invalide %p", NSStringFromClass([self class]), self); if (![self isValid]) { return; } @@ -824,7 +921,7 @@ - (void)invalidate { dispatch_group_enter(group); [self dispatchBlock:^{ @autoreleasepool { - [(id)instance invalidate]; + [(id)instance invalidate]; } dispatch_group_leave(group); } queue:moduleData.methodQueue]; @@ -840,9 +937,6 @@ - (void)invalidate { _startTime = footstone::TimePoint::SystemNow(); self.moduleSemaphore = nil; - if ([HippyBridge currentBridge] == self) { - [HippyBridge setCurrentBridge:nil]; - } dispatch_group_notify(group, dispatch_get_main_queue(), ^{ [jsExecutor executeBlockOnJavaScriptQueue:^{ @autoreleasepool { @@ -878,31 +972,81 @@ - (void)actuallyInvokeCallback:(NSNumber *)cbID arguments:(NSArray *)args { }]; } -- (NSDictionary *)deviceInfo { - //该方法可能从非UI线程调用 + +#pragma mark - DeviceInfo + +- (NSDictionary *)genRawDeviceInfoDict { + // This method may be called from a child thread NSString *iosVersion = [[UIDevice currentDevice] systemVersion]; struct utsname systemInfo; uname(&systemInfo); NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]; NSMutableDictionary *deviceInfo = [NSMutableDictionary dictionary]; - [deviceInfo setValue:@"ios" forKey:@"OS"]; - [deviceInfo setValue:iosVersion forKey:@"OSVersion"]; - [deviceInfo setValue:deviceModel forKey:@"Device"]; - [deviceInfo setValue:HippySDKVersion forKey:@"SDKVersion"]; - [deviceInfo setValue:HippyExportedDimensions() forKey:@"Dimensions"]; - NSString *countryCode = [[HPI18nUtils sharedInstance] currentCountryCode]; - NSString *lanCode = [[HPI18nUtils sharedInstance] currentAppLanguageCode]; - NSWritingDirection direction = [[HPI18nUtils sharedInstance] writingDirectionForCurrentAppLanguage]; - NSDictionary *local = @{@"country": countryCode?:@"unknown", @"language": lanCode?:@"unknown", @"direction": @(direction)}; - [deviceInfo setValue:local forKey:@"Localization"]; - return [NSDictionary dictionaryWithDictionary:deviceInfo]; + [deviceInfo setValue:@"ios" forKey:HippyNativeGlobalKeyOS]; + [deviceInfo setValue:iosVersion forKey:HippyNativeGlobalKeyOSVersion]; + [deviceInfo setValue:deviceModel forKey:HippyNativeGlobalKeyDevice]; + [deviceInfo setValue:HippySDKVersion forKey:HippyNativeGlobalKeySDKVersion]; + + NSString *appVer = [[NSBundle.mainBundle infoDictionary] objectForKey:@"CFBundleShortVersionString"]; + if (appVer) { + [deviceInfo setValue:appVer forKey:HippyNativeGlobalKeyAppVersion]; + } + + if (self.cachedDimensionsInfo) { + [deviceInfo setValue:self.cachedDimensionsInfo forKey:HippyNativeGlobalKeyDimensions]; + } + + NSString *countryCode = [[HippyI18nUtils sharedInstance] currentCountryCode]; + NSString *lanCode = [[HippyI18nUtils sharedInstance] currentAppLanguageCode]; + NSWritingDirection direction = [[HippyI18nUtils sharedInstance] writingDirectionForCurrentAppLanguage]; + NSDictionary *localizaitionInfo = @{ + @"country" : countryCode?:@"unknown", + @"language" : lanCode?:@"unknown", + @"direction" : @(direction) + }; + [deviceInfo setValue:localizaitionInfo forKey:HippyNativeGlobalKeyLocalization]; + [deviceInfo setValue:@([self isOSNightMode]) forKey:HippyNativeGlobalKeyNightMode]; + return deviceInfo; +} + +- (NSDictionary *)deviceInfo { + @synchronized (self) { + if (!_cachedDeviceInfo) { + _cachedDeviceInfo = [self genRawDeviceInfoDict]; + } + return _cachedDeviceInfo; + } } + +#pragma mark - + +static NSString *const hippyOnNightModeChangedEvent = @"onNightModeChanged"; +static NSString *const hippyOnNightModeChangedParam1 = @"NightMode"; +static NSString *const hippyOnNightModeChangedParam2 = @"RootViewTag"; + +- (void)setOSNightMode:(BOOL)isOSNightMode withRootViewTag:(nonnull NSNumber *)rootViewTag { + _isOSNightMode = isOSNightMode; + // Notify to JS Driver Side + // 1. Update global object + [self.javaScriptExecutor updateNativeInfoToHippyGlobalObject:@{ HippyNativeGlobalKeyNightMode: @(isOSNightMode) }]; + + // 2. Send event + NSDictionary *args = @{@"eventName": hippyOnNightModeChangedEvent, + @"extra": @{ hippyOnNightModeChangedParam1 : @(isOSNightMode), + hippyOnNightModeChangedParam2 : rootViewTag } }; + [self.eventDispatcher dispatchEvent:@"EventDispatcher" + methodName:@"receiveNativeEvent" args:args]; +} + + +#pragma mark - + - (NSString *)moduleConfig { NSMutableArray *config = [NSMutableArray new]; for (HippyModuleData *moduleData in [_moduleSetup moduleDataByID]) { NSArray *moduleDataConfig = [moduleData config]; - [config addObject:HPNullIfNil(moduleDataConfig)]; + [config addObject:HippyNullIfNil(moduleDataConfig)]; } id jsonArray = @{ @"remoteModuleConfig": config, @@ -911,10 +1055,10 @@ - (NSString *)moduleConfig { } - (void)setRedBoxShowEnabled:(BOOL)enabled { -#if HP_DEBUG +#if HIPPY_DEBUG HippyRedBox *redBox = [self redBox]; redBox.showEnabled = enabled; -#endif // HP_DEBUG +#endif // HIPPY_DEBUG } - (HippyOCTurboModule *)turboModuleWithName:(NSString *)name { @@ -990,35 +1134,71 @@ - (void)setSnapShotData:(NSData *)data { domManager->SetSnapShot(rootNode, string); } -@end -void HippyBridgeFatal(NSError *error, HippyBridge *bridge) { - HPFatal(error, bridge?@{@"bridge": bridge}:nil); -} +#pragma mark - -void HippyBridgeHandleException(NSException *exception, HippyBridge *bridge) { - HPHandleException(exception, bridge?@{@"bridge": bridge}:nil); -} +//FIXME: 调整优化 +- (void)setRootView:(UIView *)rootView { + auto engineResource = [[HippyJSEnginesMapper defaultInstance] JSEngineResourceForKey:self.engineKey]; + auto domManager = engineResource->GetDomManager(); + NSNumber *rootTag = [rootView hippyTag]; + //Create a RootNode instance with a root tag + _rootNode = std::make_shared([rootTag unsignedIntValue]); + //Set RootNode for AnimationManager in RootNode + _rootNode->GetAnimationManager()->SetRootNode(_rootNode); + //Set DomManager for RootNode + _rootNode->SetDomManager(domManager); + //Set screen scale factor and size for Layout system in RooNode + _rootNode->GetLayoutNode()->SetScaleFactor([UIScreen mainScreen].scale); + _rootNode->SetRootSize(rootView.frame.size.width, rootView.frame.size.height); + _rootNode->SetRootOrigin(rootView.frame.origin.x, rootView.frame.origin.y); + + //set rendermanager for dommanager + if (!domManager->GetRenderManager().lock()) { + domManager->SetRenderManager(_renderManager); + } + //bind rootview and root node + _renderManager->RegisterRootView(rootView, _rootNode); + + __weak HippyBridge *weakBridge = self; + auto cb = [weakBridge](int32_t tag, NSDictionary *params){ + HippyBridge *strongBridge = weakBridge; + if (strongBridge) { + [strongBridge rootViewSizeChangedEvent:@(tag) params:params]; + } + }; + _renderManager->SetRootViewSizeChangedEvent(cb); + //setup necessary params for bridge + [self setupDomManager:domManager rootNode:_rootNode]; +} + +- (void)resetRootSize:(CGSize)size { + auto engineResource = [[HippyJSEnginesMapper defaultInstance] JSEngineResourceForKey:self.engineKey]; + std::weak_ptr rootNode = _rootNode; + auto domManager = engineResource->GetDomManager(); + std::weak_ptr weakDomManager = domManager; + std::vector> ops = {[rootNode, weakDomManager, size](){ + auto strongRootNode = rootNode.lock(); + auto strongDomManager = weakDomManager.lock(); + if (strongRootNode && strongDomManager) { + strongRootNode->SetRootSize(size.width, size.height); + strongDomManager->DoLayout(strongRootNode); + strongDomManager->EndBatch(strongRootNode); + } + }}; + domManager->PostTask(hippy::dom::Scene(std::move(ops))); +} -#pragma mark - -@implementation HippyBridge (RedBoxDebug) -static HippyBridge *HippyCurrentBridgeInstance = nil; +@end -/** - * The last current active bridge instance. This is set automatically whenever - * the bridge is accessed. It can be useful for static functions or singletons - * that need to access the bridge for purposes such as logging, but should not - * be relied upon to return any particular instance, due to race conditions. - */ -+ (instancetype)currentBridge { - return HippyCurrentBridgeInstance; +void HippyBridgeFatal(NSError *error, HippyBridge *bridge) { + HippyFatal(error); } -+ (void)setCurrentBridge:(nullable HippyBridge *)currentBridge { - HippyCurrentBridgeInstance = currentBridge; +void HippyBridgeHandleException(NSException *exception, HippyBridge *bridge) { + HippyHandleException(exception); } -@end diff --git a/framework/ios/base/bridge/HippyBridgeDelegate.h b/framework/ios/base/bridge/HippyBridgeDelegate.h index af18dc1d8eb..2453facd476 100644 --- a/framework/ios/base/bridge/HippyBridgeDelegate.h +++ b/framework/ios/base/bridge/HippyBridgeDelegate.h @@ -22,7 +22,7 @@ @class HippyBridge; -#import "HPInvalidating.h" +#import "HippyInvalidating.h" @protocol HippyBridgeDelegate @@ -77,6 +77,27 @@ * @param reason reson for HippyBridge invalidation, typically reload, or dealloc * @param bridge HippyBridge to be invalidated */ -- (void)invalidateForReason:(HPInvalidateReason)reason bridge:(HippyBridge *)bridge; +- (void)invalidateForReason:(HippyInvalidateReason)reason bridge:(HippyBridge *)bridge; + + +#pragma mark - UI/Layout Related + +/// When return YES, +/// it indicates that you want to use the `viewWillTransitionToSize` method in UIViewController +/// instead of the deprecated UIApplicationDidChangeStatusBarOrientationNotification. +/// +/// Note that you must call `onHostControllerTransitionedToSize` of HippyRootView when size changed. +- (BOOL)shouldUseViewWillTransitionMethodToMonitorOrientation; + +/// The default status bar height when hippy cannot obtained dynamically. +/// +/// Note: In general, the page layout should not depend on `StatusBar` height, +/// Its height is dynamically changed and should be obtained dynamically. +/// This value is only used as a default value if hippy cannot be obtained. +/// +/// Only for compatibility with old code, strongly discouraged. +/// return values less than 0 will be treated as 0. +- (CGFloat)defaultStatusBarHeightNoMatterHiddenOrNot; + @end diff --git a/framework/ios/base/bridge/HippyBridgeModule.h b/framework/ios/base/bridge/HippyBridgeModule.h index 12087bd6567..cfac693dd03 100644 --- a/framework/ios/base/bridge/HippyBridgeModule.h +++ b/framework/ios/base/bridge/HippyBridgeModule.h @@ -21,12 +21,39 @@ */ #import - -#import "MacroDefines.h" +#import "HippyDefines.h" @class HippyBridge; @protocol HippyBridgeMethod; +/** + * The type of a block that is capable of sending a response to a bridged + * operation. Use this for returning callback methods to JS. + */ +typedef void (^HippyResponseSenderBlock)(NSArray *response); + +/** + * The type of a block that is capable of sending an error response to a + * bridged operation. Use this for returning error information to JS. + */ +typedef void (^HippyResponseErrorBlock)(NSError *error); + +/** + * Block that bridge modules use to resolve the JS promise waiting for a result. + * Nil results are supported and are converted to JS's undefined value. + */ +typedef void (^HippyPromiseResolveBlock)(id result); + +/** + * Block that bridge modules use to reject the JS promise waiting for a result. + * The error may be nil but it is preferable to pass an NSError object for more + * precise error messages. + */ +typedef void (^HippyPromiseRejectBlock)(NSString *code, NSString *message, NSError *error); + + +#pragma mark - + /** * This constant can be returned from +methodQueue to force module * methods to be called on the JavaScript thread. This can have serious @@ -49,7 +76,7 @@ extern dispatch_queue_t HippyJSThread; * match the Objective-C class name. */ #define HIPPY_EXPORT_MODULE(js_name) \ - HP_EXTERN void HippyRegisterModule(Class); \ + HIPPY_EXTERN void HippyRegisterModule(Class); \ +(NSString *)moduleName { \ return @ #js_name; \ } \ @@ -198,7 +225,7 @@ extern dispatch_queue_t HippyJSThread; * Like HIPPY_EXTERN_REMAP_METHOD, but allows setting a custom JavaScript name. */ #define HIPPY_EXTERN_REMAP_METHOD(js_name, method) \ - +(NSArray *)HP_CONCAT(__hippy_export__, HP_CONCAT(js_name, HP_CONCAT(__LINE__, __COUNTER__))) { \ + +(NSArray *)HIPPY_CONCAT(__hippy_export__, HIPPY_CONCAT(js_name, HIPPY_CONCAT(__LINE__, __COUNTER__))) { \ return @[@ #js_name, @ #method]; \ } diff --git a/framework/ios/base/enginewrapper/HippyContextWrapper.h b/framework/ios/base/enginewrapper/HippyContextWrapper.h index 7dad8fed62b..261a5bb0108 100644 --- a/framework/ios/base/enginewrapper/HippyContextWrapper.h +++ b/framework/ios/base/enginewrapper/HippyContextWrapper.h @@ -38,13 +38,13 @@ class CtxValue; } } -@class HPDriverStackFrame; +@class HippyJSStackFrame; typedef id __nullable (^FunctionImplementationBlock)(NSArray *arguments); @protocol HippyContextWrapper -typedef void (^ExceptionHandler)(idwrapper, NSString *message, NSArray *stackFrames); +typedef void (^ExceptionHandler)(idwrapper, NSString *message, NSArray *stackFrames); @required diff --git a/framework/ios/base/enginewrapper/jsc/HippyJSCContextWrapper.mm b/framework/ios/base/enginewrapper/jsc/HippyJSCContextWrapper.mm index 75b19e99e6a..538f5e53fe5 100644 --- a/framework/ios/base/enginewrapper/jsc/HippyJSCContextWrapper.mm +++ b/framework/ios/base/enginewrapper/jsc/HippyJSCContextWrapper.mm @@ -23,9 +23,9 @@ #import #import "NSObject+JSValue.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" #import "HippyJSCContextWrapper.h" -#import "HPDriverStackFrame.h" +#import "HippyJSStackFrame.h" #include #include "driver/napi/jsc/jsc_ctx.h" @@ -71,7 +71,7 @@ - (instancetype)initWithContext:(std::weak_ptr)context { self = [super init]; if (self) { auto strongContext = context.lock(); - HPAssert(strongContext, @"context must be available"); + HippyAssert(strongContext, @"context must be available"); if (strongContext) { auto jscontext = std::static_pointer_cast(strongContext); _napiContext = jscontext; @@ -93,9 +93,9 @@ - (instancetype)initWithContext:(std::weak_ptr)context { double lineNumber = JSValueToNumber(contextRef, [exception objectForKeyedSubscript:@"line"].JSValueRef, NULL); double column = JSValueToNumber(contextRef, [exception objectForKeyedSubscript:@"column"].JSValueRef, NULL); NSArray *stacksArray = [stacksString componentsSeparatedByString:@"\n"]; - NSMutableArray *stackFrames = [NSMutableArray arrayWithCapacity:[stacksArray count]]; + NSMutableArray *stackFrames = [NSMutableArray arrayWithCapacity:[stacksArray count]]; for (NSString *line in stacksArray) { - HPDriverStackFrame *stackFrame = [[HPDriverStackFrame alloc] initWithMethodName:line file:@"" lineNumber:lineNumber column:column]; + HippyJSStackFrame *stackFrame = [[HippyJSStackFrame alloc] initWithMethodName:line file:@"" lineNumber:lineNumber column:column]; [stackFrames addObject:stackFrame]; } exceptionHandler(strongSelf, message, [stackFrames copy]); @@ -293,7 +293,7 @@ - (id)callFunction:(NSString *)funcName arguments:(NSArray *)arguments { } JSContext *context = _context; JSValue *batchedbridgeValue = context[@"__hpBatchedBridge"]; - HPAssert(batchedbridgeValue && ![batchedbridgeValue isUndefined] && ![batchedbridgeValue isNull], @"__hpBatchedBridge must not be null or undefined"); + HippyAssert(batchedbridgeValue && ![batchedbridgeValue isUndefined] && ![batchedbridgeValue isNull], @"__hpBatchedBridge must not be null or undefined"); if (!batchedbridgeValue || [batchedbridgeValue isUndefined]) { _context.exception = [JSValue valueWithNewErrorFromMessage:@"cannot find __hpBatchedBridge" inContext:context]; return nil; @@ -344,7 +344,7 @@ - (id)runScript:(NSString *)script - (std::shared_ptr)createNumber:(NSNumber *)number { @autoreleasepool { - HPAssert(number, @"number must not be null"); + HippyAssert(number, @"number must not be null"); if (number) { JSValueRef valueRef = [number toJSValueInContext:_context].JSValueRef; return std::make_shared(_context.JSGlobalContextRef, valueRef); @@ -355,7 +355,7 @@ - (id)runScript:(NSString *)script - (std::shared_ptr)createBool:(NSNumber *)number { @autoreleasepool { - HPAssert(number, @"number must not be null"); + HippyAssert(number, @"number must not be null"); if (number) { JSValueRef valueRef = [number toJSValueInContext:_context].JSValueRef; return std::make_shared(_context.JSGlobalContextRef, valueRef); @@ -366,7 +366,7 @@ - (id)runScript:(NSString *)script - (std::shared_ptr)createString:(NSString *)string { @autoreleasepool { - HPAssert(string, @"string must not be null"); + HippyAssert(string, @"string must not be null"); if (string) { JSValueRef valueRef = [string toJSValueInContext:_context].JSValueRef; return std::make_shared(_context.JSGlobalContextRef, valueRef); @@ -385,7 +385,7 @@ - (id)runScript:(NSString *)script - (std::shared_ptr)createObject:(NSDictionary *)dictionary { @autoreleasepool { - HPAssert(dictionary, @"dictionary must not be null"); + HippyAssert(dictionary, @"dictionary must not be null"); if (dictionary) { JSValueRef valueRef = [dictionary toJSValueInContext:_context].JSValueRef; return std::make_shared(_context.JSGlobalContextRef, valueRef); @@ -396,7 +396,7 @@ - (id)runScript:(NSString *)script - (std::shared_ptr)createObjectFromJsonString:(NSString *)JsonString { @autoreleasepool { - HPAssert(JsonString, @"JsonString must not be null"); + HippyAssert(JsonString, @"JsonString must not be null"); id obj = StringJSONToObject(JsonString); if (obj) { JSValueRef valueRef = [obj toJSValueInContext:_context].JSValueRef; @@ -408,7 +408,7 @@ - (id)runScript:(NSString *)script - (std::shared_ptr)createArray:(NSArray *)array { @autoreleasepool { - HPAssert(array, @"array must not be null"); + HippyAssert(array, @"array must not be null"); if (array) { JSValueRef valueRef = [array toJSValueInContext:_context].JSValueRef; return std::make_shared(_context.JSGlobalContextRef, valueRef); @@ -419,7 +419,7 @@ - (id)runScript:(NSString *)script - (std::shared_ptr)createException:(NSString *)description { @autoreleasepool { - HPAssert(description, @"description must not be null"); + HippyAssert(description, @"description must not be null"); description = description?:@""; JSValueRef arguments[1]; arguments[0] = [description toJSValueInContext:_context].JSValueRef; diff --git a/framework/ios/base/enginewrapper/v8/HippyV8ContextWrapper.mm b/framework/ios/base/enginewrapper/v8/HippyV8ContextWrapper.mm index 871cbad03ec..0fb3414f3b3 100644 --- a/framework/ios/base/enginewrapper/v8/HippyV8ContextWrapper.mm +++ b/framework/ios/base/enginewrapper/v8/HippyV8ContextWrapper.mm @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "HPAsserts.h" -#import "HPLog.h" +#import "HippyAsserts.h" +#import "HippyLog.h" #import "HPDriverStackFrame.h" #import "HippyV8ContextWrapper.h" #import "NSObject+CtxValue.h" @@ -50,9 +50,9 @@ static id StringJSONToObject(NSString *string) { v8::Local context) { auto ctxValue = std::static_pointer_cast(value); v8::Local v8Value = ctxValue->global_value_.Get(context->GetIsolate()); - HPAssert(v8Value->IsObject(), @"value is not a object"); + HippyAssert(v8Value->IsObject(), @"value is not a object"); v8::MaybeLocal maybeObject = v8Value->ToObject(context); - HPAssert(!maybeObject.IsEmpty(), @"maybe object is not a object"); + HippyAssert(!maybeObject.IsEmpty(), @"maybe object is not a object"); return maybeObject.ToLocalChecked(); } @@ -385,7 +385,7 @@ - (BOOL)setProperty:(NSString *)propertyName v8::Local v8Name = [propertyName toV8StringInIsolate:isolate]; v8::MaybeLocal maybeValue = targetObject->Get(localContext, v8Name); if (maybeValue.IsEmpty()) { - HPLog(@"get property %@ for object failed", propertyName); + HippyLog(@"get property %@ for object failed", propertyName); return nullptr; } v8::Local value = maybeValue.ToLocalChecked(); diff --git a/framework/ios/base/executors/HippyJSEnginesMapper.mm b/framework/ios/base/executors/HippyJSEnginesMapper.mm index cea0483ba83..ef6fffaee13 100644 --- a/framework/ios/base/executors/HippyJSEnginesMapper.mm +++ b/framework/ios/base/executors/HippyJSEnginesMapper.mm @@ -21,7 +21,7 @@ */ #import "HippyJSEnginesMapper.h" -#import "HPLog.h" +#import "HippyLog.h" #include "dom/dom_manager.h" #include "driver/engine.h" @@ -125,7 +125,7 @@ - (void)removeEngineResourceForKey:(NSString *)key { EngineRef &ref = it->second; ref.second--; if (0 == ref.second) { - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyJSCExecutor destroy engine %@", key); + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyJSCExecutor destroy engine %@", key); _engineMapper.erase(it); } } diff --git a/framework/ios/base/executors/HippyJSExecutor.h b/framework/ios/base/executors/HippyJSExecutor.h index 3eae9d67f08..98c730c74f4 100644 --- a/framework/ios/base/executors/HippyJSExecutor.h +++ b/framework/ios/base/executors/HippyJSExecutor.h @@ -22,11 +22,17 @@ #import "HippyBridgeModule.h" #import "HippyDefines.h" -#import "MacroDefines.h" -#import "HPInvalidating.h" - +#import "HippyDefines.h" +#import "HippyInvalidating.h" #include + +/** + * Block that when js script execution completion + */ +typedef void (^HippyJavaScriptCallback)(id result, NSError *error); + + namespace hippy { inline namespace driver { @@ -52,12 +58,12 @@ typedef void (^HippyContextCreatedBlock)(id); /** * Default name for the JS thread */ -HP_EXTERN NSString *const HippyJSCThreadName; +HIPPY_EXTERN NSString *const HippyJSCThreadName; /** * Uses a JavaScriptCore context as the execution engine. */ -@interface HippyJSExecutor : NSObject +@interface HippyJSExecutor : NSObject @property (nonatomic, strong) HippyBridge *bridge; @@ -134,4 +140,8 @@ HP_EXTERN NSString *const HippyJSCThreadName; */ - (void)executeAsyncBlockOnJavaScriptQueue:(dispatch_block_t)block; +/// Updated hippy global info +/// - Parameter dict: updated info +- (void)updateNativeInfoToHippyGlobalObject:(NSDictionary *)dict; + @end diff --git a/framework/ios/base/executors/HippyJSExecutor.mm b/framework/ios/base/executors/HippyJSExecutor.mm index ae0ec7e803e..2dd25e4e8db 100644 --- a/framework/ios/base/executors/HippyJSExecutor.mm +++ b/framework/ios/base/executors/HippyJSExecutor.mm @@ -22,10 +22,10 @@ #import #import "VFSUriHandler.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" #import "HippyBundleURLProvider.h" #import "HippyContextWrapper.h" -#import "MacroDefines.h" +#import "HippyDefines.h" #import "HippyDevInfo.h" #import "HippyDevMenu.h" #import "HippyJSEnginesMapper.h" @@ -34,9 +34,9 @@ #import "HippyRedBox.h" #import "HippyUtils.h" #import "HippyTurboModuleManager.h" -#import "HPLog.h" -#import "HPToolUtils.h" -#import "HPFootstoneUtils.h" +#import "HippyLog.h" +#import "HippyUtils.h" +#import "HippyFootstoneUtils.h" #import "NSObject+CtxValue.h" #import "TypeConverter.h" @@ -126,7 +126,7 @@ - (void)setup { auto hippy_key = context->CreateString(kHippyKey); context->SetProperty(global_object, hippy_key, context->CreateObject()); id contextWrapper = CreateContextWrapper(context); - contextWrapper.excpetionHandler = ^(id _Nonnull wrapper, NSString * _Nonnull message, NSArray * _Nonnull stackFrames) { + contextWrapper.excpetionHandler = ^(id _Nonnull wrapper, NSString * _Nonnull message, NSArray * _Nonnull stackFrames) { HippyJSExecutor *strongSelf = weakSelf; if (!strongSelf) { return; @@ -136,17 +136,17 @@ - (void)setup { return; } NSDictionary *userInfo = @{ - HPFatalModuleName: bridge.moduleName?:@"unknown", + HippyFatalModuleName: bridge.moduleName?:@"unknown", NSLocalizedDescriptionKey:message?:@"unknown", - HPJSStackTraceKey:stackFrames + HippyJSStackTraceKey:stackFrames }; - NSError *error = [NSError errorWithDomain:HPErrorDomain code:2 userInfo:userInfo]; + NSError *error = [NSError errorWithDomain:HippyErrorDomain code:2 userInfo:userInfo]; HippyBridgeFatal(error, bridge); }; strongSelf->_contextWrapper = contextWrapper; NSMutableDictionary *deviceInfo = [NSMutableDictionary dictionaryWithDictionary:[bridge deviceInfo]]; NSString *deviceName = [[UIDevice currentDevice] name]; - NSString *clientId = HPMD5Hash([NSString stringWithFormat:@"%@%p", deviceName, strongSelf]); + NSString *clientId = HippyMD5Hash([NSString stringWithFormat:@"%@%p", deviceName, strongSelf]); NSDictionary *debugInfo = @{@"Debug" : @{@"debugClientId" : clientId}}; [deviceInfo addEntriesFromDictionary:debugInfo]; @@ -155,7 +155,7 @@ - (void)setup { if (JSONSerializationError) { NSString *errorString = [NSString stringWithFormat:@"device parse error:%@, deviceInfo:%@", [JSONSerializationError localizedFailureReason], deviceInfo]; - NSError *error = HPErrorWithMessageAndModuleName(errorString, bridge.moduleName); + NSError *error = HippyErrorWithMessageAndModuleName(errorString, bridge.moduleName); HippyBridgeFatal(error, bridge); } NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; @@ -172,7 +172,7 @@ - (void)setup { return nil; } NSArray *result = [bridge configForModuleName:moduleName]; - return HPNullIfNil(result); + return HippyNullIfNil(result); } return nil; }]; @@ -233,17 +233,15 @@ - (void)setup { } - (instancetype)initWithEngineKey:(NSString *)engineKey bridge:(HippyBridge *)bridge { + NSParameterAssert(engineKey.length > 0); if (self = [super init]) { _valid = YES; - // maybe bug in JavaScriptCore: - // JSContextRef held by JSContextGroupRef cannot be deallocated, - // unless JSContextGroupRef is deallocated self.enginekey = engineKey; self.bridge = bridge; self.ready = NO; _pendingCalls = [NSMutableArray arrayWithCapacity:4]; - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyJSCExecutor Init %p, engineKey:%@", self, engineKey); + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyJSCExecutor Init %p, engineKey:%@", self, engineKey); } return self; @@ -264,8 +262,8 @@ - (void)setSandboxDirectory:(NSString *)directory { if (!strongSelf) { return; } - HPAssert(strongSelf.pScope, @"scope must not be null"); - HPAssert(strongSelf.pScope->GetContext(), @"context must not be null"); + HippyAssert(strongSelf.pScope, @"scope must not be null"); + HippyAssert(strongSelf.pScope->GetContext(), @"context must not be null"); auto context = strongSelf.pScope->GetContext(); auto global_object = context->GetGlobalObject(); auto key = context->CreateString("__HIPPYCURDIR__"); @@ -335,11 +333,11 @@ - (void)invalidate { #ifdef ENABLE_INSPECTOR auto devtools_data_source = self.pScope->GetDevtoolsDataSource(); if (devtools_data_source) { - bool reload = self.bridge.invalidateReason == HPInvalidateReasonReload ? true : false; + bool reload = self.bridge.invalidateReason == HippyInvalidateReasonReload ? true : false; devtools_data_source->Destroy(reload); } #endif - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyJSCExecutor invalide %p", self); + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyJSCExecutor invalide %p", self); _valid = NO; #ifdef JS_JSC auto scope = self.pScope; @@ -351,7 +349,7 @@ - (void)invalidate { #endif //JS_JSC self.pScope->WillExit(); self.pScope = nullptr; - NSString *enginekey = [self enginekey]; + NSString *enginekey = self.enginekey; if (!enginekey) { return; } @@ -360,10 +358,6 @@ - (void)invalidate { }); } -- (NSString *)enginekey { - return _enginekey ?: [NSString stringWithFormat:@"%p", self]; -} - - (void)setContextName:(NSString *)contextName { #ifdef JS_JSC if (!contextName) { @@ -381,7 +375,7 @@ - (void)setContextName:(NSString *)contextName { NSString *finalName = [NSString stringWithFormat:@"HippyContext: %@", contextName]; jsc_context->SetName((__bridge CFStringRef)finalName); if (tryCatch->HasCaught()) { - HPLogWarn(@"set context throw exception"); + HippyLogWarn(@"set context throw exception"); } } }]; @@ -411,17 +405,31 @@ - (void)setInspecable:(BOOL)inspectable { } - (void)dealloc { - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyJSCExecutor dealloc %p", self); + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyJSCExecutor dealloc %p", self); [self invalidate]; } +- (void)updateNativeInfoToHippyGlobalObject:(NSDictionary *)updatedInfoDict { + if (updatedInfoDict.count <= 0){ + return; + } + __weak __typeof(self)weakSelf = self; + [self executeBlockOnJavaScriptQueue:^{ + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (!strongSelf || !strongSelf.isValid || nullptr == strongSelf.pScope) { + return; + } + [strongSelf addInfoToGlobalObject:updatedInfoDict.copy]; + }]; +} + -(void)addInfoToGlobalObject:(NSDictionary*)addInfoDict{ string_view str("__HIPPYNATIVEGLOBAL__"); auto context = self.pScope->GetContext(); auto global_object = context->GetGlobalObject(); auto hippy_native_object_key = context->CreateString(str); auto hippy_native_object_value = context->GetProperty(global_object, hippy_native_object_key); - HPAssert(hippy_native_object_value, @"__HIPPYNATIVEGLOBAL__ must not be null"); + HippyAssert(hippy_native_object_value, @"__HIPPYNATIVEGLOBAL__ must not be null"); if (!context->IsNullOrUndefined(hippy_native_object_value)) { for (NSString *key in addInfoDict) { id value = addInfoDict[key]; @@ -455,7 +463,7 @@ - (void)invokeCallbackID:(NSNumber *)cbID arguments:(NSArray *)args callback:(Hi - (void)_executeJSCall:(NSString *)method arguments:(NSArray *)arguments callback:(HippyJavaScriptCallback)onComplete { - HPAssert(onComplete != nil, @"onComplete block should not be nil"); + HippyAssert(onComplete != nil, @"onComplete block should not be nil"); __weak HippyJSExecutor *weakSelf = self; [self executeBlockOnJavaScriptQueue:^{ @autoreleasepool { @@ -491,19 +499,19 @@ - (void)_executeJSCall:(NSString *)method } } else { executeError - = HPErrorWithMessageAndModuleName([NSString stringWithFormat:@"%@ is not a function", method], moduleName); + = HippyErrorWithMessageAndModuleName([NSString stringWithFormat:@"%@ is not a function", method], moduleName); } } else { - executeError = HPErrorWithMessageAndModuleName( + executeError = HippyErrorWithMessageAndModuleName( [NSString stringWithFormat:@"property/function %@ not found in __hpBatchedBridge", method], moduleName); } } else { - executeError = HPErrorWithMessageAndModuleName(@"__hpBatchedBridge not found", moduleName); + executeError = HippyErrorWithMessageAndModuleName(@"__hpBatchedBridge not found", moduleName); } if (!StringViewUtils::IsEmpty(exception) || executeError) { if (!StringViewUtils::IsEmpty(exception)) { NSString *string = StringViewToNSString(exception); - executeError = HPErrorWithMessageAndModuleName(string, moduleName); + executeError = HippyErrorWithMessageAndModuleName(string, moduleName); } } else if (resultValue) { objcValue = ObjectFromCtxValue(context, resultValue); @@ -512,7 +520,7 @@ - (void)_executeJSCall:(NSString *)method } @catch (NSException *exception) { NSString *moduleName = strongSelf.bridge.moduleName?:@"unknown"; NSMutableDictionary *userInfo = [exception.userInfo mutableCopy]?:[NSMutableDictionary dictionary]; - [userInfo setObject:moduleName forKey:HPFatalModuleName]; + [userInfo setObject:moduleName forKey:HippyFatalModuleName]; [userInfo setObject:arguments?:[NSArray array] forKey:@"arguments"]; NSException *reportException = [NSException exceptionWithName:exception.name reason:exception.reason userInfo:userInfo]; HippyBridgeHandleException(reportException, self.bridge); @@ -522,14 +530,14 @@ - (void)_executeJSCall:(NSString *)method } - (void)executeApplicationScript:(NSData *)script sourceURL:(NSURL *)sourceURL onComplete:(HippyJavaScriptCallback)onComplete { - HPAssertParam(script); - HPAssertParam(sourceURL); + HippyAssertParam(script); + HippyAssertParam(sourceURL); __weak HippyJSExecutor* weakSelf = self; [self executeBlockOnJavaScriptQueue:^{ @autoreleasepool { HippyJSExecutor *strongSelf = weakSelf; if (!strongSelf || !strongSelf.isValid) { - onComplete(nil, HPErrorWithMessageAndModuleName(@"jsexecutor is not invalid", strongSelf.bridge.moduleName)); + onComplete(nil, HippyErrorWithMessageAndModuleName(@"jsexecutor is not invalid", strongSelf.bridge.moduleName)); return; } NSError *error = nil; @@ -570,7 +578,7 @@ - (void)executeApplicationScript:(NSData *)script sourceURL:(NSURL *)sourceURL o if (lockSuccess) { [lock unlock]; } - *error = !StringViewUtils::IsEmpty(errorMsg) ? [NSError errorWithDomain:HPErrorDomain code:2 userInfo:@{ + *error = !StringViewUtils::IsEmpty(errorMsg) ? [NSError errorWithDomain:HippyErrorDomain code:2 userInfo:@{ NSLocalizedDescriptionKey: StringViewToNSString(errorMsg)}] : nil; id objcResult = ObjectFromCtxValue(context, result); return objcResult; @@ -605,17 +613,17 @@ - (void)executeAsyncBlockOnJavaScriptQueue:(dispatch_block_t)block { } - (void)injectJSONText:(NSString *)script asGlobalObjectNamed:(NSString *)objectName callback:(HippyJavaScriptCallback)onComplete { - HPAssert(nil != script, @"param 'script' can't be nil"); + HippyAssert(nil != script, @"param 'script' can't be nil"); if (nil == script) { if (onComplete) { NSString *errorMessage = [NSString stringWithFormat:@"param 'script' is nil"]; - NSError *error = [NSError errorWithDomain:HPErrorDomain code:2 userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + NSError *error = [NSError errorWithDomain:HippyErrorDomain code:2 userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; onComplete(@(NO), error); } return; } - if (HP_DEBUG) { - HPAssert(HippyJSONParse(script, NULL) != nil, @"%@ wasn't valid JSON!", script); + if (HIPPY_DEBUG) { + HippyAssert(HippyJSONParse(script, NULL) != nil, @"%@ wasn't valid JSON!", script); } __weak HippyJSExecutor *weakSelf = self; @@ -636,7 +644,7 @@ - (void)injectJSONText:(NSString *)script asGlobalObjectNamed:(NSString *)object context->SetProperty(global_object, name_key, json_value); if (tryCatch->HasCaught()) { string_view errorMsg = tryCatch->GetExceptionMessage(); - NSError *error = [NSError errorWithDomain:HPErrorDomain code:2 userInfo:@{ + NSError *error = [NSError errorWithDomain:HippyErrorDomain code:2 userInfo:@{ NSLocalizedDescriptionKey: StringViewToNSString(errorMsg)}]; onComplete(@(NO), error); } @@ -669,7 +677,7 @@ - (NSString *)completeWSURLWithBridge:(HippyBridge *)bridge { devInfo.wsURL = bundleURLProvider.wsURL; } NSString *deviceName = [[UIDevice currentDevice] name]; - NSString *clientId = HPMD5Hash([NSString stringWithFormat:@"%@%p", deviceName, bridge]); + NSString *clientId = HippyMD5Hash([NSString stringWithFormat:@"%@%p", deviceName, bridge]); return [devInfo assembleFullWSURLWithClientId:clientId contextName:bridge.contextName]; } diff --git a/framework/ios/base/modules/HippyEventDispatcher.h b/framework/ios/base/modules/HippyEventDispatcher.h index 4fbc55b6d83..065474e1760 100644 --- a/framework/ios/base/modules/HippyEventDispatcher.h +++ b/framework/ios/base/modules/HippyEventDispatcher.h @@ -28,14 +28,14 @@ * The threshold at which text inputs will start warning that the JS thread * has fallen behind (resulting in poor input performance, missed keys, etc.) */ -HP_EXTERN const NSInteger HippyTextUpdateLagWarningThreshold; +HIPPY_EXTERN const NSInteger HippyTextUpdateLagWarningThreshold; /** * Takes an input event name and normalizes it to the form that is required * by the events system (currently that means starting with the "top" prefix, * but that's an implementation detail that may change in future). */ -HP_EXTERN NSString *HippyNormalizeInputEventName(NSString *eventName); +HIPPY_EXTERN NSString *HippyNormalizeInputEventName(NSString *eventName); /** * This class wraps the -[HippyBridge enqueueJSCall:args:] method, and diff --git a/framework/ios/base/modules/HippyEventDispatcher.mm b/framework/ios/base/modules/HippyEventDispatcher.mm index fcaae57cb24..029ad65cf73 100644 --- a/framework/ios/base/modules/HippyEventDispatcher.mm +++ b/framework/ios/base/modules/HippyEventDispatcher.mm @@ -21,8 +21,8 @@ */ #import "HippyEventDispatcher.h" -#import "HPAsserts.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" const NSInteger HippyTextUpdateLagWarningThreshold = 3; diff --git a/framework/ios/base/modules/HippyModuleData.h b/framework/ios/base/modules/HippyModuleData.h index 5466dd47315..e481a26d66d 100644 --- a/framework/ios/base/modules/HippyModuleData.h +++ b/framework/ios/base/modules/HippyModuleData.h @@ -22,13 +22,13 @@ #import -#import "HPInvalidating.h" +#import "HippyInvalidating.h" @protocol HippyBridgeMethod; @protocol HippyBridgeModule; @class HippyBridge; -@interface HippyModuleData : NSObject +@interface HippyModuleData : NSObject - (instancetype)initWithModuleClass:(Class)moduleClass bridge:(HippyBridge *)bridge; diff --git a/framework/ios/base/modules/HippyModuleData.mm b/framework/ios/base/modules/HippyModuleData.mm index 01daa96e053..02c53834502 100644 --- a/framework/ios/base/modules/HippyModuleData.mm +++ b/framework/ios/base/modules/HippyModuleData.mm @@ -23,9 +23,9 @@ #import "HippyModuleData.h" #import "HippyBridge.h" #import "HippyModuleMethod.h" -#import "HPAsserts.h" -#import "HPLog.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyLog.h" +#import "HippyUtils.h" #import @@ -59,7 +59,7 @@ - (void)setUp { // If a module overrides `constantsToExport` then we must assume that it // must be called on the main thread, because it may need to access UIKit. - _hasConstantsToExport = HPClassOverridesInstanceMethod(_moduleClass, @selector(constantsToExport)); + _hasConstantsToExport = HippyClassOverridesInstanceMethod(_moduleClass, @selector(constantsToExport)); _instanceSem = dispatch_semaphore_create(1); } @@ -93,8 +93,8 @@ - (void)setUpInstanceAndBridge { // so ModuleData needs to be valid if (!_setupComplete) { if (!_instance) { - if (HP_DEBUG && _requiresMainQueueSetup) { - HPAssertMainQueue(); + if (HIPPY_DEBUG && _requiresMainQueueSetup) { + HippyAssertMainQueue(); } _instance = [_moduleClass new]; if (!_instance) { @@ -102,7 +102,7 @@ - (void)setUpInstanceAndBridge { // of the module is not supported, and it is supposed to be passed in to // the bridge constructor. Mark setup complete to avoid doing more work. _setupComplete = YES; - HPLogWarn(@"The module %@ is returning nil from its constructor. You " + HippyLogWarn(@"The module %@ is returning nil from its constructor. You " "may need to instantiate it yourself and pass it into the " "bridge.", _moduleClass); @@ -142,7 +142,7 @@ - (void)setBridgeForInstance { @try { [(id)_instance setValue:_bridge forKey:@"bridge"]; } @catch (NSException *exception) { - HPLogError(@"%@ has no setter or ivar for its bridge, which is not " + HippyLogError(@"%@ has no setter or ivar for its bridge, which is not " "permitted. You must either @synthesize the bridge property, " "or provide your own setter method.", self.name); @@ -180,7 +180,7 @@ - (void)setUpMethodQueue { @try { [(id)_instance setValue:[self methodQueueWithoutInstance] forKey:@"methodQueue"]; } @catch (NSException *exception) { - HPLogError(@"%@ is returning nil for its methodQueue, which is not " + HippyLogError(@"%@ is returning nil for its methodQueue, which is not " "permitted. You must either return a pre-initialized " "queue, or @synthesize the methodQueue to let the bridge " "create a queue for you.", @@ -204,10 +204,10 @@ - (BOOL)hasInstance { // calls out to other threads, however we can't control when a module might // get accessed by client code during bridge setup, and a very low risk of // deadlock is better than a fairly high risk of an assertion being thrown. - if (!HPIsMainQueue()) { - HPLogWarn(@"HippyBridge required dispatch_sync to load %@. This may lead to deadlocks", _moduleClass); + if (!HippyIsMainQueue()) { + HippyLogWarn(@"HippyBridge required dispatch_sync to load %@. This may lead to deadlocks", _moduleClass); } - HPExecuteOnMainQueue(^{ + HippyExecuteOnMainQueue(^{ [self setUpInstanceAndBridge]; }); } else { @@ -259,10 +259,10 @@ - (NSString *)name { - (void)gatherConstants { if (_hasConstantsToExport && !_constantsToExport) { (void)[self instance]; - if (!HPIsMainQueue()) { - HPLogWarn(@"Required dispatch_sync to load constants for %@. This may lead to deadlocks", _moduleClass); + if (!HippyIsMainQueue()) { + HippyLogWarn(@"Required dispatch_sync to load constants for %@. This may lead to deadlocks", _moduleClass); } - HPExecuteOnMainQueue(^{ + HippyExecuteOnMainQueue(^{ self->_constantsToExport = [self->_instance constantsToExport] ?: @ {}; }); } @@ -295,7 +295,7 @@ - (NSArray *)config { [methods addObject:method.JSMethodName]; } - NSArray *config = @[self.name, HPNullIfNil(constants), HPNullIfNil(methods), HPNullIfNil(promiseMethods), HPNullIfNil(syncMethods)]; + NSArray *config = @[self.name, HippyNullIfNil(constants), HippyNullIfNil(methods), HippyNullIfNil(promiseMethods), HippyNullIfNil(syncMethods)]; return config; } diff --git a/framework/ios/base/modules/HippyModuleMethod.mm b/framework/ios/base/modules/HippyModuleMethod.mm index eac41f21722..f753230df47 100644 --- a/framework/ios/base/modules/HippyModuleMethod.mm +++ b/framework/ios/base/modules/HippyModuleMethod.mm @@ -24,11 +24,11 @@ #import "HippyBridge.h" #import "HippyTurboModuleManager.h" #import "HippyUtils.h" -#import "HPAsserts.h" -#import "HPConvert.h" -#import "HPLog.h" -#import "HPParserUtils.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyConvert.h" +#import "HippyLog.h" +#import "HippyParserUtils.h" +#import "HippyUtils.h" #include @@ -62,9 +62,9 @@ @implementation HippyModuleMethod { @synthesize arguments = _arguments; -static void HPLogArgumentError( +static void HippyLogArgumentError( __unused HippyModuleMethod *method, __unused NSUInteger index, __unused id valueOrType, __unused const char *issue) { - HPLogError(nil, + HippyLogError(nil, @"Argument %tu (%@) of %@.%@ %s", index, valueOrType, HippyBridgeModuleNameForClass(method->_moduleClass), method.JSMethodName, issue); } @@ -72,36 +72,36 @@ static void HPLogArgumentError( // least one argument, and maybe more selector parts) or NO if it doesn't. static BOOL HippyParseSelectorPart(const char **input, NSMutableString *selector) { NSString *selectorPart; - if (HPParseIdentifier(input, &selectorPart)) { + if (HippyParseIdentifier(input, &selectorPart)) { [selector appendString:selectorPart]; } - HPParseSkipWhitespace(input); - if (HPParseReadChar(input, ':')) { + HippySkipWhitespace(input); + if (HippyReadChar(input, ':')) { [selector appendString:@":"]; - HPParseSkipWhitespace(input); + HippySkipWhitespace(input); return YES; } return NO; } static BOOL HippyParseUnused(const char **input) { - return HPParseReadString(input, "__unused") || HPParseReadString(input, "__attribute__((unused))") - || HPParseReadString(input, "__attribute__((__unused__))"); + return HippyReadString(input, "__unused") || HippyReadString(input, "__attribute__((unused))") + || HippyReadString(input, "__attribute__((__unused__))"); } static HippyNullability HippyParseNullability(const char **input) { - if (HPParseReadString(input, "nullable")) { + if (HippyReadString(input, "nullable")) { return HippyNullable; - } else if (HPParseReadString(input, "nonnull")) { + } else if (HippyReadString(input, "nonnull")) { return HippyNonnullable; } return HippyNullabilityUnspecified; } static HippyNullability HippyParseNullabilityPostfix(const char **input) { - if (HPParseReadString(input, "_Nullable")) { + if (HippyReadString(input, "_Nullable")) { return HippyNullable; - } else if (HPParseReadString(input, "_Nonnull")) { + } else if (HippyReadString(input, "_Nonnull")) { return HippyNonnullable; } return HippyNullabilityUnspecified; @@ -110,7 +110,7 @@ static HippyNullability HippyParseNullabilityPostfix(const char **input) { SEL HippyParseMethodSignature(NSString *, NSArray **); SEL HippyParseMethodSignature(NSString *methodSignature, NSArray **arguments) { const char *input = methodSignature.UTF8String; - HPParseSkipWhitespace(&input); + HippySkipWhitespace(&input); NSMutableArray *args; NSMutableString *selector = [NSMutableString new]; @@ -120,32 +120,32 @@ SEL HippyParseMethodSignature(NSString *methodSignature, NSArray *arguments; _selector = HippyParseMethodSignature(_methodSignature, &arguments); _arguments = [arguments copy]; - HPAssert(_selector, @"%@ is not a valid selector", _methodSignature); + HippyAssert(_selector, @"%@ is not a valid selector", _methodSignature); // Create method invocation NSMethodSignature *methodSignature = [_moduleClass instanceMethodSignatureForSelector:_selector]; - HPAssert(methodSignature, @"%@ is not a recognized Objective-C method.", _methodSignature); + HippyAssert(methodSignature, @"%@ is not a recognized Objective-C method.", _methodSignature); NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; invocation.selector = _selector; _invocation = invocation; @@ -194,8 +194,8 @@ - (void)processMethodSignature { __weak HippyModuleMethod *weakSelf = self; void (^addBlockArgument)(void) = ^{ - HIPPY_ARG_BLOCK(if (HP_DEBUG && json && ![json isKindOfClass:[NSNumber class]]) { - HPLogArgumentError(weakSelf, index, json, "should be a function"); + HIPPY_ARG_BLOCK(if (HIPPY_DEBUG && json && ![json isKindOfClass:[NSNumber class]]) { + HippyLogArgumentError(weakSelf, index, json, "should be a function"); return NO; } __weak HippyBridge *weakBridge = bridge; @@ -225,13 +225,13 @@ - (void)processMethodSignature { BOOL isNullableType = NO; HippyMethodArgument *argument = arguments[i - 2]; NSString *typeName = argument.type; - SEL selector = HPConvertSelectorForType(typeName); - if ([HPConvert respondsToSelector:selector]) { + SEL selector = HippyConvertSelectorForType(typeName); + if ([HippyConvert respondsToSelector:selector]) { switch (objcType[0]) { #define HIPPY_CASE(_value, _type) \ case _value: { \ _type (*convert)(id, SEL, id) = (__typeof(convert))objc_msgSend; \ - HIPPY_ARG_BLOCK(_type value = convert([HPConvert class], selector, json);)\ + HIPPY_ARG_BLOCK(_type value = convert([HippyConvert class], selector, json);)\ break; \ } @@ -253,7 +253,7 @@ - (void)processMethodSignature { case _value: { \ isNullableType = YES; \ _type (*convert)(id, SEL, id) = (__typeof(convert))objc_msgSend; \ - HIPPY_ARG_BLOCK(_type value = convert([HPConvert class], selector, json);) \ + HIPPY_ARG_BLOCK(_type value = convert([HippyConvert class], selector, json);) \ break; \ } @@ -264,15 +264,15 @@ - (void)processMethodSignature { case _C_ID: { isNullableType = YES; id (*convert)(id, SEL, id) = (__typeof(convert))objc_msgSend; - HIPPY_ARG_BLOCK(id value = convert([HPConvert class], selector, json); CFBridgingRetain(value);) + HIPPY_ARG_BLOCK(id value = convert([HippyConvert class], selector, json); CFBridgingRetain(value);) break; } case _C_STRUCT_B: { - NSMethodSignature *typeSignature = [HPConvert methodSignatureForSelector:selector]; + NSMethodSignature *typeSignature = [HippyConvert methodSignatureForSelector:selector]; NSInvocation *typeInvocation = [NSInvocation invocationWithMethodSignature:typeSignature]; typeInvocation.selector = selector; - typeInvocation.target = [HPConvert class]; + typeInvocation.target = [HippyConvert class]; [argumentBlocks addObject:^(__unused HippyBridge *bridge, NSUInteger index, id json) { void *returnValue = malloc(typeSignature.methodReturnLength); @@ -292,7 +292,7 @@ - (void)processMethodSignature { if (!strcmp(objcType, blockType)) { addBlockArgument(); } else { - HPLogError(nil, @"Unsupported argument type '%@' in method %@.", typeName, [self methodName]); + HippyLogError(nil, @"Unsupported argument type '%@' in method %@.", typeName, [self methodName]); } } } @@ -301,8 +301,8 @@ - (void)processMethodSignature { } else if ([typeName isEqualToString:@"HippyResponseErrorBlock"]) { HIPPY_ARG_BLOCK( - if (HP_DEBUG && json && ![json isKindOfClass:[NSNumber class]]) { - HPLogArgumentError(weakSelf, index, json, "should be a function"); + if (HIPPY_DEBUG && json && ![json isKindOfClass:[NSNumber class]]) { + HippyLogArgumentError(weakSelf, index, json, "should be a function"); return NO; } __weak HippyBridge *weakBridge = bridge; @@ -327,9 +327,9 @@ - (void)processMethodSignature { } });) } else if ([typeName isEqualToString:@"HippyPromiseResolveBlock"]) { - HPAssert(i == numberOfArguments - 2, @"The HippyPromiseResolveBlock must be the second to last parameter in -[%@ %@]", _moduleClass, _methodSignature); - HIPPY_ARG_BLOCK(if (HP_DEBUG && ![json isKindOfClass:[NSNumber class]]) { - HPLogArgumentError(weakSelf, index, json, "should be a promise resolver function"); + HippyAssert(i == numberOfArguments - 2, @"The HippyPromiseResolveBlock must be the second to last parameter in -[%@ %@]", _moduleClass, _methodSignature); + HIPPY_ARG_BLOCK(if (HIPPY_DEBUG && ![json isKindOfClass:[NSNumber class]]) { + HippyLogArgumentError(weakSelf, index, json, "should be a promise resolver function"); return NO; } __weak HippyBridge *weakBridge = bridge; @@ -354,10 +354,10 @@ - (void)processMethodSignature { } });) } else if ([typeName isEqualToString:@"HippyPromiseRejectBlock"]) { - HPAssert( + HippyAssert( i == numberOfArguments - 1, @"The HippyPromiseRejectBlock must be the last parameter in -[%@ %@]", _moduleClass, _methodSignature); - HIPPY_ARG_BLOCK(if (HP_DEBUG && ![json isKindOfClass:[NSNumber class]]) { - HPLogArgumentError(weakSelf, index, json, "should be a promise rejecter function"); + HIPPY_ARG_BLOCK(if (HIPPY_DEBUG && ![json isKindOfClass:[NSNumber class]]) { + HippyLogArgumentError(weakSelf, index, json, "should be a promise rejecter function"); return NO; } __weak HippyBridge *weakBridge = bridge; @@ -390,16 +390,16 @@ - (void)processMethodSignature { }]; } else { // Unknown argument type - HPLogError(nil, @"Unknown argument type '%@' in method %@. Extend HippyConvert" + HippyLogError(nil, @"Unknown argument type '%@' in method %@. Extend HippyConvert" " to support this type.", typeName, [self methodName]); } - if (HP_DEBUG) { + if (HIPPY_DEBUG) { HippyNullability nullability = argument.nullability; if (!isNullableType) { if (nullability == HippyNullable) { - HPLogArgumentError(weakSelf, i - 2, typeName, + HippyLogArgumentError(weakSelf, i - 2, typeName, "is marked as " "nullable, but is not a nullable type."); } @@ -413,7 +413,7 @@ - (void)processMethodSignature { if ([typeName isEqualToString:@"NSNumber"]) { BOOL unspecified = (nullability == HippyNullabilityUnspecified); if (!argument.unused && (nullability == HippyNullable || unspecified)) { - HPLogArgumentError(weakSelf, i - 2, typeName, + HippyLogArgumentError(weakSelf, i - 2, typeName, [unspecified ? @"has unspecified nullability" : @"is marked as nullable" stringByAppendingString:@" but Hippy requires that all NSNumber " "arguments are explicitly marked as `nonnull` to ensure " @@ -441,7 +441,7 @@ - (void)processMethodSignature { } return YES; } - HPLogArgumentError(weakSelf, index, typeName, "must not be null"); + HippyLogArgumentError(weakSelf, index, typeName, "must not be null"); return NO; }; } @@ -468,7 +468,7 @@ - (NSString *)JSMethodName { } methodName = [methodName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; _JSMethodName = methodName; - HPAssert(methodName.length, + HippyAssert(methodName.length, @"%@ is not a valid JS function name, please" " supply an alternative using HIPPY_REMAP_METHOD()", _methodSignature); @@ -492,9 +492,9 @@ - (id)invokeWithBridge:(HippyBridge *)bridge module:(id)module arguments:(NSArra if (_argumentBlocks == nil) { [self processMethodSignature]; } - if (HP_DEBUG) { + if (HIPPY_DEBUG) { // Sanity check - HPAssert([module class] == _moduleClass, @"Attempted to invoke method \ + HippyAssert([module class] == _moduleClass, @"Attempted to invoke method \ %@ on a module of class %@", [self methodName], [module class]); // Safety check @@ -508,7 +508,7 @@ - (id)invokeWithBridge:(HippyBridge *)bridge module:(id)module arguments:(NSArra expectedCount -= 2; } - HPLogError(@"%@.%@ was called with %ld arguments, but expects %ld. \ + HippyLogError(@"%@.%@ was called with %ld arguments, but expects %ld. \ If you haven\'t changed this method " @"yourself, this usually means that \ your versions of the native code and JavaScript code are out " @@ -527,9 +527,9 @@ - (id)invokeWithBridge:(HippyBridge *)bridge module:(id)module arguments:(NSArra break; } HippyArgumentBlock block = _argumentBlocks[index]; - if (!block(bridge, index, HPNilIfNull(json))) { + if (!block(bridge, index, HippyNilIfNull(json))) { // Invalid argument, abort - HPLogArgumentError(self, index, json, "could not be processed. Aborting method call."); + HippyLogArgumentError(self, index, json, "could not be processed. Aborting method call."); return nil; } index++; @@ -538,7 +538,7 @@ - (id)invokeWithBridge:(HippyBridge *)bridge module:(id)module arguments:(NSArra // Invoke method [_invocation invokeWithTarget:module]; - HPAssert(@encode(HippyArgumentBlock)[0] == _C_ID, + HippyAssert(@encode(HippyArgumentBlock)[0] == _C_ID, @"Block type encoding has changed, it won't be released. A check for the block" "type encoding (%s) has to be added below.", @encode(HippyArgumentBlock)); diff --git a/framework/ios/base/modules/HippyModulesSetup.h b/framework/ios/base/modules/HippyModulesSetup.h index c3568abcca0..27effbd7181 100644 --- a/framework/ios/base/modules/HippyModulesSetup.h +++ b/framework/ios/base/modules/HippyModulesSetup.h @@ -23,15 +23,15 @@ #import #import "HippyBridgeModule.h" -#import "MacroDefines.h" -#import "HPInvalidating.h" +#import "HippyDefines.h" +#import "HippyInvalidating.h" NS_ASSUME_NONNULL_BEGIN -HP_EXTERN NSArray *HippyGetModuleClasses(void); +HIPPY_EXTERN NSArray *HippyGetModuleClasses(void); -#if HP_DEBUG -HP_EXTERN void HippyVerifyAllModulesExported(NSArray *extraModules); +#if HIPPY_DEBUG +HIPPY_EXTERN void HippyVerifyAllModulesExported(NSArray *extraModules); #endif /** @@ -46,7 +46,7 @@ typedef NSArray> *_Nullable(^HippyBridgeModuleProviderBloc @class HippyBridge, HippyModuleData, HippyModuleData; -@interface HippyModulesSetup : NSObject +@interface HippyModulesSetup : NSObject @property(nonatomic, copy, readonly) HippyBridgeModuleProviderBlock moduleProvider; diff --git a/framework/ios/base/modules/HippyModulesSetup.mm b/framework/ios/base/modules/HippyModulesSetup.mm index 1f0a06fec43..79dc84cb8b2 100644 --- a/framework/ios/base/modules/HippyModulesSetup.mm +++ b/framework/ios/base/modules/HippyModulesSetup.mm @@ -20,13 +20,13 @@ * limitations under the License. */ -#import "HPAsserts.h" +#import "HippyAsserts.h" #import "HippyBridge.h" #import "HippyModuleData.h" #import "HippyModulesSetup.h" #import "HippyTurboModule.h" -#import "HPLog.h" -#import "HPToolUtils.h" +#import "HippyLog.h" +#import "HippyUtils.h" #include "objc/runtime.h" @@ -39,16 +39,17 @@ * Register the given class as a bridge module. All modules must be registered * prior to the first bridge initialization. */ -HP_EXTERN void HippyRegisterModule(Class); +HIPPY_EXTERN void HippyRegisterModule(Class); void HippyRegisterModule(Class moduleClass) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ HippyModuleClasses = [NSMutableArray new]; }); - HPAssert([moduleClass conformsToProtocol:@protocol(HippyBridgeModule)], @"%@ does not conform to the HippyBridgeModule protocol", moduleClass); + HippyAssert([moduleClass conformsToProtocol:@protocol(HippyBridgeModule)], + @"%@ does not conform to the HippyBridgeModule protocol", moduleClass); - // Register module + // Register module (including viewManagers) [HippyModuleClasses addObject:moduleClass]; } @@ -56,8 +57,8 @@ void HippyRegisterModule(Class moduleClass) { * This function returns the module name for a given class. */ NSString *HippyBridgeModuleNameForClass(Class cls) { -#if HP_DEBUG - HPAssert([cls conformsToProtocol:@protocol(HippyBridgeModule)] || [cls conformsToProtocol:@protocol(HippyTurboModule)], +#if HIPPY_DEBUG + HippyAssert([cls conformsToProtocol:@protocol(HippyBridgeModule)] || [cls conformsToProtocol:@protocol(HippyTurboModule)], @"Bridge module `%@` does not conform to HippyBridgeModule or HippyTurboModule", cls); #endif NSString *name = nil; @@ -80,7 +81,7 @@ void HippyRegisterModule(Class moduleClass) { return name; } -#if HP_DEBUG +#if HIPPY_DEBUG void HippyVerifyAllModulesExported(NSArray *extraModules) { // Check for unexported modules unsigned int classCount; @@ -110,7 +111,7 @@ void HippyVerifyAllModulesExported(NSArray *extraModules) { if (isModuleSuperClass) { break; } - HPLogWarn(@"Class %@ was not exported. Did you forget to use HIPPY_EXPORT_MODULE()?", cls); + HippyLogWarn(@"Class %@ was not exported. Did you forget to use HIPPY_EXPORT_MODULE()?", cls); break; } superclass = class_getSuperclass(superclass); @@ -156,33 +157,33 @@ - (HippyBridgeModuleProviderBlock)moduleProvider { } - (void)setupModulesCompletion:(dispatch_block_t)completion { - HPLogInfo(@"Begin Modules Setup"); + HippyLogInfo(@"Begin Modules Setup"); NSArray> *extraModules = _providerBlock ? _providerBlock() : @[]; -#if HP_DEBUG +#if HIPPY_DEBUG static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ HippyVerifyAllModulesExported(extraModules); }); -#endif //HP_DEBUG +#endif //HIPPY_DEBUG NSMutableArray *moduleClassesByID = [NSMutableArray new]; NSMutableArray *moduleDataByID = [NSMutableArray new]; NSMutableDictionary *moduleDataByName = [NSMutableDictionary new]; - for (id module in extraModules) { - Class moduleClass = [module class]; + for (id extraModule in extraModules) { + Class moduleClass = [extraModule class]; NSString *moduleName = HippyBridgeModuleNameForClass(moduleClass); - if (HP_DEBUG) { + if (HIPPY_DEBUG) { // Check for name collisions between preregistered modules HippyModuleData *moduleData = moduleDataByName[moduleName]; if (moduleData) { - HPLogError(@"Attempted to register HippyBridgeModule class %@ for the " + HippyLogError(@"Attempted to register HippyBridgeModule class %@ for the " "name '%@', but name was already registered by class %@", moduleClass, moduleName, moduleData.moduleClass); continue; } } // Instantiate moduleData container - HippyModuleData *moduleData = [[HippyModuleData alloc] initWithModuleInstance:module bridge:_bridge]; + HippyModuleData *moduleData = [[HippyModuleData alloc] initWithModuleInstance:extraModule bridge:_bridge]; moduleDataByName[moduleName] = moduleData; [moduleClassesByID addObject:moduleClass]; [moduleDataByID addObject:moduleData]; @@ -201,7 +202,7 @@ - (void)setupModulesCompletion:(dispatch_block_t)completion { continue; } else if ([moduleData.moduleClass new] != nil) { // Both modules were non-nil, so it's unclear which should take precedence - HPLogError(@"Attempted to register HippyBridgeModule class %@ for the " + HippyLogError(@"Attempted to register HippyBridgeModule class %@ for the " "name '%@', but name was already registered by class %@", moduleClass, moduleName, moduleData.moduleClass); } @@ -219,7 +220,7 @@ - (void)setupModulesCompletion:(dispatch_block_t)completion { _moduleClassesByID = [moduleClassesByID copy]; [self prepareModules]; self.moduleSetupComplete = YES; - HPLogInfo(@"End Modules Setup"); + HippyLogInfo(@"End Modules Setup"); if (completion) { completion(); } @@ -241,7 +242,7 @@ - (void)prepareModules { (void)[moduleData instance]; [moduleData gatherConstants]; }; - if (HPIsMainQueue()) { + if (HippyIsMainQueue()) { block(); } else { dispatch_async(dispatch_get_main_queue(), block); @@ -266,13 +267,13 @@ - (void)prepareModules { } - (id)moduleForName:(NSString *)moduleName { - HPAssert(moduleName, @"module name must not be null for [HippyModulesSetup moduleForName:]"); + HippyAssert(moduleName, @"module name must not be null for [HippyModulesSetup moduleForName:]"); id module = _moduleDataByName[moduleName].instance; return module; } - (id)moduleForClass:(Class)cls { - HPAssert(cls, @"class must not be null for [HippyModulesSetup moduleForClass:]"); + HippyAssert(cls, @"class must not be null for [HippyModulesSetup moduleForClass:]"); return [self moduleForName:HippyBridgeModuleNameForClass(cls)]; } diff --git a/framework/ios/debug/websocket/HippySRWebSocket.m b/framework/ios/debug/websocket/HippySRWebSocket.m index 62a2ea2ccdd..d05094e0c41 100644 --- a/framework/ios/debug/websocket/HippySRWebSocket.m +++ b/framework/ios/debug/websocket/HippySRWebSocket.m @@ -22,8 +22,8 @@ #import -#import "HPAsserts.h" -#import "HPLog.h" +#import "HippyAsserts.h" +#import "HippyLog.h" #import "HippySRSIMDHelpers.h" typedef NS_ENUM(NSInteger, HippySROpCode) { @@ -50,7 +50,7 @@ typedef NS_ENUM(NSInteger, HippySROpCode) { //#define HippySR_ENABLE_LOG #ifdef HippySR_ENABLE_LOG -#define HippySRLog(format...) HPLogInfo(format) +#define HippySRLog(format...) HippyLogInfo(format) #else #define HippySRLog(...) \ do { \ @@ -257,7 +257,7 @@ + (void)initialize; { CRLFCRLF = [[NSData alloc] initWithBytes:"\r\n\r\n" length:4]; } - (instancetype)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols { - HPAssertParam(request); + HippyAssertParam(request); if ((self = [super init])) { _url = request.URL; @@ -371,7 +371,7 @@ - (void)setReadyState:(HippySRReadyState)aReadyState; - (void)open; { assert(_url); - HPAssert(_readyState == HippySR_CONNECTING, @"Cannot call -(void)open on HippySRWebSocket more than once"); + HippyAssert(_readyState == HippySR_CONNECTING, @"Cannot call -(void)open on HippySRWebSocket more than once"); _selfRetain = self; @@ -676,7 +676,7 @@ - (void)_writeData:(NSData *)data; - (void)send:(id)data; { - HPAssert(self.readyState != HippySR_CONNECTING, @"Invalid State: Cannot call send: until connection is open"); + HippyAssert(self.readyState != HippySR_CONNECTING, @"Invalid State: Cannot call send: until connection is open"); // TODO: maybe not copy this for performance data = [data copy]; dispatch_async(_workQueue, ^{ @@ -694,7 +694,7 @@ - (void)send:(id)data; - (void)sendPing:(NSData *)data; { - HPAssert(self.readyState == HippySR_OPEN, @"Invalid State: Cannot call send: until connection is open"); + HippyAssert(self.readyState == HippySR_OPEN, @"Invalid State: Cannot call send: until connection is open"); // TODO: maybe not copy this for performance data = [data copy] ?: [NSData data]; // It's okay for a ping to be empty dispatch_async(_workQueue, ^{ diff --git a/framework/ios/debug/websocket/HippyWebSocketManager.m b/framework/ios/debug/websocket/HippyWebSocketManager.m index ad20d48b653..44b0be3db63 100644 --- a/framework/ios/debug/websocket/HippyWebSocketManager.m +++ b/framework/ios/debug/websocket/HippyWebSocketManager.m @@ -20,10 +20,10 @@ * limitations under the License. */ -#import "MacroDefines.h" +#import "HippyDefines.h" #import "HippyWebSocketManager.h" -#import "HPConvert.h" -#import "HPToolUtils.h" +#import "HippyConvert.h" +#import "HippyUtils.h" #import "HippySRWebSocket.h" #import "HippyDefines.h" diff --git a/framework/ios/debug/websocket/HippyWebSocketProxy.h b/framework/ios/debug/websocket/HippyWebSocketProxy.h index 220230c2929..7f035699105 100644 --- a/framework/ios/debug/websocket/HippyWebSocketProxy.h +++ b/framework/ios/debug/websocket/HippyWebSocketProxy.h @@ -20,9 +20,9 @@ * limitations under the License. */ -#import "MacroDefines.h" +#import "HippyDefines.h" -#if HP_DEV // Only supported in dev mode +#if HIPPY_DEV // Only supported in dev mode #import "HippyWebSocketProxyDelegate.h" diff --git a/framework/ios/debug/websocket/HippyWebSocketProxyDelegate.h b/framework/ios/debug/websocket/HippyWebSocketProxyDelegate.h index 54cec835c56..e4e7b2c913f 100644 --- a/framework/ios/debug/websocket/HippyWebSocketProxyDelegate.h +++ b/framework/ios/debug/websocket/HippyWebSocketProxyDelegate.h @@ -20,9 +20,9 @@ * limitations under the License. */ -#import "MacroDefines.h" +#import "HippyDefines.h" -#if HP_DEV // Only supported in dev mode +#if HIPPY_DEV // Only supported in dev mode @protocol HippyWebSocketProxy; diff --git a/framework/ios/module/dev/HippyDevMenu.h b/framework/ios/module/dev/HippyDevMenu.h index ff3e05e8ca8..3ca48042d49 100644 --- a/framework/ios/module/dev/HippyDevMenu.h +++ b/framework/ios/module/dev/HippyDevMenu.h @@ -32,7 +32,7 @@ @interface HippyDevMenu : NSObject /** - * Is the menu enabled. The menu is enabled by default if HP_DEV=1, but + * Is the menu enabled. The menu is enabled by default if HIPPY_DEV=1, but * you may wish to disable it so that you can provide your own shake handler. */ @property (nonatomic, assign) BOOL shakeToShow; diff --git a/framework/ios/module/dev/HippyDevMenu.mm b/framework/ios/module/dev/HippyDevMenu.mm index bc979160f0d..733e87e18e6 100644 --- a/framework/ios/module/dev/HippyDevMenu.mm +++ b/framework/ios/module/dev/HippyDevMenu.mm @@ -24,13 +24,13 @@ #import "HippyEventDispatcher.h" #import "HippyKeyCommands.h" #import "HippyWebSocketProxy.h" -#import "HPAsserts.h" -#import "HPToolUtils.h" -#import "MacroDefines.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" +#import "HippyDefines.h" #include -#if HP_DEV +#if HIPPY_DEV static NSString *const HippyShowDevMenuNotification = @"HippyShowDevMenuNotification"; static NSString *const HippyDevMenuSettingsKey = @"HippyDevMenu"; @@ -107,7 +107,7 @@ - (void)callHandler { @end -@interface HippyDevMenu () { +@interface HippyDevMenu () { __weak UIAlertController *_actionSheet; NSUserDefaults *_defaults; } @@ -124,7 +124,7 @@ + (void)initialize { // We're swizzling here because it's poor form to override methods in a category, // however UIWindow doesn't actually implement motionEnded:withEvent:, so there's // no need to call the original implementation. - HPSwapInstanceMethods([UIWindow class], @selector(motionEnded:withEvent:), @selector(hippy_motionEnded:withEvent:)); + HippySwapInstanceMethods([UIWindow class], @selector(motionEnded:withEvent:), @selector(hippy_motionEnded:withEvent:)); } - (instancetype)init { @@ -209,7 +209,7 @@ - (void)addItem:(NSString *)title handler:(void (^)(void))handler { } - (void)addItem:(__unused HippyDevMenuItem *)item { - HPAssert(NO, @"[HippyDevMenu addItem:]方法没有实现,怎么没问题?"); + HippyAssert(NO, @"[HippyDevMenu addItem:]方法没有实现,怎么没问题?"); } - (NSArray *)menuItems { @@ -230,7 +230,7 @@ - (void)addItem:(__unused HippyDevMenuItem *)item { } HIPPY_EXPORT_METHOD(show) { - if (_actionSheet || !_bridge || HPRunningInAppExtension()) { + if (_actionSheet || !_bridge || HippyRunningInAppExtension()) { return; } @@ -264,7 +264,7 @@ - (void)addItem:(__unused HippyDevMenuItem *)item { handler:^(__unused UIAlertAction *action) { }]]; - [HPPresentedViewController() presentViewController:_actionSheet animated:YES completion:^(void){}]; + [HippyPresentedViewController() presentViewController:_actionSheet animated:YES completion:^(void){}]; } @end @@ -289,7 +289,7 @@ - (void)addItem:(__unused HippyDevMenu *)item { @implementation HippyBridge (HippyDevMenu) - (HippyDevMenu *)devMenu { -#if HP_DEV +#if HIPPY_DEV return [self moduleForClass:[HippyDevMenu class]]; #else return nil; diff --git a/framework/ios/module/dev/HippyRedBox.h b/framework/ios/module/dev/HippyRedBox.h index f72091915ce..87f0e397950 100644 --- a/framework/ios/module/dev/HippyRedBox.h +++ b/framework/ios/module/dev/HippyRedBox.h @@ -50,4 +50,13 @@ @property (nonatomic, readonly) HippyRedBox *redBox; +/// The last current active bridge instance. ++ (nullable id)currentBridge; + +/// Record the last active bridge instance. +/// - Parameter currentBridge: bridge instance, pass nil to reset. ++ (void)setCurrentBridge:(nullable HippyBridge *)currentBridge; + @end + + diff --git a/framework/ios/module/dev/HippyRedBox.mm b/framework/ios/module/dev/HippyRedBox.mm index 71524a0252b..f90215a110e 100644 --- a/framework/ios/module/dev/HippyRedBox.mm +++ b/framework/ios/module/dev/HippyRedBox.mm @@ -24,22 +24,22 @@ #import "HippyErrorInfo.h" #import "HippyRedBox.h" #import "HippyUtils.h" +#import "HippyWeakProxy.h" +#import "HippyAsserts.h" +#import "HippyConvert.h" +#import "HippyJSStackFrame.h" +#import "HippyLog.h" +#import "HippyUtils.h" -#import "HPAsserts.h" -#import "HPConvert.h" -#import "HPDriverStackFrame.h" -#import "HPLog.h" -#import "HPToolUtils.h" - -#import "MacroDefines.h" +#import "HippyDefines.h" -#if HP_DEBUG +#if HIPPY_DEBUG @class HippyRedBoxWindow; @protocol HippyRedBoxWindowActionDelegate -- (void)redBoxWindow:(HippyRedBoxWindow *)redBoxWindow openStackFrameInEditor:(HPDriverStackFrame *)stackFrame; +- (void)redBoxWindow:(HippyRedBoxWindow *)redBoxWindow openStackFrameInEditor:(HippyJSStackFrame *)stackFrame; - (void)reloadFromRedBoxWindow:(HippyRedBoxWindow *)redBoxWindow; @end @@ -51,7 +51,7 @@ @interface HippyRedBoxWindow : UIWindow *_lastStackTrace; + NSArray *_lastStackTrace; __weak UIWindow *_previousKeyWindow; } @@ -137,7 +137,7 @@ - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } -- (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack isUpdate:(BOOL)isUpdate { +- (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack isUpdate:(BOOL)isUpdate { // Show if this is a new message, or if we're updating the previous message if ((self.hidden && !isUpdate) || (!self.hidden && isUpdate && [_lastErrorMessage isEqualToString:message])) { _lastStackTrace = stack; @@ -151,7 +151,7 @@ - (void)showErrorMessage:(NSString *)message withStack:(NSArray +@interface HippyRedBox () @end @implementation HippyRedBox { @@ -344,7 +344,7 @@ - (void)registerErrorCustomizer:(id)errorCustomizer { // WARNING: Should only be called from the main thread/dispatch queue. - (HippyErrorInfo *)_customizeError:(HippyErrorInfo *)error { - HPAssertMainQueue(); + HippyAssertMainQueue(); if (!self->_errorCustomizers) { return error; @@ -375,7 +375,7 @@ - (void)showErrorMessage:(NSString *)message withDetails:(NSString *)details { } - (void)showErrorMessage:(NSString *)message withRawStack:(NSString *)rawStack { - NSArray *stack = [HPDriverStackFrame stackFramesWithLines:rawStack]; + NSArray *stack = [HippyJSStackFrame stackFramesWithLines:rawStack]; [self showErrorMessage:message withStack:stack isUpdate:NO]; } @@ -391,8 +391,8 @@ - (void)showErrorMessage:(NSString *)message withStack:(NSArray *)stack isUpdate if (!_showEnabled) { return; } - if (![[stack firstObject] isKindOfClass:[HPDriverStackFrame class]]) { - stack = [HPDriverStackFrame stackFramesWithDictionaries:stack]; + if (![[stack firstObject] isKindOfClass:[HippyJSStackFrame class]]) { + stack = [HippyJSStackFrame stackFramesWithDictionaries:stack]; } dispatch_async(dispatch_get_main_queue(), ^{ @@ -417,9 +417,9 @@ - (void)invalidate { } - (void)redBoxWindow:(__unused HippyRedBoxWindow *)redBoxWindow -openStackFrameInEditor:(HPDriverStackFrame *)stackFrame { +openStackFrameInEditor:(HippyJSStackFrame *)stackFrame { //todo - HPLog(@"red box cannot open stack frame"); + HippyLog(@"red box cannot open stack frame"); } - (void)reloadFromRedBoxWindow:(__unused HippyRedBoxWindow *)redBoxWindow { @@ -428,14 +428,36 @@ - (void)reloadFromRedBoxWindow:(__unused HippyRedBoxWindow *)redBoxWindow { @end + +#pragma mark - + + @implementation HippyBridge (HippyRedBox) - (HippyRedBox *)redBox { return [self moduleForClass:[HippyRedBox class]]; } +static HippyWeakProxy *HippyCurrentBridgeInstance = nil; + +/** + * The last current active bridge instance. This is set automatically whenever + * the bridge is accessed. It can be useful for static functions or singletons + * that need to access the bridge for purposes such as logging, but should not + * be relied upon to return any particular instance, due to race conditions. + */ ++ (instancetype)currentBridge { + return (id)HippyCurrentBridgeInstance; +} + ++ (void)setCurrentBridge:(nullable HippyBridge *)currentBridge { + HippyCurrentBridgeInstance = [HippyWeakProxy weakProxyForObject:currentBridge]; +} + + @end + #else // Disabled @implementation HippyRedBox diff --git a/framework/ios/module/eventobserver/HippyEventObserverModule.mm b/framework/ios/module/eventobserver/HippyEventObserverModule.mm index 94e44ab9754..8c3404cfb83 100644 --- a/framework/ios/module/eventobserver/HippyEventObserverModule.mm +++ b/framework/ios/module/eventobserver/HippyEventObserverModule.mm @@ -22,7 +22,7 @@ #import "HippyEventObserverModule.h" #import "HippyEventDispatcher.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" @implementation HippyEventObserverModule { NSMutableDictionary *_config; @@ -46,7 +46,7 @@ - (instancetype)init } HIPPY_EXPORT_METHOD(addListener:(NSString *)eventName) { - HPAssertParam(eventName); + HippyAssertParam(eventName); NSNumber *value = _config[eventName]; if (value == nil) { value = @(1); @@ -87,7 +87,7 @@ - (void)dealloc - (void)sendEvent:(NSString *)eventName params:(NSDictionary *)params { - HPAssertParam(eventName); + HippyAssertParam(eventName); [self.bridge.eventDispatcher dispatchEvent:@"EventDispatcher" methodName:@"receiveNativeEvent" args:@{@"eventName": eventName, @"extra": params ? : @{}}]; } @end diff --git a/framework/ios/module/exception/HippyExceptionModule.mm b/framework/ios/module/exception/HippyExceptionModule.mm index ca70fcf2b63..fb90340fb08 100644 --- a/framework/ios/module/exception/HippyExceptionModule.mm +++ b/framework/ios/module/exception/HippyExceptionModule.mm @@ -23,8 +23,8 @@ #import "HippyExceptionModule.h" #import "HippyBridge.h" #import "HippyDefines.h" -#import "HPAsserts.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" @implementation HippyExceptionModule @@ -59,13 +59,13 @@ @implementation HippyExceptionModule } NSDictionary *errorInfo = @{NSLocalizedDescriptionKey:title?:@"unknown", NSLocalizedFailureReasonErrorKey: detail?:@"unkonwn", - HPJSStackTraceKey:formatStacks, + HippyJSStackTraceKey:formatStacks, @"HippyTimeIntervalKey":timeInterval ?:@(0), - HPFatalModuleName:[[self bridge] moduleName]?:@"unknown" + HippyFatalModuleName:[[self bridge] moduleName]?:@"unknown" }; - NSError *error = [NSError errorWithDomain:HPErrorDomain code:1 userInfo:errorInfo]; - HPFatal(error, @{@"bridge": self.bridge}); + NSError *error = [NSError errorWithDomain:HippyErrorDomain code:1 userInfo:errorInfo]; + HippyFatal(error); } @end diff --git a/framework/ios/module/imageloader/HippyImageLoaderModule.mm b/framework/ios/module/imageloader/HippyImageLoaderModule.mm index c61d8af3334..a74b776d5af 100644 --- a/framework/ios/module/imageloader/HippyImageLoaderModule.mm +++ b/framework/ios/module/imageloader/HippyImageLoaderModule.mm @@ -24,7 +24,7 @@ #import "HippyBridge+VFSLoader.h" #import "HippyImageLoaderModule.h" -#import "HPToolUtils.h" +#import "HippyUtils.h" #import "HippyDefines.h" static NSString *const kImageLoaderModuleErrorDomain = @"kImageLoaderModuleErrorDomain"; @@ -43,11 +43,11 @@ @implementation HippyImageLoaderModule @synthesize bridge = _bridge; -- (id)imageProviderForData:(NSData *)data { - NSArray> *providers = [self.bridge imageProviderClasses]; - for (Class cls in providers) { +- (id)imageProviderForData:(NSData *)data { + NSArray> *providers = [self.bridge imageProviderClasses]; + for (Class cls in providers) { if ([cls canHandleData:data]) { - id object = [[(Class)cls alloc] init]; + id object = [[(Class)cls alloc] init]; [object setImageData:data]; return object; } @@ -64,7 +64,7 @@ @implementation HippyImageLoaderModule progress:nil completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { - id imageProvider = [self imageProviderForData:data]; + id imageProvider = [self imageProviderForData:data]; if (!imageProvider) { NSError *error = [NSError errorWithDomain:kImageLoaderModuleErrorDomain code:ImageLoaderErrorParseError userInfo:@{@"reason": @"no image provider error"}]; diff --git a/framework/ios/module/loader/HippyBridge+VFSLoader.mm b/framework/ios/module/loader/HippyBridge+VFSLoader.mm index 7eea84d8efa..b49adff215e 100644 --- a/framework/ios/module/loader/HippyBridge+VFSLoader.mm +++ b/framework/ios/module/loader/HippyBridge+VFSLoader.mm @@ -21,7 +21,7 @@ */ #import "HippyBridge+VFSLoader.h" -#import "HPToolUtils.h" +#import "HippyUtils.h" #include "VFSUriLoader.h" #include "VFSUriHandler.h" @@ -40,7 +40,7 @@ - (void)loadContentsAsynchronouslyFromUrl:(NSString *)urlString } std::shared_ptr loader = [self VFSUriLoader].lock(); if (loader) { - NSURL *url = HPURLWithString(urlString, nil); + NSURL *url = HippyURLWithString(urlString, nil); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; if (method) { [request setHTTPMethod:method]; diff --git a/framework/ios/module/loader/HippyFileHandler.mm b/framework/ios/module/loader/HippyFileHandler.mm index caae3fa914c..c9605ca2517 100644 --- a/framework/ios/module/loader/HippyFileHandler.mm +++ b/framework/ios/module/loader/HippyFileHandler.mm @@ -21,7 +21,7 @@ */ #import "HippyBridge.h" -#import "HPToolUtils.h" +#import "HippyUtils.h" #include "HippyFileHandler.h" #include "footstone/logging.h" diff --git a/framework/ios/module/localstorage/HippyAsyncLocalStorage.h b/framework/ios/module/localstorage/HippyAsyncLocalStorage.h index 65432cc952a..7924a86e380 100644 --- a/framework/ios/module/localstorage/HippyAsyncLocalStorage.h +++ b/framework/ios/module/localstorage/HippyAsyncLocalStorage.h @@ -21,7 +21,7 @@ */ #import "HippyBridgeModule.h" -#import "HPInvalidating.h" +#import "HippyInvalidating.h" /** * A simple, asynchronous, persistent, key-value storage system designed as a @@ -40,7 +40,7 @@ extern NSUInteger HPLOCALSTORAGEIOTYPEREAD; extern NSUInteger HPLOCALSTORAGEIOTYPEWRITE; -@interface HippyAsyncLocalStorage : NSObject +@interface HippyAsyncLocalStorage : NSObject @property (nonatomic, assign) BOOL clearOnInvalidate; diff --git a/framework/ios/module/localstorage/HippyAsyncLocalStorage.mm b/framework/ios/module/localstorage/HippyAsyncLocalStorage.mm index aae43840aa7..660f441c9f9 100644 --- a/framework/ios/module/localstorage/HippyAsyncLocalStorage.mm +++ b/framework/ios/module/localstorage/HippyAsyncLocalStorage.mm @@ -26,10 +26,10 @@ #import "HippyBridge.h" #import "HippyDefines.h" #import "HippyUtils.h" -#import "HPAsserts.h" -#import "HPConvert.h" -#import "HPLog.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyConvert.h" +#import "HippyLog.h" +#import "HippyUtils.h" NSString *const HippyStorageDirectory = @"HippyAsyncLocalStorage_V1"; static NSString *const HippyManifestFileName = @"manifest.json"; @@ -204,12 +204,12 @@ - (void)dealloc { } - (NSString *)_filePathForKey:(NSString *)key { - NSString *safeFileName = HPMD5Hash(key); + NSString *safeFileName = HippyMD5Hash(key); return [[self HippyGetStorageDirectory] stringByAppendingPathComponent:safeFileName]; } - (NSDictionary *)_ensureSetup { - HPAssertThread(HippyGetMethodQueue(), @"Must be executed on storage thread"); + HippyAssertThread(HippyGetMethodQueue(), @"Must be executed on storage thread"); NSError *error = nil; if (!_HippyHasCreatedStorageDirectory) { @@ -228,7 +228,7 @@ - (NSDictionary *)_ensureSetup { NSString *serialized = [self _readFileFromPath:[self HippyGetManifestFilePath] key:nil error:&errorOut]; NSMutableDictionary *tmpDic = serialized ? HippyJSONParseMutable(serialized, &error) : [NSMutableDictionary new]; if (error) { - HPLogWarn(@"Failed to parse manifest - creating new one.\n\n%@", error); + HippyLogWarn(@"Failed to parse manifest - creating new one.\n\n%@", error); tmpDic = [NSMutableDictionary new]; } [_manifest addEntriesFromDictionary:tmpDic]; @@ -378,10 +378,10 @@ - (BOOL)handleDataSizeExceedForIOType:(NSUInteger)IOType moduleName:(NSString *) for (NSString *key in keys) { id keyError; id value = [self _getValueForKey:key errorOut:&keyError]; - [result addObject:@[key, HPNullIfNil(value)]]; + [result addObject:@[key, HippyNullIfNil(value)]]; HippyAppendError(keyError, &errors); } - callback(@[HPNullIfNil(errors), result]); + callback(@[HippyNullIfNil(errors), result]); } HIPPY_EXPORT_METHOD(multiSet:(NSArray *> *)kvPairs @@ -400,7 +400,7 @@ - (BOOL)handleDataSizeExceedForIOType:(NSUInteger)IOType moduleName:(NSString *) if (changedManifest) { [self _writeManifest:&errors]; } - callback(@[HPNullIfNil(errors)]); + callback(@[HippyNullIfNil(errors)]); } HIPPY_EXPORT_METHOD(multiMerge:(NSArray *> *)kvPairs @@ -420,7 +420,7 @@ - (BOOL)handleDataSizeExceedForIOType:(NSUInteger)IOType moduleName:(NSString *) NSError *jsonError; NSMutableDictionary *mergedVal = HippyJSONParseMutable(value, &jsonError); if (HippyMergeRecursive(mergedVal, HippyJSONParse(entry[1], &jsonError))) { - entry = @[entry[0], HPNullIfNil(HippyJSONStringify(mergedVal, NULL))]; + entry = @[entry[0], HippyNullIfNil(HippyJSONStringify(mergedVal, NULL))]; } if (jsonError) { keyError = HippyJSErrorFromNSError(jsonError); @@ -435,7 +435,7 @@ - (BOOL)handleDataSizeExceedForIOType:(NSUInteger)IOType moduleName:(NSString *) if (changedManifest) { [self _writeManifest:&errors]; } - callback(@[HPNullIfNil(errors)]); + callback(@[HippyNullIfNil(errors)]); } HIPPY_EXPORT_METHOD(multiRemove:(NSArray *)keys @@ -467,14 +467,14 @@ - (BOOL)handleDataSizeExceedForIOType:(NSUInteger)IOType moduleName:(NSString *) if (changedManifest) { [self _writeManifest:&errors]; } - callback(@[HPNullIfNil(errors)]); + callback(@[HippyNullIfNil(errors)]); } HIPPY_EXPORT_METHOD(clear:(HippyResponseSenderBlock)callback) { [_manifest removeAllObjects]; [HippyGetCache() removeAllObjects]; NSDictionary *error = [self HippyDeleteStorageDirectory]; - callback(@[HPNullIfNil(error)]); + callback(@[HippyNullIfNil(error)]); } HIPPY_EXPORT_METHOD(getAllKeys:(HippyResponseSenderBlock)callback) { diff --git a/framework/ios/module/netinfo/HippyNetInfo.h b/framework/ios/module/netinfo/HippyNetInfo.h index b273cb8eb94..f8be74ee9f4 100644 --- a/framework/ios/module/netinfo/HippyNetInfo.h +++ b/framework/ios/module/netinfo/HippyNetInfo.h @@ -21,8 +21,8 @@ */ #import "HippyEventObserverModule.h" -#import "HPInvalidating.h" +#import "HippyInvalidating.h" -@interface HippyNetInfo : HippyEventObserverModule +@interface HippyNetInfo : HippyEventObserverModule @end diff --git a/framework/ios/module/netinfo/HippyNetInfo.mm b/framework/ios/module/netinfo/HippyNetInfo.mm index 2066d050ef5..61879703a3f 100644 --- a/framework/ios/module/netinfo/HippyNetInfo.mm +++ b/framework/ios/module/netinfo/HippyNetInfo.mm @@ -26,7 +26,7 @@ #import "HippyNetInfo.h" #import "HippyNetInfoIntenal.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" @interface HippyNetInfo () { } diff --git a/framework/ios/module/netinfo/HippyNetInfoIntenal.m b/framework/ios/module/netinfo/HippyNetInfoIntenal.m index c2152d81d78..25449ed0c7d 100644 --- a/framework/ios/module/netinfo/HippyNetInfoIntenal.m +++ b/framework/ios/module/netinfo/HippyNetInfoIntenal.m @@ -24,7 +24,7 @@ #import #import "HippyNetInfoIntenal.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" #include @@ -205,7 +205,7 @@ - (void)registerNetworkChangedListener { } - (HippyNetworkTypeObject *)addNetworkTypeChangeObserver:(id)observer { - HPAssert([observer respondsToSelector:@selector(hippyNetworkTypeChanged:)], @"observer shoud conform HippyNetworkTypeChangedDelegate"); + HippyAssert([observer respondsToSelector:@selector(hippyNetworkTypeChanged:)], @"observer shoud conform HippyNetworkTypeChangedDelegate"); if (observer) { [_observers addObject:observer]; } @@ -234,7 +234,7 @@ - (NSString *)currentCellType { - (void)notifyObserversNetworkTypeChanged:(HippyNetworkTypeObject *)object { NSArray> *observers = [_observers allObjects]; for (id observer in observers) { - HPAssert([observer respondsToSelector:@selector(hippyNetworkTypeChanged:)], @"observer shoud conform HippyNetworkTypeChangedDelegate"); + HippyAssert([observer respondsToSelector:@selector(hippyNetworkTypeChanged:)], @"observer shoud conform HippyNetworkTypeChangedDelegate"); if ([observer respondsToSelector:@selector(hippyNetworkTypeChanged:)]) { [observer hippyNetworkTypeChanged:object]; } diff --git a/framework/ios/module/network/HippyNetWork.mm b/framework/ios/module/network/HippyNetWork.mm index f435ef57a56..6e8caa203a0 100644 --- a/framework/ios/module/network/HippyNetWork.mm +++ b/framework/ios/module/network/HippyNetWork.mm @@ -26,8 +26,8 @@ #import "HippyBridge+VFSLoader.h" #import "HippyDefines.h" #import "HippyNetWork.h" -#import "HPAsserts.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" static NSStringEncoding GetStringEncodingFromURLResponse(NSURLResponse *response) { NSString *textEncoding = [response textEncodingName]; @@ -54,8 +54,8 @@ @implementation HippyNetWork NSDictionary *header = params[@"headers"]; NSString *body = params[@"body"]; - HPAssertParam(url); - HPAssertParam(method); + HippyAssertParam(url); + HippyAssertParam(method); NSMutableDictionary *vfsParams = [NSMutableDictionary new]; [header enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, __unused BOOL *stop) { diff --git a/framework/ios/module/rootview/HippyRootViewManager.h b/framework/ios/module/rootview/HippyRootViewManager.h index 971522a9067..d41d9034fcf 100644 --- a/framework/ios/module/rootview/HippyRootViewManager.h +++ b/framework/ios/module/rootview/HippyRootViewManager.h @@ -23,12 +23,12 @@ #import #import "HippyBridgeModule.h" -#import "MacroDefines.h" +#import "HippyDefines.h" NS_ASSUME_NONNULL_BEGIN -HP_EXTERN NSString *const HippyDidDidRemoveRootViewNotification; -HP_EXTERN NSString *const HippyRootViewTagKey; +HIPPY_EXTERN NSString *const HippyDidDidRemoveRootViewNotification; +HIPPY_EXTERN NSString *const HippyRootViewTagKey; @interface HippyRootViewManager : NSObject diff --git a/framework/ios/module/turbo/HippyOCTurboModule.mm b/framework/ios/module/turbo/HippyOCTurboModule.mm index 379d9247249..9fe98209e93 100644 --- a/framework/ios/module/turbo/HippyOCTurboModule.mm +++ b/framework/ios/module/turbo/HippyOCTurboModule.mm @@ -25,9 +25,9 @@ #import "HippyOCTurboModule+Inner.h" #import "HippyTurboModuleManager.h" #import "HippyJSExecutor.h" -#import "HPAsserts.h" -#import "HPLog.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyLog.h" +#import "HippyUtils.h" #import "NSObject+CtxValue.h" #import "NSObject+HippyTurbo.h" @@ -118,8 +118,8 @@ - (id)invokeObjCMethodWithName:(NSString *)methodName } } - if (HP_DEBUG && !method) { - HPLogError(@"Unknown methodID: %@ for module:%@", methodName, obj); + if (HIPPY_DEBUG && !method) { + HippyLogError(@"Unknown methodID: %@ for module:%@", methodName, obj); return nil; } @@ -128,13 +128,13 @@ - (id)invokeObjCMethodWithName:(NSString *)methodName return value; } @catch (NSException *exception) { // Pass on JS exceptions - if ([exception.name hasPrefix:HPFatalExceptionName]) { + if ([exception.name hasPrefix:HippyFatalExceptionName]) { @throw exception; } NSString *message = [NSString stringWithFormat:@"Exception '%@' was thrown while invoking %@ on target %@ with params %@", exception, method.JSMethodName, NSStringFromClass([self class]) ,argumentArray]; - NSError *error = HPErrorWithMessageAndModuleName(message, self.bridge.moduleName); + NSError *error = HippyErrorWithMessageAndModuleName(message, self.bridge.moduleName); HippyBridgeFatal(error, self.bridge); return nil; } @@ -265,7 +265,7 @@ static id convertJSIObjectToNSObject(const std::shared_ptr &co NSError *error; id objcObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (error) { - HPLogError(@"JSONObjectWithData error:%@", error); + HippyLogError(@"JSONObjectWithData error:%@", error); } return objcObject; } diff --git a/framework/ios/module/turbo/HippyTurboModule.h b/framework/ios/module/turbo/HippyTurboModule.h index f5556e98994..10643569a31 100644 --- a/framework/ios/module/turbo/HippyTurboModule.h +++ b/framework/ios/module/turbo/HippyTurboModule.h @@ -39,7 +39,7 @@ + (NSString *)turoboModuleName; #define HIPPY_EXPORT_TURBO_MODULE(js_name) \ - HP_EXTERN void HippyRegisterTurboModule(NSString *, Class); \ + HIPPY_EXTERN void HippyRegisterTurboModule(NSString *, Class); \ +(NSString *)turoboModuleName { \ return @ #js_name; \ } \ @@ -54,8 +54,8 @@ -(id)method #define HIPPY_EXTERN_REMAP_TURBO_METHOD(js_name, method) \ - +(NSArray *)HP_CONCAT(__hippy_export_turbo__, \ - HP_CONCAT(js_name, HP_CONCAT(__LINE__, __COUNTER__))) { \ + +(NSArray *)HIPPY_CONCAT(__hippy_export_turbo__, \ + HIPPY_CONCAT(js_name, HIPPY_CONCAT(__LINE__, __COUNTER__))) { \ return @[@ #js_name, @ #method]; \ } diff --git a/framework/ios/module/turbo/HippyTurboModuleManager.mm b/framework/ios/module/turbo/HippyTurboModuleManager.mm index 7579f9499a0..c5c5814f5d7 100644 --- a/framework/ios/module/turbo/HippyTurboModuleManager.mm +++ b/framework/ios/module/turbo/HippyTurboModuleManager.mm @@ -23,7 +23,7 @@ #import "HippyJSExecutor.h" #import "HippyModuleData.h" #import "HippyTurboModuleManager.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" #include @@ -32,10 +32,10 @@ static NSMutableDictionary *HippyTurboModuleMap; -HP_EXTERN void HippyRegisterTurboModule(NSString *, Class); +HIPPY_EXTERN void HippyRegisterTurboModule(NSString *, Class); void HippyRegisterTurboModule(NSString *moduleName, Class moduleClass) { if (!moduleClass || !moduleName || moduleName.length == 0) { - HPAssert(NO, @"moduleName or moduleClass is nil or empty!"); + HippyAssert(NO, @"moduleName or moduleClass is nil or empty!"); return; } @@ -44,11 +44,11 @@ void HippyRegisterTurboModule(NSString *moduleName, Class moduleClass) { HippyTurboModuleMap = [NSMutableDictionary dictionary]; }); - HPAssert([moduleClass conformsToProtocol:@protocol(HippyTurboModule)], + HippyAssert([moduleClass conformsToProtocol:@protocol(HippyTurboModule)], @"%@ does not conform to the HippyTurboModule protocol", moduleClass); if ([HippyTurboModuleMap objectForKey:moduleName]) { - HPAssert(NO, @"dumplicate regist the moduleName(%@) for %@ and %@", + HippyAssert(NO, @"dumplicate regist the moduleName(%@) for %@ and %@", moduleName, NSStringFromClass(moduleClass), NSStringFromClass([HippyTurboModuleMap objectForKey:moduleName])); @@ -109,7 +109,7 @@ - (__kindof HippyOCTurboModule *)turboModuleWithName:(NSString *)name { module = [[moduleCls alloc] initWithName:name bridge:_bridge]; [self.turboModuleCache setObject:module forKey:name]; } else { - HPAssert(NO, @"moduleClass of %@ is not conformsToProtocol(HippyTurboModuleImpProtocol)!", name); + HippyAssert(NO, @"moduleClass of %@ is not conformsToProtocol(HippyTurboModuleImpProtocol)!", name); } } return module; diff --git a/framework/ios/module/turbo/NSObject+HippyTurbo.m b/framework/ios/module/turbo/NSObject+HippyTurbo.m index 97d27259bbf..f703373ef50 100644 --- a/framework/ios/module/turbo/NSObject+HippyTurbo.m +++ b/framework/ios/module/turbo/NSObject+HippyTurbo.m @@ -21,8 +21,8 @@ */ #import "HippyModuleMethod.h" -#import "HPAsserts.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" #import "NSObject+HippyTurbo.h" #include diff --git a/framework/ios/utils/HippyDefines.h b/framework/ios/utils/HippyDefines.h deleted file mode 100644 index c121852aeab..00000000000 --- a/framework/ios/utils/HippyDefines.h +++ /dev/null @@ -1,51 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * Hippy available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * The type of a block that is capable of sending a response to a bridged - * operation. Use this for returning callback methods to JS. - */ -typedef void (^HippyResponseSenderBlock)(NSArray *response); - -/** - * The type of a block that is capable of sending an error response to a - * bridged operation. Use this for returning error information to JS. - */ -typedef void (^HippyResponseErrorBlock)(NSError *error); - -/** - * Block that bridge modules use to resolve the JS promise waiting for a result. - * Nil results are supported and are converted to JS's undefined value. - */ -typedef void (^HippyPromiseResolveBlock)(id result); - -/** - * Block that bridge modules use to reject the JS promise waiting for a result. - * The error may be nil but it is preferable to pass an NSError object for more - * precise error messages. - */ -typedef void (^HippyPromiseRejectBlock)(NSString *code, NSString *message, NSError *error); - -/** - * Block that when js script execution completion - */ -typedef void (^HippyJavaScriptCallback)(id result, NSError *error); diff --git a/framework/ios/utils/HippyErrorInfo.h b/framework/ios/utils/HippyErrorInfo.h index 5d6159cf128..310f0a0e6df 100644 --- a/framework/ios/utils/HippyErrorInfo.h +++ b/framework/ios/utils/HippyErrorInfo.h @@ -22,15 +22,15 @@ #import -@class HPDriverStackFrame; +@class HippyJSStackFrame; /** * An ObjC wrapper for Hippy Native errors. */ @interface HippyErrorInfo : NSObject @property (nonatomic, copy, readonly) NSString *errorMessage; -@property (nonatomic, copy, readonly) NSArray *stack; +@property (nonatomic, copy, readonly) NSArray *stack; -- (instancetype)initWithErrorMessage:(NSString *)errorMessage stack:(NSArray *)stack; +- (instancetype)initWithErrorMessage:(NSString *)errorMessage stack:(NSArray *)stack; @end diff --git a/framework/ios/utils/HippyErrorInfo.m b/framework/ios/utils/HippyErrorInfo.m index 0725f67b513..155299dcbd6 100644 --- a/framework/ios/utils/HippyErrorInfo.m +++ b/framework/ios/utils/HippyErrorInfo.m @@ -22,11 +22,11 @@ #import "HippyErrorInfo.h" -#import "HPDriverStackFrame.h" +#import "HippyJSStackFrame.h" @implementation HippyErrorInfo -- (instancetype)initWithErrorMessage:(NSString *)errorMessage stack:(NSArray *)stack { +- (instancetype)initWithErrorMessage:(NSString *)errorMessage stack:(NSArray *)stack { self = [super init]; if (self) { _errorMessage = [errorMessage copy]; diff --git a/framework/ios/utils/HippyUtils.h b/framework/ios/utils/HippyUtils.h deleted file mode 100644 index 349845aebc0..00000000000 --- a/framework/ios/utils/HippyUtils.h +++ /dev/null @@ -1,51 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * Hippy available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import - -#import "MacroDefines.h" - -NS_ASSUME_NONNULL_BEGIN - -// JSON serialization/deserialization -HP_EXTERN NSString *__nullable HippyJSONStringify(id __nullable jsonObject, NSError **error); -HP_EXTERN id __nullable HippyJSONParse(NSString *__nullable jsonString, NSError **error); -HP_EXTERN id __nullable HippyJSONParseMutable(NSString *__nullable jsonString, NSError **error); - -// Sanitize a JSON object by stripping invalid types and/or NaN values -HP_EXTERN id HippyJSONClean(id object); - -// Get MD5 hash of a string -HP_EXTERN NSString *HPMD5Hash(NSString *string); - -// Creates a standardized error object to return in callbacks -HP_EXTERN NSDictionary *HippyMakeError( - NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); -HP_EXTERN NSDictionary *HippyMakeAndLogError( - NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData); -HP_EXTERN NSDictionary *HippyJSErrorFromNSError(NSError *error); -HP_EXTERN NSDictionary *HippyJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error); - -// The default error code to use as the `code` property for callback error objects -HP_EXTERN NSString *const HippyErrorUnspecified; - -NS_ASSUME_NONNULL_END diff --git a/framework/ios/utils/HippyUtils.m b/framework/ios/utils/HippyUtils.m deleted file mode 100644 index 19d3a194d57..00000000000 --- a/framework/ios/utils/HippyUtils.m +++ /dev/null @@ -1,256 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * Hippy available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import - -#import "HippyUtils.h" -#import "HPAsserts.h" -#import "HPLog.h" - -#include - -NSString *const HippyErrorUnspecified = @"HippyErrorUnspecified"; - -static NSString *__nullable _HPJSONStringifyNoRetry(id __nullable jsonObject, NSError **error) { - if (!jsonObject) { - return nil; - } - - static SEL JSONKitSelector = NULL; - static NSSet *collectionTypes; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - SEL selector = NSSelectorFromString(@"JSONStringWithOptions:error:"); - if ([NSDictionary instancesRespondToSelector:selector]) { - JSONKitSelector = selector; - collectionTypes = [NSSet setWithObjects:[NSArray class], [NSMutableArray class], [NSDictionary class], [NSMutableDictionary class], nil]; - } - }); - - @try { - // Use JSONKit if available and object is not a fragment - if (JSONKitSelector && [collectionTypes containsObject:[jsonObject classForCoder]]) { - return ((NSString * (*)(id, SEL, int, NSError **)) objc_msgSend)(jsonObject, JSONKitSelector, 0, error); - } - - // Use Foundation JSON method - NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:(NSJSONWritingOptions)NSJSONReadingAllowFragments error:error]; - - return jsonData ? [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] : nil; - } @catch (NSException *exception) { - // Convert exception to error - if (error) { - *error = [NSError errorWithDomain:HPErrorDomain code:0 userInfo:@ { NSLocalizedDescriptionKey: exception.description ?: @"" }]; - } - return nil; - } -} - -NSString *__nullable HippyJSONStringify(id __nullable jsonObject, NSError **error) { - if (error) { - return _HPJSONStringifyNoRetry(jsonObject, error); - } else { - NSError *localError; - NSString *json = _HPJSONStringifyNoRetry(jsonObject, &localError); - if (localError) { - HPLogError(@"HPJSONStringify() encountered the following error: %@", localError.localizedDescription); - // Sanitize the data, then retry. This is slow, but it prevents uncaught - // data issues from crashing in production - return _HPJSONStringifyNoRetry(HippyJSONClean(jsonObject), NULL); - } - return json; - } -} - -static id __nullable _HPJSONParse(NSString *__nullable jsonString, BOOL mutable, NSError **error) { - static SEL JSONKitSelector = NULL; - static SEL JSONKitMutableSelector = NULL; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - SEL selector = NSSelectorFromString(@"objectFromJSONStringWithParseOptions:error:"); - if ([NSString instancesRespondToSelector:selector]) { - JSONKitSelector = selector; - JSONKitMutableSelector = NSSelectorFromString(@"mutableObjectFromJSONStringWithParseOptions:error:"); - } - }); - - if (jsonString) { - // Use JSONKit if available and string is not a fragment - if (JSONKitSelector) { - NSInteger length = jsonString.length; - for (NSInteger i = 0; i < length; i++) { - unichar c = [jsonString characterAtIndex:i]; - if (strchr("{[", c)) { - static const int options = (1 << 2); // loose unicode - SEL selector = mutable ? JSONKitMutableSelector : JSONKitSelector; - return ((id(*)(id, SEL, int, NSError **))objc_msgSend)(jsonString, selector, options, error); - } - if (!strchr(" \r\n\t", c)) { - break; - } - } - } - - // Use Foundation JSON method - NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; - if (!jsonData) { - jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; - if (jsonData) { - HPLogWarn(@"HPJSONParse received the following string, which could " - "not be losslessly converted to UTF8 data: '%@'", - jsonString); - } else { - NSString *errorMessage = @"HPJSONParse received invalid UTF8 data"; - if (error) { - *error = HPErrorWithMessage(errorMessage); - } else { - HPLogError(@"%@", errorMessage); - } - return nil; - } - } - NSJSONReadingOptions options = NSJSONReadingAllowFragments; - if (mutable) { - options |= NSJSONReadingMutableContainers; - } - return [NSJSONSerialization JSONObjectWithData:jsonData options:options error:error]; - } - return nil; -} - -id __nullable HippyJSONParse(NSString *__nullable jsonString, NSError **error) { - return _HPJSONParse(jsonString, NO, error); -} - -id __nullable HippyJSONParseMutable(NSString *__nullable jsonString, NSError **error) { - return _HPJSONParse(jsonString, YES, error); -} - -id HippyJSONClean(id object) { - static dispatch_once_t onceToken; - static NSSet *validLeafTypes; - dispatch_once(&onceToken, ^{ - validLeafTypes = [[NSSet alloc] initWithArray:@[ - [NSString class], - [NSMutableString class], - [NSNumber class], - [NSNull class], - ]]; - }); - - if ([validLeafTypes containsObject:[object classForCoder]]) { - if ([object isKindOfClass:[NSNumber class]]) { - return @(HPZeroIfNaN([object doubleValue])); - } - if ([object isKindOfClass:[NSString class]]) { - if ([object UTF8String] == NULL) { - return (id)kCFNull; - } - } - return object; - } - - if ([object isKindOfClass:[NSDictionary class]]) { - __block BOOL copy = NO; - NSMutableDictionary *values = [[NSMutableDictionary alloc] initWithCapacity:[object count]]; - [object enumerateKeysAndObjectsUsingBlock:^(NSString *key, id item, __unused BOOL *stop) { - id value = HippyJSONClean(item); - values[key] = value; - copy |= value != item; - }]; - return copy ? values : object; - } - - if ([object isKindOfClass:[NSArray class]]) { - __block BOOL copy = NO; - __block NSArray *values = object; - [object enumerateObjectsUsingBlock:^(id item, NSUInteger idx, __unused BOOL *stop) { - id value = HippyJSONClean(item); - if (copy) { - [(NSMutableArray *)values addObject:value]; - } else if (value != item) { - // Converted value is different, so we'll need to copy the array - values = [[NSMutableArray alloc] initWithCapacity:values.count]; - for (NSUInteger i = 0; i < idx; i++) { - [(NSMutableArray *)values addObject:object[i]]; - } - [(NSMutableArray *)values addObject:value]; - copy = YES; - } - }]; - return values; - } - - return (id)kCFNull; -} - -NSString *HPMD5Hash(NSString *string) { - const char *str = string.UTF8String; - unsigned char result[CC_MD5_DIGEST_LENGTH]; - CC_MD5(str, (CC_LONG)strlen(str), result); - - return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", result[0], result[1], result[2], result[3], - result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], - result[15]]; -} - -NSDictionary *HippyMakeError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData) { - if (toStringify) { - message = [message stringByAppendingString:[toStringify description]]; - } - - NSMutableDictionary *error = [extraData mutableCopy] ?: [NSMutableDictionary new]; - error[@"message"] = message; - return error; -} - -NSDictionary *HippyMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData) { - NSDictionary *error = HippyMakeError(message, toStringify, extraData); - HPLogError(@"\nError: %@", error); - return error; -} - -NSDictionary *HippyJSErrorFromNSError(NSError *error) { - NSString *codeWithDomain = [NSString stringWithFormat:@"E%@%ld", error.domain.uppercaseString, (long)error.code]; - return HippyJSErrorFromCodeMessageAndNSError(codeWithDomain, error.localizedDescription, error); -} - -NSDictionary *HippyJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error) { - NSString *errorMessage; - NSArray *stackTrace = [NSThread callStackSymbols]; - NSMutableDictionary *errorInfo = [NSMutableDictionary dictionaryWithObject:stackTrace forKey:@"nativeStackIOS"]; - - if (error) { - errorMessage = error.localizedDescription ?: @"Unknown error from a native module"; - errorInfo[@"domain"] = error.domain ?: HPErrorDomain; - } else { - errorMessage = @"Unknown error from a native module"; - errorInfo[@"domain"] = HPErrorDomain; - } - errorInfo[@"code"] = code ?: HippyErrorUnspecified; - errorInfo[@"userInfo"] = HPNullIfNil(error.userInfo); - - // Allow for explicit overriding of the error message - errorMessage = message ?: errorMessage; - - return HippyMakeError(errorMessage, nil, errorInfo); -} diff --git a/modules/ios/logutils/HPLogUtils.h b/framework/ios/utils/HippyWeakProxy.h similarity index 82% rename from modules/ios/logutils/HPLogUtils.h rename to framework/ios/utils/HippyWeakProxy.h index d22dbd0c418..05e66b4624a 100644 --- a/modules/ios/logutils/HPLogUtils.h +++ b/framework/ios/utils/HippyWeakProxy.h @@ -1,4 +1,5 @@ -/* +/*! + * iOS SDK * * Tencent is pleased to support the open source community by making * Hippy available. @@ -10,23 +11,23 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ #import -#import "MacroDefines.h" -#import "HPLog.h" - NS_ASSUME_NONNULL_BEGIN -HP_EXTERN void HPSetTDFLogFunction(HPLogFunction logFunction); +@interface HippyWeakProxy : NSProxy + ++ (instancetype)weakProxyForObject:(id)target; + +@end NS_ASSUME_NONNULL_END diff --git a/framework/ios/utils/HippyWeakProxy.m b/framework/ios/utils/HippyWeakProxy.m new file mode 100644 index 00000000000..597bd8cc8b1 --- /dev/null +++ b/framework/ios/utils/HippyWeakProxy.m @@ -0,0 +1,67 @@ +/*! + * iOS SDK + * + * Tencent is pleased to support the open source community by making + * Hippy available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "HippyWeakProxy.h" + +@interface HippyWeakProxy () + +@property (nonatomic, weak) id target; + +@end + +@implementation HippyWeakProxy + ++ (instancetype)weakProxyForObject:(id)target { + HippyWeakProxy *proxy = [HippyWeakProxy alloc]; + proxy.target = target; + return proxy; +} + +- (id)forwardingTargetForSelector:(SEL)aSelector { + return _target; +} + +- (BOOL)respondsToSelector:(SEL)aSelector { + return [_target respondsToSelector:aSelector]; +} + +#pragma mark Handling Unimplemented Methods + +- (void)forwardInvocation:(NSInvocation *)invocation { + // Fallback for when target is nil. Don't do anything, just return 0/NULL/nil. + // The method signature we've received to get here is just a dummy to keep `doesNotRecognizeSelector:` from firing. + // We can't really handle struct return types here because we don't know the length. + void *nullPointer = NULL; + [invocation setReturnValue:&nullPointer]; +} + +- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { + // We only get here if `forwardingTargetForSelector:` returns nil. + // In that case, our weak target has been reclaimed. Return a dummy method signature to keep `doesNotRecognizeSelector:` from firing. + // We'll emulate the Obj-c messaging nil behavior by setting the return value to nil in `forwardInvocation:`, but we'll assume that the return + // value is `sizeof(void *)`. Other libraries handle this situation by making use of a global method signature cache, but that seems heavier than + // necessary and has issues as well. See https://www.mikeash.com/pyblog/friday-qa-2010-02-26-futures.html and + // https://github.com/steipete/PSTDelegateProxy/issues/1 for examples of using a method signature cache. + return [NSObject instanceMethodSignatureForSelector:@selector(init)]; +} + +@end diff --git a/framework/ios/utils/NSObject+CtxValue.h b/framework/ios/utils/NSObject+CtxValue.h index 5541198173b..50ad7be36d5 100644 --- a/framework/ios/utils/NSObject+CtxValue.h +++ b/framework/ios/utils/NSObject+CtxValue.h @@ -21,7 +21,7 @@ */ #import -#import "MacroDefines.h" +#import "HippyDefines.h" #include @@ -77,6 +77,6 @@ using CtxPtr = std::shared_ptr; @end -HP_EXTERN id ObjectFromCtxValue(CtxPtr context, CtxValuePtr value); +HIPPY_EXTERN id ObjectFromCtxValue(CtxPtr context, CtxValuePtr value); NS_ASSUME_NONNULL_END diff --git a/framework/ios/utils/NSObject+CtxValue.mm b/framework/ios/utils/NSObject+CtxValue.mm index 17e07af8083..c33a8fb3082 100644 --- a/framework/ios/utils/NSObject+CtxValue.mm +++ b/framework/ios/utils/NSObject+CtxValue.mm @@ -21,7 +21,7 @@ */ #import "NSObject+CtxValue.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" #include "driver/napi/js_ctx.h" #include "driver/napi/js_ctx_value.h" @@ -32,7 +32,7 @@ @implementation NSObject (CtxValue) - (CtxValuePtr)convertToCtxValue:(const CtxPtr &)context; { @autoreleasepool { - HPAssert(NO, @"%@ must implemente convertToCtxValue method", NSStringFromClass([self class])); + HippyAssert(NO, @"%@ must implemente convertToCtxValue method", NSStringFromClass([self class])); std::unordered_map valueMap; return context->CreateObject(valueMap); } diff --git a/framework/ios/utils/jsc/NSObject+JSValue.h b/framework/ios/utils/jsc/NSObject+JSValue.h index 88efad4ba83..0ae0fa74ed0 100644 --- a/framework/ios/utils/jsc/NSObject+JSValue.h +++ b/framework/ios/utils/jsc/NSObject+JSValue.h @@ -22,7 +22,7 @@ #import #import -#import "MacroDefines.h" +#import "HippyDefines.h" NS_ASSUME_NONNULL_BEGIN @@ -50,6 +50,6 @@ NS_ASSUME_NONNULL_BEGIN @end -HP_EXTERN id ObjectFromJSValueRef(JSGlobalContextRef const context, JSValueRef const value, JSValueRef _Nonnull * _Nonnull exception); +HIPPY_EXTERN id ObjectFromJSValueRef(JSGlobalContextRef const context, JSValueRef const value, JSValueRef _Nonnull * _Nonnull exception); NS_ASSUME_NONNULL_END diff --git a/framework/ios/utils/jsc/NSObject+JSValue.m b/framework/ios/utils/jsc/NSObject+JSValue.m index b767c69ff63..3181893264f 100644 --- a/framework/ios/utils/jsc/NSObject+JSValue.m +++ b/framework/ios/utils/jsc/NSObject+JSValue.m @@ -21,7 +21,7 @@ */ #import "NSObject+JSValue.h" -#import "HPLog.h" +#import "HippyLog.h" @implementation NSObject (JSValue) @@ -34,7 +34,7 @@ - (JSValue *)toJSValueInContext:(JSContext *)context { [self isKindOfClass:NSClassFromString(@"NSNull")]) { } else { - HPLogError(@"unsupport type to JSValue:%@", NSStringFromClass([self class])); + HippyLogError(@"unsupport type to JSValue:%@", NSStringFromClass([self class])); } #endif //DEBUG return [JSValue valueWithObject:self inContext:context]; @@ -86,7 +86,7 @@ - (JSValue *)toJSValueInContext:(JSContext *)context { size_t length = [self length]; void *data = malloc(length); if (!data) { - HPLogError(@"out of memory, NSData to JSValue memory allocation failure"); + HippyLogError(@"out of memory, NSData to JSValue memory allocation failure"); return [JSValue valueWithObject:self inContext:context]; } [self getBytes:data length:length]; diff --git a/framework/ios/utils/v8/NSObject+V8Value.h b/framework/ios/utils/v8/NSObject+V8Value.h index 0a03330d308..537426cb5c5 100644 --- a/framework/ios/utils/v8/NSObject+V8Value.h +++ b/framework/ios/utils/v8/NSObject+V8Value.h @@ -70,8 +70,8 @@ NS_ASSUME_NONNULL_BEGIN @end -HP_EXTERN id ObjectFromV8Value(v8::Local value, v8::Isolate *isolate, v8::Local context); +HIPPY_EXTERN id ObjectFromV8Value(v8::Local value, v8::Isolate *isolate, v8::Local context); -HP_EXTERN NSString *TryToFetchStringFromV8Value(v8::Local value, v8::Isolate *isolate); +HIPPY_EXTERN NSString *TryToFetchStringFromV8Value(v8::Local value, v8::Isolate *isolate); NS_ASSUME_NONNULL_END diff --git a/framework/ios/utils/v8/NSObject+V8Value.mm b/framework/ios/utils/v8/NSObject+V8Value.mm index fe37133afd2..5776b27dc7f 100644 --- a/framework/ios/utils/v8/NSObject+V8Value.mm +++ b/framework/ios/utils/v8/NSObject+V8Value.mm @@ -21,19 +21,19 @@ */ #import "NSObject+V8Value.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" @implementation NSObject (V8Value) - (v8::Local)toV8ValueInIsolate:(v8::Isolate *)isolate context:(v8::Local)context { - HPAssert(isolate, @"ios must not be null for object convert"); + HippyAssert(isolate, @"ios must not be null for object convert"); #ifdef DEBUG BOOL isRightType = [self isKindOfClass:[NSArray class]] || [self isKindOfClass:[NSDictionary class]] || [self isKindOfClass:[NSData class]] || [self isKindOfClass:[NSString class]] || [self isKindOfClass:[NSNumber class]]; - HPAssert(isRightType, @"toV8ValueInIsolate is not supported by %@ class", NSStringFromClass([self class])); + HippyAssert(isRightType, @"toV8ValueInIsolate is not supported by %@ class", NSStringFromClass([self class])); #endif v8::Local object = v8::Object::New(isolate); return object; @@ -44,7 +44,7 @@ @implementation NSObject (V8Value) @implementation NSArray (V8Value) - (v8::Local)toV8ValueInIsolate:(v8::Isolate *)isolate context:(v8::Local)context { - HPAssert(isolate, @"ios must not be null for array convert"); + HippyAssert(isolate, @"ios must not be null for array convert"); size_t count = [self count]; v8::Local elements[count]; for (size_t i = 0; i < count; i++) { @@ -59,7 +59,7 @@ @implementation NSArray (V8Value) @implementation NSDictionary (V8Value) - (v8::Local)toV8ValueInIsolate:(v8::Isolate *)isolate context:(v8::Local)context { - HPAssert(isolate, @"ios must not be null for dictionary convert"); + HippyAssert(isolate, @"ios must not be null for dictionary convert"); v8::Local object = v8::Object::New(isolate); for (id key in self) { id value = [self objectForKey:key]; @@ -81,7 +81,7 @@ static void ArrayBufferDataDeleter(void* data, size_t length, void* deleter_data #endif //V8_MAJOR_VERSION >= 9 - (v8::Local)toV8ValueInIsolate:(v8::Isolate *)isolate context:(v8::Local)context { - HPAssert(isolate, @"ios must not be null for data convert"); + HippyAssert(isolate, @"ios must not be null for data convert"); size_t length = [self length]; void *buffer = malloc(length); if (!buffer) { @@ -106,7 +106,7 @@ @implementation NSString (V8Value) } - (v8::Local)toV8StringInIsolate:(v8::Isolate *)isolate { - HPAssert(isolate, @"ios must not be null for string convert"); + HippyAssert(isolate, @"ios must not be null for string convert"); const char *p = [self UTF8String]?:""; v8::MaybeLocal string = v8::String::NewFromUtf8(isolate, p); return string.ToLocalChecked(); @@ -117,7 +117,7 @@ @implementation NSString (V8Value) @implementation NSNumber (V8Value) - (v8::Local)toV8ValueInIsolate:(v8::Isolate *)isolate context:(v8::Local)context { - HPAssert(isolate, @"ios must not be null for number convert"); + HippyAssert(isolate, @"ios must not be null for number convert"); v8::Local number = v8::Number::New(isolate, [self doubleValue]); return number; } @@ -148,7 +148,7 @@ id ObjectFromV8Value(v8::Local value, v8::Isolate *isolate, v8::Local return nil; } else if (value->IsString()) { - HPAssert(isolate, @"isolate must not be null for string value"); + HippyAssert(isolate, @"isolate must not be null for string value"); v8::Local string = value.As(); int len = string->Length(); if (string->IsOneByte()) { @@ -165,7 +165,7 @@ id ObjectFromV8Value(v8::Local value, v8::Isolate *isolate, v8::Local } } else if (value->IsStringObject()) { - HPAssert(isolate, @"isolate must not be null for string value"); + HippyAssert(isolate, @"isolate must not be null for string value"); v8::Local stringObj = value.As(); return ObjectFromV8Value(stringObj->ValueOf(), isolate, context); } @@ -238,7 +238,7 @@ id ObjectFromV8Value(v8::Local value, v8::Isolate *isolate, v8::Local NSMutableDictionary *keysValues = [NSMutableDictionary dictionaryWithCapacity:length]; for (uint32_t i = 0; i < length; i++) { v8::Local key = props->Get(context, i).ToLocalChecked(); - HPAssert(key->IsString(), @"ObjectFromV8Value only supports keys as string"); + HippyAssert(key->IsString(), @"ObjectFromV8Value only supports keys as string"); if (!key->IsString()) { continue; } @@ -253,7 +253,7 @@ id ObjectFromV8Value(v8::Local value, v8::Isolate *isolate, v8::Local else { #ifdef DEBUG - HPAssert(NO, @"no implementation ObjectFromV8Value for type %@", ObjectFromV8Value(value->TypeOf(isolate), isolate, context)); + HippyAssert(NO, @"no implementation ObjectFromV8Value for type %@", ObjectFromV8Value(value->TypeOf(isolate), isolate, context)); #endif return nil; } diff --git a/hippy.podspec b/hippy.podspec index 838b2182259..baeae08812d 100644 --- a/hippy.podspec +++ b/hippy.podspec @@ -8,35 +8,20 @@ layout_engine = "Taitank" js_engine = "jsc" -use_frameworks = false; Pod::Spec.new do |s| if ENV["layout_engine"] layout_engine = ENV["layout_engine"] end - if ENV["use_frameworks"] - use_frameworks = true - end if ENV["js_engine"] js_engine = ENV["js_engine"] end puts "layout engine is #{layout_engine}, js engine is #{js_engine}" - puts "use_frameworks trigger is #{use_frameworks}" - if use_frameworks - framework_header_path = '${PODS_CONFIGURATION_BUILD_DIR}/hippy/hippy.framework/Headers' - s.module_map = false; - end - puts 'hippy.podspec read begins' + + s.name = 'hippy' s.version = '3.0.0' s.summary = 'Hippy Cross Platform Framework' - -# This description is used to generate tags and improve search results. -# * Think: What does it do? Why did you write it? What is the focus? -# * Try to keep it short, snappy and to the point. -# * Write the description between the DESC delimiters below. -# * Finally, don't worry about the indent, CocoaPods strips it! - s.description = <<-DESC Hippy is designed for developers to easily build cross-platform and high-performance awesome apps. DESC @@ -46,6 +31,7 @@ Pod::Spec.new do |s| s.source = {:git => 'https://github.com/Tencent/Hippy.git', :tag => s.version} s.platform = :ios s.ios.deployment_target = '11.0' + s.module_map = false; # hippy3暂未支持module #prepare_command not working for subspecs,so we remove devtools script from devtools subspec to root s.prepare_command = <<-CMD @@ -72,6 +58,8 @@ Pod::Spec.new do |s| framework.dependency 'hippy/Base' framework.dependency 'hippy/JSDriver' framework.dependency 'hippy/Image' + framework.dependency 'hippy/iOSVFS' + framework.dependency 'hippy/NativeRenderer' puts 'hippy subspec \'framework\' read end' end @@ -81,13 +69,8 @@ Pod::Spec.new do |s| footstone.source_files = ['modules/footstone/**/*.{h,cc}'] footstone.public_header_files = ['modules/footstone/**/*.h'] footstone.exclude_files = ['modules/footstone/include/footstone/platform/adr', 'modules/footstone/src/platform/adr'] - if use_frameworks - header_search_paths = "#{framework_header_path}" + " #{framework_header_path}/include" - footstone.header_mappings_dir = 'modules/footstone' - else - header_search_paths = '${PODS_ROOT}/hippy/modules/footstone/include' + - ' ${PODS_ROOT}/hippy/modules/footstone' - end + footstone.header_mappings_dir = 'modules/footstone/include/' + header_search_paths = '$(PODS_TARGET_SRCROOT)/modules/footstone/include' + ' $(PODS_TARGET_SRCROOT)/modules/footstone' footstone.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', 'GCC_PREPROCESSOR_DEFINITIONS[config=Release]' => '${inherited} NDEBUG=1', @@ -95,9 +78,6 @@ Pod::Spec.new do |s| 'GCC_ENABLE_CPP_RTTI' => false, 'HEADER_SEARCH_PATHS' => header_search_paths } - footstone.user_target_xcconfig = { - 'HEADER_SEARCH_PATHS' => header_search_paths - } footstone.preserve_path = 'modules/footstone' puts 'hippy subspec \'footstone\' read end' end @@ -139,22 +119,15 @@ Pod::Spec.new do |s| puts 'hippy subspec \'vfs\' read begin' vfs.libraries = 'c++' vfs.source_files = ['modules/vfs/native/**/*.{h,cc}'] - vfs.public_header_files = ['modules/vfs/native/include/vfs/**/*.h'] - if use_frameworks - header_search_paths = framework_header_path - vfs.header_mappings_dir = 'modules/vfs/native/include' - else - header_search_paths = '${PODS_ROOT}/hippy/modules/vfs/native/include' - end + vfs.public_header_files = ['modules/vfs/native/include/**/*.h'] + vfs.header_mappings_dir = 'modules/vfs/native/include/' + header_search_paths = '$(PODS_TARGET_SRCROOT)/modules/vfs/native/include/' vfs.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', 'HEADER_SEARCH_PATHS' => header_search_paths, 'GCC_ENABLE_CPP_EXCEPTIONS' => false, 'GCC_ENABLE_CPP_RTTI' => false, } - vfs.user_target_xcconfig = { - 'HEADER_SEARCH_PATHS' => header_search_paths - } vfs.preserve_path = 'modules/vfs/native' vfs.dependency 'hippy/Footstone' puts 'hippy subspec \'vfs\' read end' @@ -182,6 +155,7 @@ Pod::Spec.new do |s| driver.frameworks = 'JavaScriptCore' driver.source_files = ['driver/js/include/**/*.h', 'driver/js/src/**/*.cc'] driver.public_header_files = 'driver/js/include/**/*.h' + driver.header_mappings_dir = 'driver/js/include/' if js_engine == "jsc" driver.exclude_files = [ 'driver/js/include/driver/napi/v8', @@ -210,12 +184,7 @@ Pod::Spec.new do |s| 'driver/js/src/vm/jsc'] end - if use_frameworks - header_search_paths = framework_header_path - driver.header_mappings_dir = 'driver/js/include' - else - header_search_paths = '${PODS_ROOT}/hippy/driver/js/include/' - end + header_search_paths = '$(PODS_TARGET_SRCROOT)/driver/js/include/' definition_engine = '' if js_engine == "jsc" definition_engine = 'JS_JSC=1' @@ -230,9 +199,6 @@ Pod::Spec.new do |s| 'GCC_ENABLE_CPP_EXCEPTIONS' => false, 'GCC_ENABLE_CPP_RTTI' => false, } - driver.user_target_xcconfig = { - 'HEADER_SEARCH_PATHS' => header_search_paths, - } driver.dependency 'hippy/Footstone' driver.dependency 'hippy/Dom' driver.dependency 'hippy/iOSVFS' @@ -257,12 +223,7 @@ Pod::Spec.new do |s| dom_source_files = Array['dom/include/**/*.h', 'dom/src/**/*.cc'] dom_exclude_files = Array['dom/src/dom/*unittests.cc', 'dom/src/dom/tools'] - if use_frameworks - dom_pod_target_header_path = framework_header_path - dom.header_mappings_dir = 'dom/include' - else - dom_pod_target_header_path = '${PODS_ROOT}/hippy/dom/include/' - end + dom_pod_target_header_path = '$(PODS_TARGET_SRCROOT)/dom/include/' if layout_engine == "Taitank" dom_exclude_files.append('dom/include/dom/yoga_layout_node.h') dom_exclude_files.append('dom/src/dom/yoga_layout_node.cc') @@ -274,6 +235,7 @@ Pod::Spec.new do |s| dom.libraries = 'c++' dom.source_files = dom_source_files dom.public_header_files = ['dom/include/**/*.h'] + dom.header_mappings_dir = 'dom/include/' dom.exclude_files = dom_exclude_files dom.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', @@ -281,9 +243,6 @@ Pod::Spec.new do |s| 'GCC_ENABLE_CPP_EXCEPTIONS' => false, 'GCC_ENABLE_CPP_RTTI' => false, } - dom.user_target_xcconfig = { - 'HEADER_SEARCH_PATHS' => dom_pod_target_header_path - } dom.dependency 'hippy/Footstone' if layout_engine == "Taitank" dom.dependency 'hippy/Taitank' @@ -316,11 +275,7 @@ Pod::Spec.new do |s| puts 'hippy subspec \'Taitank\' read begin' taitank.source_files = ['dom/dom_project/_deps/taitank-src/src/*.{h,cc}'] taitank.public_header_files = ['dom/include/dom/taitank_layout_node.h', 'dom/dom_project/_deps/taitank-src/src/*.h'] - if use_frameworks - header_search_paths = framework_header_path - else - header_search_paths = '${PODS_ROOT}/hippy/dom/dom_project/_deps/taitank-src/src' - end + header_search_paths = '$(PODS_TARGET_SRCROOT)/dom/dom_project/_deps/taitank-src/src' taitank.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', 'HEADER_SEARCH_PATHS' => header_search_paths, @@ -336,11 +291,7 @@ Pod::Spec.new do |s| puts 'hippy subspec \'yoga\' read begin' yoga.source_files = ['dom/dom_project/_deps/yoga-src/yoga/**/*.{c,h,cpp}'] yoga.public_header_files = ['dom/include/dom/yoga_layout_node.h', 'dom/dom_project/_deps/yoga-src/yoga/**/*.h'] - if use_frameworks - header_search_paths = framework_header_path - else - header_search_paths = '${PODS_ROOT}/hippy/dom/dom_project/_deps/yoga-src' - end + header_search_paths = '$(PODS_TARGET_SRCROOT)/dom/dom_project/_deps/yoga-src' yoga.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', 'HEADER_SEARCH_PATHS' => header_search_paths, @@ -401,25 +352,16 @@ Pod::Spec.new do |s| #devtools_backend 'devtools/devtools-backend/**/*.{h,hpp,cc}', ] - if use_frameworks - pod_search_path = "#{framework_header_path}/devtools-integration/ios/DevtoolsBackend/_deps/asio-src/asio/include" + - " #{framework_header_path}/devtools-integration/ios/DevtoolsBackend/_deps/json-src/include" + - " #{framework_header_path}/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/include" + - " #{framework_header_path}/devtools-integration/ios/DevtoolsBackend/_deps/websocketpp-src" + - " #{framework_header_path}/devtools-integration/native/include" + - " #{framework_header_path}/devtools-backend/include" + - " #{framework_header_path}/devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/arch" - devtools.header_mappings_dir = 'devtools' - else - pod_search_path = '${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/asio-src/asio/include' + - ' ${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/json-src/include' + - ' ${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/include' + - ' ${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/websocketpp-src' + - ' ${PODS_ROOT}/hippy/devtools/devtools-integration/native/include' + - ' ${PODS_ROOT}/hippy/devtools/devtools-backend/include' + - ' ${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/arch' - end + + pod_search_path = '$(PODS_TARGET_SRCROOT)/devtools/devtools-integration/ios/DevtoolsBackend/_deps/asio-src/asio/include' + + ' $(PODS_TARGET_SRCROOT)/devtools/devtools-integration/ios/DevtoolsBackend/_deps/json-src/include' + + ' $(PODS_TARGET_SRCROOT)/devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/include' + + ' $(PODS_TARGET_SRCROOT)/devtools/devtools-integration/ios/DevtoolsBackend/_deps/websocketpp-src' + + ' $(PODS_TARGET_SRCROOT)/devtools/devtools-integration/native/include' + + ' $(PODS_TARGET_SRCROOT)/devtools/devtools-backend/include' + + ' $(PODS_TARGET_SRCROOT)/devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/arch' + devtools.pod_target_xcconfig = { 'HEADER_SEARCH_PATHS' => pod_search_path, 'GCC_PREPROCESSOR_DEFINITIONS' => 'ENABLE_INSPECTOR=1 ASIO_NO_TYPEID ASIO_NO_EXCEPTIONS ASIO_DISABLE_ALIGNOF _WEBSOCKETPP_NO_EXCEPTIONS_ JSON_NOEXCEPTION BASE64_STATIC_DEFINE', @@ -444,7 +386,7 @@ Pod::Spec.new do |s| v8.public_header_files = ['v8forios/v8/include'] v8.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', - 'HEADER_SEARCH_PATHS' => '${PODS_ROOT}/hippy/v8forios/v8/include ${PODS_ROOT}/hippy/v8forios/v8/include/v8', + 'HEADER_SEARCH_PATHS' => '$(PODS_TARGET_SRCROOT)/v8forios/v8/include $(PODS_TARGET_SRCROOT)/v8forios/v8/include/v8', 'GCC_ENABLE_CPP_EXCEPTIONS' => false, 'GCC_ENABLE_CPP_RTTI' => false, } @@ -455,5 +397,4 @@ Pod::Spec.new do |s| end end - puts 'hippy.podspec read ends' end diff --git a/hippy_backup.podspec b/hippy_backup.podspec new file mode 100644 index 00000000000..0e32cc620b9 --- /dev/null +++ b/hippy_backup.podspec @@ -0,0 +1,453 @@ +# +# Be sure to run `pod lib lint hippy.podspec --verbose --use-libraries' to ensure this is a +# valid spec before submitting. +# +# Any lines starting with a # are optional, but their use is encouraged +# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html +# + +layout_engine = "Taitank" +js_engine = "jsc" +use_frameworks = false; + +Pod::Spec.new do |s| + if ENV["layout_engine"] + layout_engine = ENV["layout_engine"] + end + if ENV["use_frameworks"] + use_frameworks = true + end + if ENV["js_engine"] + js_engine = ENV["js_engine"] + end + puts "layout engine is #{layout_engine}, js engine is #{js_engine}" + puts "use_frameworks trigger is #{use_frameworks}" + if use_frameworks + framework_header_path = '${PODS_CONFIGURATION_BUILD_DIR}/hippy/hippy.framework/Headers' + s.module_map = false; + end + + s.name = 'hippy' + s.version = '3.0.0' + s.summary = 'Hippy Cross Platform Framework' + s.description = <<-DESC + Hippy is designed for developers to easily build cross-platform and high-performance awesome apps. + DESC + s.homepage = 'https://hippyjs.org' + s.license = { :type => 'Apache2', :file => 'LICENSE' } + s.author = 'OpenHippy Team' + s.source = {:git => 'https://github.com/Tencent/Hippy.git', :tag => s.version} + s.platform = :ios + s.ios.deployment_target = '11.0' + + #prepare_command not working for subspecs,so we remove devtools script from devtools subspec to root + s.prepare_command = <<-CMD + ./xcodeinitscript.sh "#{layout_engine}" "#{js_engine}" + CMD + + s.subspec 'Framework' do |framework| + puts 'hippy subspec \'framework\' read begin' + framework.source_files = 'framework/ios/**/*.{h,m,c,mm,s,cpp,cc}' + framework.public_header_files = 'framework/ios/**/*.h' + if js_engine == "jsc" + framework.exclude_files = ['framework/ios/base/enginewrapper/v8', 'framework/ios/utils/v8'] + elsif js_engine == "v8" + framework.exclude_files = ['framework/ios/base/enginewrapper/jsc', 'framework/ios/utils/jsc'] + else + framework.exclude_files = ['framework/ios/base/enginewrapper/jsc', 'framework/ios/utils/jsc', 'framework/ios/base/enginewrapper/v8', 'framework/ios/utils/v8'] + end + framework.libraries = 'c++' + framework.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + framework.dependency 'hippy/Base' + framework.dependency 'hippy/JSDriver' + framework.dependency 'hippy/Image' + framework.dependency 'hippy/iOSVFS' + framework.dependency 'hippy/NativeRenderer' + puts 'hippy subspec \'framework\' read end' + end + + s.subspec 'Footstone' do |footstone| + puts 'hippy subspec \'footstone\' read begin' + footstone.libraries = 'c++' + footstone.source_files = ['modules/footstone/**/*.{h,cc}'] + footstone.public_header_files = ['modules/footstone/**/*.h'] + footstone.exclude_files = ['modules/footstone/include/footstone/platform/adr', 'modules/footstone/src/platform/adr'] + if use_frameworks + header_search_paths = "#{framework_header_path}" + " #{framework_header_path}/include" + footstone.header_mappings_dir = 'modules/footstone' + else + header_search_paths = '${PODS_ROOT}/hippy/modules/footstone/include' + + ' ${PODS_ROOT}/hippy/modules/footstone' + end + footstone.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'GCC_PREPROCESSOR_DEFINITIONS[config=Release]' => '${inherited} NDEBUG=1', + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + 'HEADER_SEARCH_PATHS' => header_search_paths + } + footstone.user_target_xcconfig = { + 'HEADER_SEARCH_PATHS' => header_search_paths + } + footstone.preserve_path = 'modules/footstone' + puts 'hippy subspec \'footstone\' read end' + end + + s.subspec 'FootstoneUtils' do |footstoneutils| + puts 'hippy subspec \'footstoneutils\' read begin' + footstoneutils.libraries = 'c++' + footstoneutils.source_files = ['modules/ios/footstoneutils/*.{h,mm}'] + footstoneutils.public_header_files = ['modules/ios/footstoneutils/*.h'] + footstoneutils.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + footstoneutils.dependency 'hippy/Footstone' + footstoneutils.dependency 'hippy/Base' + puts 'hippy subspec \'footstoneutils\' read end' + end + + s.subspec 'Image' do |image| + puts 'hippy subspec \'image\' read begin' + image.libraries = 'c++' + image.frameworks = 'CoreServices' + image.public_header_files = 'modules/ios/image/*.h' + image.source_files = 'modules/ios/image/*.{h,m,mm}' + puts 'hippy subspec \'image\' read end' + end + + s.subspec 'Base' do |base| + puts 'hippy subspec \'base\' read begin' + base.libraries = 'c++' + base.source_files = ['modules/ios/base/*.{h,m,mm}', 'modules/ios/logutils/*.{h,mm}'] + base.public_header_files = ['modules/ios/base/*.h', 'modules/ios/logutils/*.h'] + base.dependency 'hippy/Footstone' + puts 'hippy subspec \'base\' read end' + end + + s.subspec 'VFS' do |vfs| + puts 'hippy subspec \'vfs\' read begin' + vfs.libraries = 'c++' + vfs.source_files = ['modules/vfs/native/**/*.{h,cc}'] + vfs.public_header_files = ['modules/vfs/native/include/vfs/**/*.h'] + if use_frameworks + header_search_paths = framework_header_path + vfs.header_mappings_dir = 'modules/vfs/native/include' + else + header_search_paths = '${PODS_ROOT}/hippy/modules/vfs/native/include' + end + vfs.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'HEADER_SEARCH_PATHS' => header_search_paths, + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + vfs.user_target_xcconfig = { + 'HEADER_SEARCH_PATHS' => header_search_paths + } + vfs.preserve_path = 'modules/vfs/native' + vfs.dependency 'hippy/Footstone' + puts 'hippy subspec \'vfs\' read end' + end + + s.subspec 'iOSVFS' do |iosvfs| + puts 'hippy subspec \'iosvfs\' read begin' + iosvfs.libraries = 'c++' + iosvfs.source_files = ['modules/vfs/ios/*.{h,m,mm}'] + iosvfs.public_header_files = ['modules/vfs/ios/*.h'] + iosvfs.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + iosvfs.dependency 'hippy/VFS' + iosvfs.dependency 'hippy/Footstone' + iosvfs.dependency 'hippy/FootstoneUtils' + puts 'hippy subspec \'iosvfs\' read end' + end + + s.subspec 'JSDriver' do |driver| + puts 'hippy subspec \'driver\' read begin' + driver.libraries = 'c++' + driver.frameworks = 'JavaScriptCore' + driver.source_files = ['driver/js/include/**/*.h', 'driver/js/src/**/*.cc'] + driver.public_header_files = 'driver/js/include/**/*.h' + if js_engine == "jsc" + driver.exclude_files = [ + 'driver/js/include/driver/napi/v8', + 'driver/js/src/napi/v8', + 'driver/js/include/driver/runtime', + 'driver/js/src/runtime', + 'driver/js/include/driver/vm/v8', + 'driver/js/src/vm/v8'] + elsif js_engine == "v8" + driver.exclude_files = [ + 'driver/js/include/driver/napi/jsc', + 'driver/js/src/napi/jsc', + 'driver/js/include/driver/vm/jsc', + 'driver/js/src/vm/jsc'] + else + driver.exclude_files = [ + 'driver/js/include/driver/napi/v8', + 'driver/js/src/napi/v8', + 'driver/js/include/driver/runtime', + 'driver/js/src/runtime', + 'driver/js/include/vm/v8', + 'driver/js/src/vm/v8', + 'driver/js/include/driver/napi/jsc', + 'driver/js/src/napi/jsc', + 'driver/js/include/vm/jsc', + 'driver/js/src/vm/jsc'] + end + + if use_frameworks + header_search_paths = framework_header_path + driver.header_mappings_dir = 'driver/js/include' + else + header_search_paths = '${PODS_ROOT}/hippy/driver/js/include/' + end + definition_engine = '' + if js_engine == "jsc" + definition_engine = 'JS_JSC=1' + elsif js_engine == "v8" + definition_engine = 'JS_V8=1' + else + end + driver.pod_target_xcconfig = { + 'HEADER_SEARCH_PATHS' => header_search_paths, + 'GCC_PREPROCESSOR_DEFINITIONS' => definition_engine, + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + driver.user_target_xcconfig = { + 'HEADER_SEARCH_PATHS' => header_search_paths, + } + driver.dependency 'hippy/Footstone' + driver.dependency 'hippy/Dom' + driver.dependency 'hippy/iOSVFS' + driver.preserve_path = 'driver/js' + puts 'hippy subspec \'driver\' read end' + end + + s.subspec 'NativeRenderer' do |renderer| + puts 'hippy subspec \'nativerenderer\' read begin' + renderer.libraries = 'c++' + renderer.source_files = 'renderer/native/ios/**/*.{h,m,mm}' + renderer.public_header_files = 'renderer/native/ios/**/*.h' + renderer.dependency 'hippy/Base' + renderer.dependency 'hippy/DomUtils' + renderer.dependency 'hippy/Image' + renderer.dependency 'hippy/iOSVFS' + puts 'hippy subspec \'nativerenderer\' read end' + end + + s.subspec 'Dom' do |dom| + puts 'hippy subspec \'dom\' read begin' + dom_source_files = Array['dom/include/**/*.h', 'dom/src/**/*.cc'] + dom_exclude_files = Array['dom/src/dom/*unittests.cc', + 'dom/src/dom/tools'] + if use_frameworks + dom_pod_target_header_path = framework_header_path + dom.header_mappings_dir = 'dom/include' + else + dom_pod_target_header_path = '${PODS_ROOT}/hippy/dom/include/' + end + if layout_engine == "Taitank" + dom_exclude_files.append('dom/include/dom/yoga_layout_node.h') + dom_exclude_files.append('dom/src/dom/yoga_layout_node.cc') + elsif layout_engine == "Yoga" + dom_exclude_files.append('dom/include/dom/taitank_layout_node.h') + dom_exclude_files.append('dom/src/dom/taitank_layout_node.cc') + end + + dom.libraries = 'c++' + dom.source_files = dom_source_files + dom.public_header_files = ['dom/include/**/*.h'] + dom.exclude_files = dom_exclude_files + dom.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'HEADER_SEARCH_PATHS' => dom_pod_target_header_path, + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + dom.user_target_xcconfig = { + 'HEADER_SEARCH_PATHS' => dom_pod_target_header_path + } + dom.dependency 'hippy/Footstone' + if layout_engine == "Taitank" + dom.dependency 'hippy/Taitank' + elsif layout_engine == "Yoga" + dom.dependency 'hippy/Yoga' + end + dom.preserve_path = 'dom' + puts 'hippy subspec \'dom\' read end' + end + + s.subspec 'DomUtils' do |domutils| + puts 'hippy subspec \'domutils\' read begin' + dom_source_files = Array['modules/ios/domutils/*.{h,mm}'] + domutils.libraries = 'c++' + domutils.source_files = dom_source_files + domutils.public_header_files = ['modules/ios/domutils/*.h'] + domutils.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + domutils.dependency 'hippy/Dom' + domutils.dependency 'hippy/FootstoneUtils' + domutils.dependency 'hippy/Base' + puts 'hippy subspec \'domutils\' read end' + end + + if layout_engine == "Taitank" + s.subspec 'Taitank' do |taitank| + puts 'hippy subspec \'Taitank\' read begin' + taitank.source_files = ['dom/dom_project/_deps/taitank-src/src/*.{h,cc}'] + taitank.public_header_files = ['dom/include/dom/taitank_layout_node.h', 'dom/dom_project/_deps/taitank-src/src/*.h'] + if use_frameworks + header_search_paths = framework_header_path + else + header_search_paths = '${PODS_ROOT}/hippy/dom/dom_project/_deps/taitank-src/src' + end + taitank.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'HEADER_SEARCH_PATHS' => header_search_paths, + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + taitank.libraries = 'c++' + taitank.preserve_path = 'dom/dom_project' + puts 'hippy subspec \'Taitank\' read end' + end + elsif layout_engine == "Yoga" + s.subspec 'Yoga' do |yoga| + puts 'hippy subspec \'yoga\' read begin' + yoga.source_files = ['dom/dom_project/_deps/yoga-src/yoga/**/*.{c,h,cpp}'] + yoga.public_header_files = ['dom/include/dom/yoga_layout_node.h', 'dom/dom_project/_deps/yoga-src/yoga/**/*.h'] + if use_frameworks + header_search_paths = framework_header_path + else + header_search_paths = '${PODS_ROOT}/hippy/dom/dom_project/_deps/yoga-src' + end + yoga.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'HEADER_SEARCH_PATHS' => header_search_paths, + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + yoga.libraries = 'c++' + yoga.preserve_path = 'dom/dom_project' + puts 'hippy subspec \'yoga\' read end' + end + end + + #devtools subspec + s.subspec 'DevTools' do |devtools| + puts 'hippy subspec \'devtools\' read begin' + devtools.libraries = 'c++' + devtools_exclude_files = Array.new; + if js_engine == "jsc" + devtools_exclude_files += ['devtools/devtools-integration/native/include/devtools/v8', 'devtools/devtools-integration/native/src/v8'] + elsif js_engine == "v8" + else + devtools_exclude_files += ['devtools/devtools-integration/native/include/devtools/v8', 'devtools/devtools-integration/native/src/v8'] + end + devtools.exclude_files = [ + #test files + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/**/*test*/**/*', + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/**/*test*', + #benchmark files + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/**/benchmark/**', + #js files + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/**/javascript/**', + #Dom includes all taitank or yoga files, and Devtools dependends on Dom, so let Dom does the including work, otherwise, 'duplicated symbols' error occurs + #taitank or yoga files + #currently Devtools specify taitank layout + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/taitank-*/**/*', + #other files + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/lib_openmp.c', + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/tables/table_generator.c', + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/arch/**/{dec,enc}_*.c', + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/bin/base64.c', + ] + devtools_exclude_files + devtools.public_header_files = [ + 'devtools/devtools-integration/native/include/devtools/devtools_data_source.h', + #devtools_integration/native + 'devtools/devtools-integration/native/**/*.h', + #devtools_backend + 'devtools/devtools-backend/**/*.{h,hpp}', + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/*-src/**/*.{h,hpp,ipp}', + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/tables/*.h', + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-build/config.h', + ] + devtools.source_files = [ + #devtools_integration/native + 'devtools/devtools-integration/native/**/*.{h,cc}', + #devtools_integration/ios + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/*-src/**/*.{h,hpp,c,cc,ipp}', + 'devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-build/config.h', + #devtools_backend + 'devtools/devtools-backend/**/*.{h,hpp,cc}', + ] + if use_frameworks + pod_search_path = "#{framework_header_path}/devtools-integration/ios/DevtoolsBackend/_deps/asio-src/asio/include" + + " #{framework_header_path}/devtools-integration/ios/DevtoolsBackend/_deps/json-src/include" + + " #{framework_header_path}/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/include" + + " #{framework_header_path}/devtools-integration/ios/DevtoolsBackend/_deps/websocketpp-src" + + " #{framework_header_path}/devtools-integration/native/include" + + " #{framework_header_path}/devtools-backend/include" + + " #{framework_header_path}/devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/arch" + + devtools.header_mappings_dir = 'devtools' + else + pod_search_path = '${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/asio-src/asio/include' + + ' ${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/json-src/include' + + ' ${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/include' + + ' ${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/websocketpp-src' + + ' ${PODS_ROOT}/hippy/devtools/devtools-integration/native/include' + + ' ${PODS_ROOT}/hippy/devtools/devtools-backend/include' + + ' ${PODS_ROOT}/hippy/devtools/devtools-integration/ios/DevtoolsBackend/_deps/base64-src/lib/arch' + end + devtools.pod_target_xcconfig = { + 'HEADER_SEARCH_PATHS' => pod_search_path, + 'GCC_PREPROCESSOR_DEFINITIONS' => 'ENABLE_INSPECTOR=1 ASIO_NO_TYPEID ASIO_NO_EXCEPTIONS ASIO_DISABLE_ALIGNOF _WEBSOCKETPP_NO_EXCEPTIONS_ JSON_NOEXCEPTION BASE64_STATIC_DEFINE', + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + devtools.user_target_xcconfig = { + 'GCC_PREPROCESSOR_DEFINITIONS' => 'ENABLE_INSPECTOR=1' + } + devtools.dependency 'hippy/Footstone' + devtools.dependency 'hippy/Dom' + devtools.dependency 'hippy/VFS' + devtools.preserve_path = 'devtools' + puts 'hippy subspec \'devtools\' read end' + end + + if js_engine == "v8" + s.subspec 'v8' do |v8| + puts 'hippy subspec \'v8\' read begin' + v8.source_files = ['v8forios/v8/include'] + v8.public_header_files = ['v8forios/v8/include'] + v8.pod_target_xcconfig = { + 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17', + 'HEADER_SEARCH_PATHS' => '${PODS_ROOT}/hippy/v8forios/v8/include ${PODS_ROOT}/hippy/v8forios/v8/include/v8', + 'GCC_ENABLE_CPP_EXCEPTIONS' => false, + 'GCC_ENABLE_CPP_RTTI' => false, + } + v8.libraries = 'c++' + v8.vendored_library = 'v8forios/v8/libv8.a' + v8.preserve_path = 'v8forios/v8' + puts 'hippy subspec \'v8\' read end' + end + end + +end diff --git a/modules/ios/base/HPToolUtils.h b/modules/ios/base/HPToolUtils.h deleted file mode 100644 index c4bd20d7421..00000000000 --- a/modules/ios/base/HPToolUtils.h +++ /dev/null @@ -1,112 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * Hippy available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import -#import -#import - -#include "MacroDefines.h" - -NS_ASSUME_NONNULL_BEGIN - - -// Check is we are currently on the main queue (not to be confused with -// the main thread, which is not neccesarily the same thing) -// https://twitter.com/olebegemann/status/738656134731599872 -HP_EXTERN BOOL HPIsMainQueue(void); - -// Execute the specified block on the main queue. Unlike dispatch_async() -// this will execute immediately if we're already on the main queue. -HP_EXTERN void HPExecuteOnMainQueue(dispatch_block_t block); - -// Deprecated - do not use. -HP_EXTERN void HPExecuteOnMainThread(dispatch_block_t block, BOOL sync); - -// Method swizzling -HP_EXTERN void HPSwapClassMethods(Class cls, SEL original, SEL replacement); -HP_EXTERN void HPSwapInstanceMethods(Class cls, SEL original, SEL replacement); - -// Module subclass support -HP_EXTERN BOOL HPClassOverridesClassMethod(Class cls, SEL selector); -HP_EXTERN BOOL HPClassOverridesInstanceMethod(Class cls, SEL selector); - -// Returns YES if HP is running in a test environment -HP_EXTERN BOOL HPRunningInTestEnvironment(void); - -// Returns YES if HP is running in an iOS App Extension -HP_EXTERN BOOL HPRunningInAppExtension(void); - -// Returns the shared UIApplication instance, or nil if running in an App Extension -HP_EXTERN UIApplication *__nullable HPSharedApplication(void); - -// Returns the current main window, useful if you need to access the root view -// or view controller -HP_EXTERN UIWindow *__nullable HPKeyWindow(void); - -// Returns the presented view controller, useful if you need -// e.g. to present a modal view controller or alert over it -HP_EXTERN UIViewController *__nullable HPPresentedViewController(void); - -// Does this device support force touch (aka 3D Touch)? -HP_EXTERN BOOL HPForceTouchAvailable(void); - -// Create an NSError in the HPErrorDomain -HP_EXTERN NSError *HPErrorWithMessage(NSString *message); - -// Create an NSError in the HPErrorDomain -HP_EXTERN NSError *HPErrorWithMessageAndModuleName(NSString *message, NSString *__nullable moduleName); - -// Create an NSError with HPFatalModuleName from another error -HP_EXTERN NSError *HPErrorFromErrorAndModuleName(NSError *error, NSString *__nullable moduleName); - -// Convert nil values to NSNull, and vice-versa -#define HPNullIfNil(value) (value ?: (id)kCFNull) -#define HPNilIfNull(value) (value == (id)kCFNull ? nil : value) - -// Convert NaN or infinite values to zero, as these aren't JSON-safe -HP_EXTERN double HPZeroIfNaN(double value); - -// Converts a CGColor to a hex string -HP_EXTERN NSString *HPColorToHexString(CGColorRef color); - -/** - * convert string to UIColor - * colorString could be 'fff','#fff','ffffff','#ffffff','ffffffff','#ffffffff' - * or 'red', 'green','blue'.etc - */ -HP_EXTERN UIColor *HPConvertStringToColor(NSString *colorString); - -HP_EXTERN UIColor *HPConvertNumberToColor(NSInteger colorNumber); - -// Get standard localized string (if it exists) -HP_EXTERN NSString *HPUIKitLocalizedString(NSString *string); - -// URL manipulation -HP_EXTERN NSString *__nullable HPGetURLQueryParam(NSURL *__nullable URL, NSString *param); -HP_EXTERN NSURL *__nullable HPURLByReplacingQueryParam(NSURL *__nullable URL, NSString *param, NSString *__nullable value); -HP_EXTERN NSURL *__nullable HPURLWithString(NSString *__nonnull URLString, NSString *__nullable baseURLString); -HP_EXTERN NSString *HPSchemeFromURLString(NSString *urlString); - -//Get String Encoding From HTTP URL Response -HP_EXTERN NSStringEncoding HPGetStringEncodingFromURLResponse(NSURLResponse *response); - -NS_ASSUME_NONNULL_END diff --git a/modules/ios/base/HPAsserts.h b/modules/ios/base/HippyAsserts.h similarity index 59% rename from modules/ios/base/HPAsserts.h rename to modules/ios/base/HippyAsserts.h index e5c83db37e4..1d16a401782 100644 --- a/modules/ios/base/HPAsserts.h +++ b/modules/ios/base/HippyAsserts.h @@ -23,145 +23,145 @@ #if __OBJC__ #import #endif -#import "MacroDefines.h" -#import "HPDriverStackFrame.h" -#import "HPToolUtils.h" +#import "HippyDefines.h" +#import "HippyJSStackFrame.h" +#import "HippyUtils.h" NS_ASSUME_NONNULL_BEGIN /** * This is the main assert macro that you should use. Asserts should be compiled out * in production builds. You can customize the assert behaviour by setting a custom - * assert handler through `HPSetAssertFunction`. + * assert handler through `HippySetAssertFunction`. */ #ifndef NS_BLOCK_ASSERTIONS -#define HPAssert(condition, ...) \ +#define HippyAssert(condition, ...) \ do { \ if ((condition) == 0) { \ - _HPAssertFormat(#condition, __FILE__, __LINE__, __func__, __VA_ARGS__); \ - if (HP_NSASSERT) { \ + _HippyAssertFormat(#condition, __FILE__, __LINE__, __func__, __VA_ARGS__); \ + if (HIPPY_DEBUG) { \ [[NSAssertionHandler currentHandler] handleFailureInFunction:@(__func__) file:@(__FILE__) lineNumber:__LINE__ \ description:__VA_ARGS__]; \ } \ } \ } while (false) #else -#define HPAssert(condition, ...) \ +#define HippyAssert(condition, ...) \ do { \ } while (false) #endif -HP_EXTERN void _HPAssertFormat(const char *, const char *, int, const char *, NSString *, ...) NS_FORMAT_FUNCTION(5, 6); +HIPPY_EXTERN void _HippyAssertFormat(const char *, const char *, int, const char *, NSString *, ...) NS_FORMAT_FUNCTION(5, 6); -#define HPAssertUnimplemented() \ +#define HippyAssertUnimplemented() \ do { \ - HPLogError(@"Not implemented in: %s", __FUNCTION__) \ + HippyLogError(@"Not implemented in: %s", __FUNCTION__) \ abort(); \ } while (0) /** * Report a fatal condition when executing. These calls will _NOT_ be compiled out * in production, and crash the app by default. You can customize the fatal behaviour - * by setting a custom fatal handler through `HPSetFatalHandler`. + * by setting a custom fatal handler through `HippySetFatalHandler`. */ -HP_EXTERN void HPFatal(NSError *error, NSDictionary *__nullable userInfo); +HIPPY_EXTERN void HippyFatal(NSError *error); -HP_EXTERN void HPHandleException(NSException *exception, NSDictionary *userInfo); +HIPPY_EXTERN void HippyHandleException(NSException *exception); /** * The default error domain to be used for HP errors. */ -HP_EXTERN NSString *const HPErrorDomain; +HIPPY_EXTERN NSString *const HippyErrorDomain; /** * JS Stack trace provided as part of an NSError's userInfo */ -HP_EXTERN NSString *const HPJSStackTraceKey; +HIPPY_EXTERN NSString *const HippyJSStackTraceKey; /** * Raw JS Stack trace string provided as part of an NSError's userInfo */ -HP_EXTERN NSString *const HPJSRawStackTraceKey; +HIPPY_EXTERN NSString *const HippyJSRawStackTraceKey; /** - * Name of fatal exceptions generated by HPFatal + * Name of fatal exceptions generated by HippyFatal */ -HP_EXTERN NSString *const HPFatalExceptionName; +HIPPY_EXTERN NSString *const HippyFatalExceptionName; /** - * Module Name of fatal exceptions generated by HPFatal + * Module Name of fatal exceptions generated by HippyFatal */ -HP_EXTERN NSString *const HPFatalModuleName; +HIPPY_EXTERN NSString *const HippyFatalModuleName; /** * A block signature to be used for custom assertion handling. */ -typedef void (^HPAssertFunction)(NSString *condition, NSString *fileName, NSNumber *lineNumber, NSString *function, NSString *message); +typedef void (^HippyAssertFunction)(NSString *condition, NSString *fileName, NSNumber *lineNumber, NSString *function, NSString *message); -typedef void (^HPFatalHandler)(NSError *error, NSDictionary *userInfo); +typedef void (^HippyFatalHandler)(NSError *error); -typedef void (^HPExceptionHandler)(NSException *e); +typedef void (^HippyExceptionHandler)(NSException *e); /** * Convenience macro for asserting that a parameter is non-nil/non-zero. */ -#define HPAssertParam(name) HPAssert(name, @"'%s' is a required parameter", #name) +#define HippyAssertParam(name) HippyAssert(name, @"'%s' is a required parameter", #name) /** * Convenience macro for asserting that we're running on main queue. */ -#define HPAssertMainQueue() HPAssert(HPIsMainQueue(), @"This function must be called on the main thread") +#define HippyAssertMainQueue() HippyAssert(HippyIsMainQueue(), @"This function must be called on the main thread") /** * Convenience macro for asserting that we're running off the main queue. */ -#define HPAssertNotMainQueue() HPAssert(!HPIsMainQueue(), @"This function must not be called on the main thread") +#define HippyAssertNotMainQueue() HippyAssert(!HippyIsMainQueue(), @"This function must not be called on the main thread") /** - * These methods get and set the current assert function called by the HPAssert + * These methods get and set the current assert function called by the HippyAssert * macros. You can use these to replace the standard behavior with custom assert * functionality. */ -HP_EXTERN void HPSetAssertFunction(HPAssertFunction assertFunction); -HP_EXTERN HPAssertFunction HPGetAssertFunction(void); +HIPPY_EXTERN void HippySetAssertFunction(HippyAssertFunction assertFunction); +HIPPY_EXTERN HippyAssertFunction HippyGetAssertFunction(void); /** * This appends additional code to the existing assert function, without * replacing the existing functionality. Useful if you just want to forward * assert info to an extra service without changing the default behavior. */ -HP_EXTERN void HPAddAssertFunction(HPAssertFunction assertFunction); +HIPPY_EXTERN void HippyAddAssertFunction(HippyAssertFunction assertFunction); /** * This method temporarily overrides the assert function while performing the * specified block. This is useful for testing purposes (to detect if a given * function asserts something) or to suppress or override assertions temporarily. */ -HP_EXTERN void HPPerformBlockWithAssertFunction(void (^block)(void), HPAssertFunction assertFunction); +HIPPY_EXTERN void HippyPerformBlockWithAssertFunction(void (^block)(void), HippyAssertFunction assertFunction); /** * Get the current thread's name (or the current queue, if in debug mode) */ -HP_EXTERN NSString *HPCurrentThreadName(void); +HIPPY_EXTERN NSString *HippyCurrentThreadName(void); /** - These methods get and set the current fatal handler called by the HPFatal method. + These methods get and set the current fatal handler called by the HippyFatal method. */ -HP_EXTERN void HPSetFatalHandler(HPFatalHandler fatalHandler); -HP_EXTERN HPFatalHandler HPGetFatalHandler(void); +HIPPY_EXTERN void HippySetFatalHandler(HippyFatalHandler fatalHandler); +HIPPY_EXTERN HippyFatalHandler HippyGetFatalHandler(void); -HP_EXTERN void HPSetExceptionHandler(HPExceptionHandler exceptionhandler); -HP_EXTERN HPExceptionHandler HPGetExceptionHandler(void); +HIPPY_EXTERN void HippySetExceptionHandler(HippyExceptionHandler exceptionhandler); +HIPPY_EXTERN HippyExceptionHandler HippyGetExceptionHandler(void); -HP_EXTERN NSString *HPFormatError(NSString *message, NSArray *stackTrace, NSUInteger maxMessageLength); +HIPPY_EXTERN NSString *HippyFormatError(NSString *message, NSArray *stackTrace, NSUInteger maxMessageLength); /** * Convenience macro to assert which thread is currently running (DEBUG mode only) */ #ifdef DEBUG -#define HPAssertThread(thread, format...) \ +#define HippyAssertThread(thread, format...) \ _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ - HPAssert([(id)thread isKindOfClass:[NSString class]] ? [HPCurrentThreadName() isEqualToString:(NSString *)thread] \ + HippyAssert([(id)thread isKindOfClass:[NSString class]] ? [HippyCurrentThreadName() isEqualToString:(NSString *)thread] \ : [(id)thread isKindOfClass:[NSThread class]] ? [NSThread currentThread] == (NSThread *)thread \ : dispatch_get_current_queue() == (dispatch_queue_t)thread, \ format); \ @@ -169,7 +169,7 @@ HP_EXTERN NSString *HPFormatError(NSString *message, NSArray *functionStack = threadDictionary[HPAssertFunctionStack]; - HPAssertFunction assertFunction = functionStack.lastObject; + NSArray *functionStack = threadDictionary[HippyAssertFunctionStack]; + HippyAssertFunction assertFunction = functionStack.lastObject; if (assertFunction) { return assertFunction; } - return HPCurrentAssertFunction; + return HippyCurrentAssertFunction; } -void _HPAssertFormat(const char *condition, const char *fileName, int lineNumber, const char *function, NSString *format, ...) { - HPAssertFunction assertFunction = HPGetLocalAssertFunction(); +void _HippyAssertFormat(const char *condition, const char *fileName, int lineNumber, const char *function, NSString *format, ...) { + HippyAssertFunction assertFunction = HippyGetLocalAssertFunction(); if (assertFunction) { va_list args; va_start(args, format); @@ -60,32 +69,30 @@ void _HPAssertFormat(const char *condition, const char *fileName, int lineNumber } } -void HPFatal(NSError *error, NSDictionary *__nullable userInfo) { +void HippyFatal(NSError *error) { NSString *failReason = error.localizedFailureReason; if (failReason && failReason.length >= 100) { failReason = [[failReason substringToIndex:100] stringByAppendingString:@"(...Description Too Long)"]; } NSString *fatalMessage = nil; - NSString *moduleDescription = [NSString stringWithFormat:@"Module:%@", error.userInfo[HPFatalModuleName] ?: @"unknown"]; + NSString *moduleDescription = [NSString stringWithFormat:@"Module:%@", error.userInfo[HippyFatalModuleName] ?: @"unknown"]; if (failReason) { fatalMessage = [NSString stringWithFormat:@"%@,%@[Reason]: %@", moduleDescription, error.localizedDescription, failReason]; } else { fatalMessage = [NSString stringWithFormat:@"%@,%@", moduleDescription, error.localizedDescription]; } - //void HPLogNativeInternal(HPLogLevel, const char *, int, NSDictionary *, NSString *, ...) - - HPLogNativeInternal(HPLogLevelFatal, NULL, 0, userInfo, @"%@", fatalMessage); - - HPFatalHandler fatalHandler = HPGetFatalHandler(); + + HippyLogNativeInternal(HippyLogLevelFatal, NULL, 0, @"%@", fatalMessage); + HippyFatalHandler fatalHandler = HippyGetFatalHandler(); if (fatalHandler) { - fatalHandler(error, userInfo); + fatalHandler(error); } else { -#if HP_DEBUG +#if HIPPY_DEBUG @try { - NSString *name = [NSString stringWithFormat:@"%@: %@", HPFatalExceptionName, error.localizedDescription]; - NSString *message = HPFormatError(error.localizedDescription, error.userInfo[HPJSStackTraceKey], 75); + NSString *name = [NSString stringWithFormat:@"%@: %@", HippyFatalExceptionName, error.localizedDescription]; + NSString *message = HippyFormatError(error.localizedDescription, error.userInfo[HippyJSStackTraceKey], 75); if (failReason) { - name = [NSString stringWithFormat:@"%@: %@[Reason]: %@", HPFatalExceptionName, error.localizedDescription, failReason]; + name = [NSString stringWithFormat:@"%@: %@[Reason]: %@", HippyFatalExceptionName, error.localizedDescription, failReason]; } [NSException raise:name format:@"%@", message]; } @catch (NSException *e) { @@ -94,47 +101,47 @@ void HPFatal(NSError *error, NSDictionary *__nullable userInfo) { } } -void HPHandleException(NSException *exception, NSDictionary *userInfo) { - HPLogNativeInternal(HPLogLevelFatal, NULL, 0, userInfo, @"%@", exception.description); - HPExceptionHandler exceptionHandler = HPGetExceptionHandler(); +void HippyHandleException(NSException *exception) { + HippyLogNativeInternal(HippyLogLevelFatal, NULL, 0, @"%@", exception.description); + HippyExceptionHandler exceptionHandler = HippyGetExceptionHandler(); if (exceptionHandler) { exceptionHandler(exception); } } -void HPSetAssertFunction(HPAssertFunction assertFunction) { - HPCurrentAssertFunction = assertFunction; +void HippySetAssertFunction(HippyAssertFunction assertFunction) { + HippyCurrentAssertFunction = assertFunction; } -HPAssertFunction HPGetAssertFunction(void) { - return HPCurrentAssertFunction; +HippyAssertFunction HippyGetAssertFunction(void) { + return HippyCurrentAssertFunction; } -void HPAddAssertFunction(HPAssertFunction assertFunction) { - HPAssertFunction existing = HPCurrentAssertFunction; +void HippyAddAssertFunction(HippyAssertFunction assertFunction) { + HippyAssertFunction existing = HippyCurrentAssertFunction; if (existing) { - HPCurrentAssertFunction = ^(NSString *condition, NSString *fileName, NSNumber *lineNumber, NSString *function, NSString *message) { + HippyCurrentAssertFunction = ^(NSString *condition, NSString *fileName, NSNumber *lineNumber, NSString *function, NSString *message) { existing(condition, fileName, lineNumber, function, message); assertFunction(condition, fileName, lineNumber, function, message); }; } else { - HPCurrentAssertFunction = assertFunction; + HippyCurrentAssertFunction = assertFunction; } } -void HPPerformBlockWithAssertFunction(void (^block)(void), HPAssertFunction assertFunction) { +void HippyPerformBlockWithAssertFunction(void (^block)(void), HippyAssertFunction assertFunction) { NSMutableDictionary *threadDictionary = [NSThread currentThread].threadDictionary; - NSMutableArray *functionStack = threadDictionary[HPAssertFunctionStack]; + NSMutableArray *functionStack = threadDictionary[HippyAssertFunctionStack]; if (!functionStack) { functionStack = [NSMutableArray new]; - threadDictionary[HPAssertFunctionStack] = functionStack; + threadDictionary[HippyAssertFunctionStack] = functionStack; } [functionStack addObject:assertFunction]; block(); [functionStack removeLastObject]; } -NSString *HPCurrentThreadName(void) { +NSString *HippyCurrentThreadName(void) { NSThread *thread = [NSThread currentThread]; NSString *threadName = [NSThread isMainThread] || thread.isMainThread ? @"main" : thread.name; if (threadName.length == 0) { @@ -148,23 +155,23 @@ void HPPerformBlockWithAssertFunction(void (^block)(void), HPAssertFunction asse return threadName; } -void HPSetFatalHandler(HPFatalHandler fatalhandler) { - HPCurrentFatalHandler = fatalhandler; +void HippySetFatalHandler(HippyFatalHandler fatalhandler) { + HippyCurrentFatalHandler = fatalhandler; } -HPFatalHandler HPGetFatalHandler(void) { - return HPCurrentFatalHandler; +HippyFatalHandler HippyGetFatalHandler(void) { + return HippyCurrentFatalHandler; } -void HPSetExceptionHandler(HPExceptionHandler exceptionhandler) { - HPCurrentExceptionHandler = exceptionhandler; +void HippySetExceptionHandler(HippyExceptionHandler exceptionhandler) { + HippyCurrentExceptionHandler = exceptionhandler; } -HPExceptionHandler HPGetExceptionHandler(void) { - return HPCurrentExceptionHandler; +HippyExceptionHandler HippyGetExceptionHandler(void) { + return HippyCurrentExceptionHandler; } -NSString *HPFormatError(NSString *message, NSArray *stackTrace, NSUInteger maxMessageLength) { +NSString *HippyFormatError(NSString *message, NSArray *stackTrace, NSUInteger maxMessageLength) { if (maxMessageLength > 0 && message.length > maxMessageLength) { message = [[message substringToIndex:maxMessageLength] stringByAppendingString:@"..."]; } @@ -176,7 +183,7 @@ HPExceptionHandler HPGetExceptionHandler(void) { NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(\\d+\\.js)$" options:NSRegularExpressionCaseInsensitive error:NULL]; - for (HPDriverStackFrame *frame in stackTrace) { + for (HippyJSStackFrame *frame in stackTrace) { NSString *fileName = frame.file; if (fileName && [regex numberOfMatchesInString:fileName options:0 range:NSMakeRange(0, [fileName length])]) { fileName = [fileName stringByAppendingString:@":"]; diff --git a/modules/ios/base/HPConvert.h b/modules/ios/base/HippyConvert.h similarity index 87% rename from modules/ios/base/HPConvert.h rename to modules/ios/base/HippyConvert.h index 7181889d5f5..e147cbf1f1e 100644 --- a/modules/ios/base/HPConvert.h +++ b/modules/ios/base/HippyConvert.h @@ -22,7 +22,7 @@ #import -#import "HPLog.h" +#import "HippyLog.h" /** * This class provides a collection of conversion functions for mapping @@ -30,7 +30,7 @@ * custom setter methods. */ -@interface HPConvert : NSObject +@interface HippyConvert : NSObject + (id)id:(id)json; @@ -112,21 +112,21 @@ typedef BOOL css_backface_visibility_t; @end -HP_EXTERN NSNumber *HPConvertEnumValue(const char *, NSDictionary *, NSNumber *, id); -HP_EXTERN NSNumber *HPConvertMultiEnumValue(const char *, NSDictionary *, NSNumber *, id); -HP_EXTERN NSArray *HPConvertArrayValue(SEL, id); +HIPPY_EXTERN NSNumber *HippyConvertEnumValue(const char *, NSDictionary *, NSNumber *, id); +HIPPY_EXTERN NSNumber *HippyConvertMultiEnumValue(const char *, NSDictionary *, NSNumber *, id); +HIPPY_EXTERN NSArray *HippyConvertArrayValue(SEL, id); /** * Get the converter function for the specified type */ -HP_EXTERN SEL HPConvertSelectorForType(NSString *type); +HIPPY_EXTERN SEL HippyConvertSelectorForType(NSString *type); /** * This macro is used for logging conversion errors. This is just used to * avoid repeating the same boilerplate for every error message. */ -#define HPLogConvertError(json, typeName) \ - HPLogError(@"JSON value '%@' of type %@ cannot be converted to %@", json, [json classForCoder], typeName) +#define HippyLogConvertError(json, typeName) \ + HippyLogError(@"JSON value '%@' of type %@ cannot be converted to %@", json, [json classForCoder], typeName) /** * This macro is used for creating simple converter functions that just call @@ -139,13 +139,13 @@ HP_EXTERN SEL HPConvertSelectorForType(NSString *type); */ #define HP_CUSTOM_CONVERTER(type, name, code) \ +(type)name : (id)json { \ - if (!HP_DEBUG) { \ + if (!HIPPY_DEBUG) { \ return code; \ } else { \ @try { \ return code; \ } @catch (__unused NSException * e) { \ - HPLogConvertError(json, @ #type); \ + HippyLogConvertError(json, @ #type); \ json = nil; \ return code; \ } \ @@ -158,7 +158,7 @@ HP_EXTERN SEL HPConvertSelectorForType(NSString *type); * detailed error reporting if an invalid value is passed in. */ #define HP_NUMBER_CONVERTER(type, getter) \ - HP_CUSTOM_CONVERTER(type, type, [HP_DEBUG ? [self NSNumber:json] : json getter]) + HP_CUSTOM_CONVERTER(type, type, [HIPPY_DEBUG ? [self NSNumber:json] : json getter]) /** * This macro is used for creating converters for enum types. @@ -170,7 +170,7 @@ HP_EXTERN SEL HPConvertSelectorForType(NSString *type); dispatch_once(&onceToken, ^{ \ mapping = values; \ }); \ - return (type)[HPConvertEnumValue(#type, mapping, @(default), json) getter]; \ + return (type)[HippyConvertEnumValue(#type, mapping, @(default), json) getter]; \ } /** @@ -184,7 +184,7 @@ HP_EXTERN SEL HPConvertSelectorForType(NSString *type); dispatch_once(&onceToken, ^{ \ mapping = values; \ }); \ - return [HPConvertMultiEnumValue(#type, mapping, @(default), json) getter]; \ + return [HippyConvertMultiEnumValue(#type, mapping, @(default), json) getter]; \ } /** @@ -192,5 +192,5 @@ HP_EXTERN SEL HPConvertSelectorForType(NSString *type); */ #define HP_ARRAY_CONVERTER(type) \ +(NSArray *)type##Array : (id)json { \ - return HPConvertArrayValue(@selector(type:), json); \ + return HippyConvertArrayValue(@selector(type:), json); \ } diff --git a/modules/ios/base/HPConvert.m b/modules/ios/base/HippyConvert.m similarity index 86% rename from modules/ios/base/HPConvert.m rename to modules/ios/base/HippyConvert.m index b171e3cf232..ca97cebd48f 100644 --- a/modules/ios/base/HPConvert.m +++ b/modules/ios/base/HippyConvert.m @@ -20,13 +20,13 @@ * limitations under the License. */ -#import "HPConvert.h" -#import "HPParserUtils.h" -#import "HPToolUtils.h" +#import "HippyConvert.h" +#import "HippyParserUtils.h" +#import "HippyUtils.h" #include -@implementation HPConvert +@implementation HippyConvert HP_CONVERTER(id, id, self) @@ -42,13 +42,13 @@ @implementation HPConvert * This macro is used for creating converter functions for directly * representable json values that require no conversion. */ -#if HP_DEBUG +#if HIPPY_DEBUG #define HP_JSON_CONVERTER(type) \ +(type *)type : (id)json { \ if ([json isKindOfClass:[type class]]) { \ return json; \ } else if (json) { \ - HPLogConvertError(json, @ #type); \ + HippyLogConvertError(json, @ #type); \ } \ return nil; \ } @@ -80,8 +80,8 @@ + (NSIndexSet *)NSIndexSet : (id)json { NSMutableIndexSet *indexSet = [NSMutableIndexSet new]; for (NSNumber *number in json) { NSInteger index = number.integerValue; - if (HP_DEBUG && index < 0) { - HPLogError(@"Invalid index value %ld. Indices must be positive.", (long)index); + if (HIPPY_DEBUG && index < 0) { + HippyLogError(@"Invalid index value %ld. Indices must be positive.", (long)index); } [indexSet addIndex:index]; } @@ -96,7 +96,7 @@ + (NSURL *)NSURL:(id)json { @try { // NSURL has a history of crashing with bad input, so let's be safe - NSURL *URL = HPURLWithString(path, NULL); + NSURL *URL = HippyURLWithString(path, NULL); if (URL.scheme) { // Was a well-formed absolute URL return URL; } @@ -110,7 +110,7 @@ + (NSURL *)NSURL:(id)json { CFURLRef urlRef = CFURLCreateWithBytes(NULL, (const UInt8 *)[uriData bytes], [uriData length], kCFStringEncodingUTF8, NULL); // bug:直接将CFURLRef转化为NSURL,如果包含有汉字字符,UIWebView载入之后,在shouldstartload中的request对应的URL会出现不正确的情况,不知道为什么。只能先转换为string,在转换为NSURL解决 CFStringRef stringRef = CFURLGetString(urlRef); - URL = HPURLWithString((__bridge NSString *)stringRef, NULL); + URL = HippyURLWithString((__bridge NSString *)stringRef, NULL); CFRelease(urlRef); if (URL) { return URL; @@ -127,11 +127,11 @@ + (NSURL *)NSURL:(id)json { path = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:path]; } if (!(URL = [NSURL fileURLWithPath:path])) { - HPLogConvertError(json, @"a valid URL"); + HippyLogConvertError(json, @"a valid URL"); } return URL; } @catch (__unused NSException *e) { - HPLogConvertError(json, @"a valid URL"); + HippyLogConvertError(json, @"a valid URL"); return nil; } } @@ -166,7 +166,7 @@ + (NSURLRequest *)NSURLRequest:(id)json { __block BOOL allHeadersAreStrings = YES; [headers enumerateKeysAndObjectsUsingBlock:^(__unused NSString *key, id header, BOOL *stop) { if (![header isKindOfClass:[NSString class]]) { - HPLogError(@"Values of HTTP headers passed must be of type string. " + HippyLogError(@"Values of HTTP headers passed must be of type string. " "Value of header '%@' is not a string.", key); allHeadersAreStrings = NO; @@ -186,7 +186,7 @@ + (NSURLRequest *)NSURLRequest:(id)json { return [request copy]; } if (json) { - HPLogConvertError(json, @"a valid URLRequest"); + HippyLogConvertError(json, @"a valid URLRequest"); } return nil; } @@ -205,13 +205,13 @@ + (NSDate *)NSDate:(id)json { }); NSDate *date = [formatter dateFromString:json]; if (!date) { - HPLogError(@"JSON String '%@' could not be interpreted as a date. " + HippyLogError(@"JSON String '%@' could not be interpreted as a date. " "Expected format: YYYY-MM-DD'T'HH:mm:ss.sssZ", json); } return date; } else if (json) { - HPLogConvertError(json, @"a date"); + HippyLogConvertError(json, @"a date"); } return nil; } @@ -222,7 +222,7 @@ + (NSDate *)NSDate:(id)json { // JS standard for time zones is minutes. HP_CUSTOM_CONVERTER(NSTimeZone *, NSTimeZone, [NSTimeZone timeZoneForSecondsFromGMT:[self double:json] * 60.0]) -NSNumber *HPConvertEnumValue(__unused const char *typeName, NSDictionary *mapping, NSNumber *defaultValue, id json) { +NSNumber *HippyConvertEnumValue(__unused const char *typeName, NSDictionary *mapping, NSNumber *defaultValue, id json) { if (!json) { return defaultValue; } @@ -231,33 +231,33 @@ + (NSDate *)NSDate:(id)json { if ([allValues containsObject:json] || [json isEqual:defaultValue]) { return json; } - HPLogError(@"Invalid %s '%@'. should be one of: %@", typeName, json, allValues); + HippyLogError(@"Invalid %s '%@'. should be one of: %@", typeName, json, allValues); return defaultValue; } - if (HP_DEBUG && ![json isKindOfClass:[NSString class]]) { - HPLogError(@"Expected NSNumber or NSString for %s, received %@: %@", typeName, [json classForCoder], json); + if (HIPPY_DEBUG && ![json isKindOfClass:[NSString class]]) { + HippyLogError(@"Expected NSNumber or NSString for %s, received %@: %@", typeName, [json classForCoder], json); } id value = mapping[json]; - if (HP_DEBUG && !value && [json description].length > 0) { - HPLogError(@"Invalid %s '%@'. should be one of: %@", typeName, json, + if (HIPPY_DEBUG && !value && [json description].length > 0) { + HippyLogError(@"Invalid %s '%@'. should be one of: %@", typeName, json, [[mapping allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]); } return value ?: defaultValue; } -NSNumber *HPConvertMultiEnumValue(const char *typeName, NSDictionary *mapping, NSNumber *defaultValue, id json) { +NSNumber *HippyConvertMultiEnumValue(const char *typeName, NSDictionary *mapping, NSNumber *defaultValue, id json) { if ([json isKindOfClass:[NSArray class]]) { if ([json count] == 0) { return defaultValue; } long long result = 0; for (id arrayElement in json) { - NSNumber *value = HPConvertEnumValue(typeName, mapping, defaultValue, arrayElement); + NSNumber *value = HippyConvertEnumValue(typeName, mapping, defaultValue, arrayElement); result |= value.longLongValue; } return @(result); } - return HPConvertEnumValue(typeName, mapping, defaultValue, json); + return HippyConvertEnumValue(typeName, mapping, defaultValue, json); } HP_ENUM_CONVERTER(NSLineBreakMode, (@{ @@ -388,14 +388,14 @@ + (NSDate *)NSDate:(id)json { }), UIBarStyleDefault, integerValue) -static void HPConvertCGStructValue(__unused const char *type, NSArray *fields, NSDictionary *aliases, CGFloat *result, id json) { +static void HippyConvertCGStructValue(__unused const char *type, NSArray *fields, NSDictionary *aliases, CGFloat *result, id json) { NSUInteger count = fields.count; if ([json isKindOfClass:[NSArray class]]) { - if (HP_DEBUG && [json count] != count) { - HPLogError(@"Expected array with count %lu, but count is %lu: %@", (unsigned long)count, (unsigned long)[json count], json); + if (HIPPY_DEBUG && [json count] != count) { + HippyLogError(@"Expected array with count %lu, but count is %lu: %@", (unsigned long)count, (unsigned long)[json count], json); } else { for (NSUInteger i = 0; i < count; i++) { - result[i] = [HPConvert CGFloat:json[i]]; + result[i] = [HippyConvert CGFloat:json[i]]; } } } else if ([json isKindOfClass:[NSDictionary class]]) { @@ -405,16 +405,16 @@ static void HPConvertCGStructValue(__unused const char *type, NSArray *fields, N NSString *key = aliases[alias]; NSNumber *number = json[alias]; if (number != nil) { - HPLogWarn(@"Using deprecated '%@' property for '%s'. Use '%@' instead.", alias, type, key); + HippyLogWarn(@"Using deprecated '%@' property for '%s'. Use '%@' instead.", alias, type, key); ((NSMutableDictionary *)json)[key] = number; } } } for (NSUInteger i = 0; i < count; i++) { - result[i] = [HPConvert CGFloat:json[fields[i]]]; + result[i] = [HippyConvert CGFloat:json[fields[i]]]; } } else if (json) { - HPLogConvertError(json, @(type)); + HippyLogConvertError(json, @(type)); } } @@ -430,7 +430,7 @@ +(type)type : (id)json { fields = values; \ }); \ type result; \ - HPConvertCGStructValue(#type, fields, aliases, (CGFloat *)&result, json); \ + HippyConvertCGStructValue(#type, fields, aliases, (CGFloat *)&result, json); \ return result; \ } @@ -478,7 +478,7 @@ + (UIColor *)UIColor : (id)json { CGFloat b = (argb & 0xFF) / 255.0; return [UIColor colorWithRed:r green:g blue:b alpha:a]; } else { - HPLogConvertError(json, @"a UIColor. Did you forget to call processColor() on the JS side?"); + HippyLogConvertError(json, @"a UIColor. Did you forget to call processColor() on the JS side?"); return nil; } } @@ -487,12 +487,12 @@ + (CGColorRef)CGColor:(id)json { return [self UIColor:json].CGColor; } -NSArray *HPConvertArrayValue(SEL type, id json) { +NSArray *HippyConvertArrayValue(SEL type, id json) { __block BOOL copy = NO; - __block NSArray *values = json = [HPConvert NSArray:json]; + __block NSArray *values = json = [HippyConvert NSArray:json]; if ([values isKindOfClass:[NSArray class]]) { [json enumerateObjectsUsingBlock:^(id jsonValue, NSUInteger idx, __unused BOOL *stop) { - id value = ((id(*)(Class, SEL, id))objc_msgSend)([HPConvert class], type, jsonValue); + id value = ((id(*)(Class, SEL, id))objc_msgSend)([HippyConvert class], type, jsonValue); if (copy) { if (value) { [(NSMutableArray *)values addObject:value]; @@ -515,9 +515,9 @@ + (CGColorRef)CGColor:(id)json { } } -SEL HPConvertSelectorForType(NSString *type) { +SEL HippyConvertSelectorForType(NSString *type) { const char *input = type.UTF8String; - return NSSelectorFromString([HPParseType(&input) stringByAppendingString:@":"]); + return NSSelectorFromString([HippyParseType(&input) stringByAppendingString:@":"]); } HP_ARRAY_CONVERTER(NSURL) @@ -527,7 +527,7 @@ SEL HPConvertSelectorForType(NSString *type) { * This macro is used for creating converter functions for directly * representable json array values that require no conversion. */ -#if HP_DEBUG +#if HIPPY_DEBUG #define HP_JSON_ARRAY_CONVERTER(type) HP_ARRAY_CONVERTER(type) #else #define HP_JSON_ARRAY_CONVERTER(type) \ @@ -539,7 +539,7 @@ +(NSArray *)type##Array : (id)json { \ HP_JSON_ARRAY_CONVERTER(NSArray) HP_JSON_ARRAY_CONVERTER(NSString) + (NSArray *> *)NSStringArrayArray : (id)json { - return HPConvertArrayValue(@selector(NSStringArray:), json); + return HippyConvertArrayValue(@selector(NSStringArray:), json); } HP_JSON_ARRAY_CONVERTER(NSDictionary) HP_JSON_ARRAY_CONVERTER(NSNumber) @@ -553,7 +553,7 @@ + (NSArray *)CGColorArray : (id)json { return colors; } -static id HPConvertPropertyListValue(id json) { +static id HippyConvertPropertyListValue(id json) { if (!json || json == (id)kCFNull) { return nil; } @@ -562,7 +562,7 @@ static id HPConvertPropertyListValue(id json) { __block BOOL copy = NO; NSMutableDictionary *values = [[NSMutableDictionary alloc] initWithCapacity:[json count]]; [json enumerateKeysAndObjectsUsingBlock:^(NSString *key, id jsonValue, __unused BOOL *stop) { - id value = HPConvertPropertyListValue(jsonValue); + id value = HippyConvertPropertyListValue(jsonValue); if (value) { values[key] = value; } @@ -575,7 +575,7 @@ static id HPConvertPropertyListValue(id json) { __block BOOL copy = NO; __block NSArray *values = json; [json enumerateObjectsUsingBlock:^(id jsonValue, NSUInteger idx, __unused BOOL *stop) { - id value = HPConvertPropertyListValue(jsonValue); + id value = HippyConvertPropertyListValue(jsonValue); if (copy) { if (value) { [(NSMutableArray *)values addObject:value]; @@ -600,7 +600,7 @@ static id HPConvertPropertyListValue(id json) { } + (NSPropertyList)NSPropertyList:(id)json { - return HPConvertPropertyListValue(json); + return HippyConvertPropertyListValue(json); } HP_ENUM_CONVERTER(css_backface_visibility_t, (@{ @"hidden": @NO, @"visible": @YES }), YES, boolValue) diff --git a/modules/ios/base/HippyDefines.h b/modules/ios/base/HippyDefines.h new file mode 100644 index 00000000000..9387bc726d8 --- /dev/null +++ b/modules/ios/base/HippyDefines.h @@ -0,0 +1,77 @@ +/*! + * iOS SDK + * + * Tencent is pleased to support the open source community by making + * HP available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if __OBJC__ +#import +#endif + +/** + * Make global functions usable in C++ + */ +#if defined(__cplusplus) +#define HIPPY_EXTERN extern "C" __attribute__((visibility("default"))) +#else +#define HIPPY_EXTERN extern __attribute__((visibility("default"))) +#endif + +/** + * The HIPPY_DEBUG macro can be used to exclude error checking and logging code + * from release builds to improve performance and reduce binary size. + */ +#ifndef HIPPY_DEBUG +#ifdef DEBUG +#define HIPPY_DEBUG 1 +#else +#define HIPPY_DEBUG 0 +#endif //#ifdef DEBUG +#endif //#ifndef HIPPY_DEBUG + +/** + * The HIPPY_DEV macro can be used to enable or disable development tools + * such as the debug executors, dev menu, red box, etc. + */ +#ifndef HIPPY_DEV +#ifdef DEBUG +#define HIPPY_DEV 1 +#else +#define HIPPY_DEV 0 +#endif //#ifdef DEBUG +#endif //#ifndef HIPPY_DEV + +/** + * Concat two literals. Supports macro expansions, + * e.g. HIPPY_CONCAT(foo, __FILE__). + */ +#define HIPPY_CONCAT2(A, B) A##B +#define HIPPY_CONCAT(A, B) HIPPY_CONCAT2(A, B) + + +/** + * Throw an assertion for unimplemented methods. + */ +#define HIPPY_NOT_IMPLEMENTED(method) \ +_Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wmissing-method-return-type\"") \ +_Pragma("clang diagnostic ignored \"-Wunused-parameter\"") HIPPY_EXTERN NSException *_HippyNotImplementedException(SEL, Class); \ +method NS_UNAVAILABLE { \ +@throw _HippyNotImplementedException(_cmd, [self class]); \ +} \ +_Pragma("clang diagnostic pop") diff --git a/modules/ios/base/HPI18nUtils.h b/modules/ios/base/HippyI18nUtils.h similarity index 92% rename from modules/ios/base/HPI18nUtils.h rename to modules/ios/base/HippyI18nUtils.h index d28fb96fe0a..2ef1074ae50 100644 --- a/modules/ios/base/HPI18nUtils.h +++ b/modules/ios/base/HippyI18nUtils.h @@ -25,7 +25,7 @@ NS_ASSUME_NONNULL_BEGIN -@protocol HPI18nProtocol +@protocol HippyI18nProtocol @optional @@ -37,9 +37,9 @@ NS_ASSUME_NONNULL_BEGIN /** I18n manager for render */ -@interface HPI18nUtils : NSObject +@interface HippyI18nUtils : NSObject -@property(nonatomic, weak) id delegate; +@property(nonatomic, weak) id delegate; + (instancetype)sharedInstance; diff --git a/modules/ios/base/HPI18nUtils.m b/modules/ios/base/HippyI18nUtils.m similarity index 94% rename from modules/ios/base/HPI18nUtils.m rename to modules/ios/base/HippyI18nUtils.m index 94281bc599c..04532093418 100644 --- a/modules/ios/base/HPI18nUtils.m +++ b/modules/ios/base/HippyI18nUtils.m @@ -20,13 +20,13 @@ * limitations under the License. */ -#import "HPI18nUtils.h" +#import "HippyI18nUtils.h" -@implementation HPI18nUtils +@implementation HippyI18nUtils + (instancetype)sharedInstance { static dispatch_once_t onceToken; - static HPI18nUtils *instance = nil; + static HippyI18nUtils *instance = nil; dispatch_once(&onceToken, ^{ instance = [[[self class] alloc] init]; }); diff --git a/modules/ios/base/HPInvalidating.h b/modules/ios/base/HippyInvalidating.h similarity index 83% rename from modules/ios/base/HPInvalidating.h rename to modules/ios/base/HippyInvalidating.h index 4a539098461..19432ba622d 100644 --- a/modules/ios/base/HPInvalidating.h +++ b/modules/ios/base/HippyInvalidating.h @@ -22,12 +22,12 @@ #import -typedef NS_ENUM(NSUInteger, HPInvalidateReason) { - HPInvalidateReasonDealloc = 0, - HPInvalidateReasonReload +typedef NS_ENUM(NSUInteger, HippyInvalidateReason) { + HippyInvalidateReasonDealloc = 0, + HippyInvalidateReasonReload }; -@protocol HPInvalidating +@protocol HippyInvalidating - (void)invalidate; diff --git a/modules/ios/base/HPDriverStackFrame.h b/modules/ios/base/HippyJSStackFrame.h similarity index 85% rename from modules/ios/base/HPDriverStackFrame.h rename to modules/ios/base/HippyJSStackFrame.h index 1310d3f85a9..059163db028 100644 --- a/modules/ios/base/HPDriverStackFrame.h +++ b/modules/ios/base/HippyJSStackFrame.h @@ -22,7 +22,7 @@ #import -@interface HPDriverStackFrame : NSObject +@interface HippyJSStackFrame : NSObject @property (nonatomic, copy, readonly) NSString *methodName; @property (nonatomic, copy, readonly) NSString *file; @@ -34,7 +34,7 @@ + (instancetype)stackFrameWithDictionary:(NSDictionary *)dict; - (NSDictionary *)toDictionary; -+ (NSArray *)stackFramesWithLines:(NSString *)lines; -+ (NSArray *)stackFramesWithDictionaries:(NSArray *)dicts; ++ (NSArray *)stackFramesWithLines:(NSString *)lines; ++ (NSArray *)stackFramesWithDictionaries:(NSArray *)dicts; @end diff --git a/modules/ios/base/HPDriverStackFrame.m b/modules/ios/base/HippyJSStackFrame.m similarity index 77% rename from modules/ios/base/HPDriverStackFrame.m rename to modules/ios/base/HippyJSStackFrame.m index 2b9dbd13962..c67cb79dd89 100644 --- a/modules/ios/base/HPDriverStackFrame.m +++ b/modules/ios/base/HippyJSStackFrame.m @@ -20,24 +20,24 @@ * limitations under the License. */ -#import "HPDriverStackFrame.h" -#import "HPLog.h" -#import "HPToolUtils.h" +#import "HippyJSStackFrame.h" +#import "HippyLog.h" +#import "HippyUtils.h" -static NSRegularExpression *HPJSStackFrameRegex() { +static NSRegularExpression *HippyJSStackFrameRegex(void) { static dispatch_once_t onceToken; static NSRegularExpression *_regex; dispatch_once(&onceToken, ^{ NSError *regexError; _regex = [NSRegularExpression regularExpressionWithPattern:@"^([^@]+)@(.*):(\\d+):(\\d+)$" options:0 error:®exError]; if (regexError) { - HPLogError(@"Failed to build regex: %@", [regexError localizedDescription]); + HippyLogError(@"Failed to build regex: %@", [regexError localizedDescription]); } }); return _regex; } -@implementation HPDriverStackFrame +@implementation HippyJSStackFrame - (instancetype)initWithMethodName:(NSString *)methodName file:(NSString *)file lineNumber:(NSInteger)lineNumber column:(NSInteger)column { if (self = [super init]) { @@ -51,15 +51,15 @@ - (instancetype)initWithMethodName:(NSString *)methodName file:(NSString *)file - (NSDictionary *)toDictionary { return @{ - @"methodName": HPNullIfNil(self.methodName), - @"file": HPNullIfNil(self.file), + @"methodName": HippyNullIfNil(self.methodName), + @"file": HippyNullIfNil(self.file), @"lineNumber": @(self.lineNumber), @"column": @(self.column) }; } + (instancetype)stackFrameWithLine:(NSString *)line { - NSTextCheckingResult *match = [HPJSStackFrameRegex() firstMatchInString:line options:0 range:NSMakeRange(0, line.length)]; + NSTextCheckingResult *match = [HippyJSStackFrameRegex() firstMatchInString:line options:0 range:NSMakeRange(0, line.length)]; if (!match) { return nil; } @@ -77,10 +77,10 @@ + (instancetype)stackFrameWithDictionary:(NSDictionary *)dict { column:[dict[@"column"] integerValue]]; } -+ (NSArray *)stackFramesWithLines:(NSString *)lines { ++ (NSArray *)stackFramesWithLines:(NSString *)lines { NSMutableArray *stack = [NSMutableArray new]; for (NSString *line in [lines componentsSeparatedByString:@"\n"]) { - HPDriverStackFrame *frame = [self stackFrameWithLine:line]; + HippyJSStackFrame *frame = [self stackFrameWithLine:line]; if (frame) { [stack addObject:frame]; } @@ -88,10 +88,10 @@ + (instancetype)stackFrameWithDictionary:(NSDictionary *)dict { return stack; } -+ (NSArray *)stackFramesWithDictionaries:(NSArray *)dicts { ++ (NSArray *)stackFramesWithDictionaries:(NSArray *)dicts { NSMutableArray *stack = [NSMutableArray new]; for (NSDictionary *dict in dicts) { - HPDriverStackFrame *frame = [self stackFrameWithDictionary:dict]; + HippyJSStackFrame *frame = [self stackFrameWithDictionary:dict]; if (frame) { [stack addObject:frame]; } diff --git a/modules/ios/base/HPLog.h b/modules/ios/base/HippyLog.h similarity index 53% rename from modules/ios/base/HPLog.h rename to modules/ios/base/HippyLog.h index a51540087f3..066421f5a86 100644 --- a/modules/ios/base/HPLog.h +++ b/modules/ios/base/HippyLog.h @@ -22,117 +22,117 @@ # if defined(__OBJC__) #import +#import "HippyDefines.h" -#import "MacroDefines.h" - -#ifndef HP_LOG_ENABLED +#ifndef HIPPY_LOG_ENABLED #ifdef DEBUG -#define HP_LOG_ENABLED 1 +#define HIPPY_LOG_ENABLED 1 #else -#define HP_LOG_ENABLED 0 +#define HIPPY_LOG_ENABLED 0 #endif //#ifdef DEBUG -#endif //#ifndef HP_LOG_ENABLED +#endif //#ifndef HIPPY_LOG_ENABLED /** * Thresholds for logs to display a redbox. You can override these values when debugging * in order to tweak the default logging behavior. */ -#ifndef HPLOG_REDBOX_LEVEL -#define HPLOG_REDBOX_LEVEL HPLogLevelError +#ifndef HIPPYLOG_REDBOX_LEVEL +#define HIPPYLOG_REDBOX_LEVEL HippyLogLevelError #endif /** * Logging macros. Use these to log information, warnings and errors in your * own code. */ -#define HPLog(...) _HPLog(HPLogLevelInfo, __VA_ARGS__) -#define HPLogTrace(...) _HPLog(HPLogLevelTrace, __VA_ARGS__) -#define HPLogInfo(...) _HPLog(HPLogLevelInfo, __VA_ARGS__) -#define HPLogWarn(...) _HPLog(HPLogLevelWarning, __VA_ARGS__) -#define HPLogError(...) _HPLog(HPLogLevelError, __VA_ARGS__) -#define HPLogFatal(...) _HPLog(HPLogLevelFatal, __VA_ARGS__) +#define HippyLog(...) _HippyLog(HippyLogLevelInfo, __VA_ARGS__) +#define HippyLogTrace(...) _HippyLog(HippyLogLevelTrace, __VA_ARGS__) +#define HippyLogInfo(...) _HippyLog(HippyLogLevelInfo, __VA_ARGS__) +#define HippyLogWarn(...) _HippyLog(HippyLogLevelWarning, __VA_ARGS__) +#define HippyLogError(...) _HippyLog(HippyLogLevelError, __VA_ARGS__) +#define HippyLogFatal(...) _HippyLog(HippyLogLevelFatal, __VA_ARGS__) /** * An enum representing the severity of the log message. */ -typedef NS_ENUM(NSInteger, HPLogLevel) { - HPLogLevelTrace = 0, - HPLogLevelInfo = 1, - HPLogLevelWarning = 2, - HPLogLevelError = 3, - HPLogLevelFatal = 4 +typedef NS_ENUM(NSInteger, HippyLogLevel) { + HippyLogLevelTrace = 0, + HippyLogLevelInfo = 1, + HippyLogLevelWarning = 2, + HippyLogLevelError = 3, + HippyLogLevelFatal = 4 }; +/** + * An enum representing the source of a log message. + */ +typedef NS_ENUM(NSInteger, HippyLogSource) { HippyLogSourceNative = 1, HippyLogSourceJavaScript = 2 }; + /** * A block signature to be used for custom logging functions. In most cases you - * will want to pass these arguments to the HPFormatLog function in order to + * will want to pass these arguments to the HippyFormatLog function in order to * generate a string. */ -typedef void (^HPLogFunction)(HPLogLevel level, NSString *fileName, - NSNumber *lineNumber, NSString *message, - NSArray *, NSDictionary *userInfo); - -typedef void (^HPLogShowFunction)(NSString *message, NSArray *stacks); +typedef void (^HippyLogFunction)(HippyLogLevel level, HippyLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message); /** * A method to generate a string from a collection of log data. To omit any * particular data from the log, just pass nil or zero for the argument. */ -HP_EXTERN NSString *HPFormatLog(NSDate *timestamp, HPLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message); +HIPPY_EXTERN NSString *HippyFormatLog(NSDate *timestamp, HippyLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message); /** - * The default logging function used by HPLogXX. + * The default logging function used by HippyLogXX. */ -extern HPLogFunction HPDefaultLogFunction; +extern HippyLogFunction HippyDefaultLogFunction; /** * These methods get and set the global logging threshold. This is the level - * below which logs will be ignored. Default is HPLogLevelInfo for debug and - * HPLogLevelError for production. + * below which logs will be ignored. Default is HippyLogLevelInfo for debug and + * HippyLogLevelError for production. */ -HP_EXTERN void HPSetLogThreshold(HPLogLevel threshold); -HP_EXTERN HPLogLevel HPGetLogThreshold(void); +HIPPY_EXTERN void HippySetLogThreshold(HippyLogLevel threshold); +HIPPY_EXTERN HippyLogLevel HippyGetLogThreshold(void); /** - * These methods get and set the global logging function called by the HPLogXX + * These methods get and set the global logging function called by the HippyLogXX * macros. You can use these to replace the standard behavior with custom log * functionality. */ -HP_EXTERN void HPSetLogFunction(HPLogFunction logFunction); -HP_EXTERN HPLogFunction HPGetLogFunction(void); +HIPPY_EXTERN void HippySetLogFunction(HippyLogFunction logFunction); +HIPPY_EXTERN HippyLogFunction HippyGetLogFunction(void); /** * This appends additional code to the existing log function, without replacing * the existing functionality. Useful if you just want to forward logs to an * extra service without changing the default behavior. */ -HP_EXTERN void HPAddLogFunction(HPLogFunction logFunction); +HIPPY_EXTERN void HippyAddLogFunction(HippyLogFunction logFunction); /** * This method temporarily overrides the log function while performing the * specified block. This is useful for testing purposes (to detect if a given * function logs something) or to suppress or override logging temporarily. */ -HP_EXTERN void HPPerformBlockWithLogFunction(void (^block)(void), HPLogFunction logFunction); +HIPPY_EXTERN void HippyPerformBlockWithLogFunction(void (^block)(void), HippyLogFunction logFunction); /** * This method adds a conditional prefix to any messages logged within the scope * of the passed block. This is useful for adding additional context to log * messages. The block will be performed synchronously on the current thread. */ -HP_EXTERN void HPPerformBlockWithLogPrefix(void (^block)(void), NSString *prefix); +HIPPY_EXTERN void HippyPerformBlockWithLogPrefix(void (^block)(void), NSString *prefix); /** * Private logging function - ignore this. */ -#if HP_LOG_ENABLED -#define _HPLog(lvl, ...) HPLogNativeInternal(lvl, __FILE__, __LINE__, nil, __VA_ARGS__); +#if HIPPY_LOG_ENABLED +#define _HippyLog(lvl, ...) HippyLogNativeInternal(lvl, __FILE__, __LINE__, __VA_ARGS__); #else -#define _HPLog(lvl, ...) \ +#define _HippyLog(lvl, ...) \ do { \ } while (0) #endif -HP_EXTERN void HPLogNativeInternal(HPLogLevel, const char *, int, NSDictionary *, NSString *, ...) NS_FORMAT_FUNCTION(5, 6); +HIPPY_EXTERN void HippyLogNativeInternal(HippyLogLevel, const char *, int, NSString *, ...) NS_FORMAT_FUNCTION(4, 5); #endif // defined(__OBJC__) diff --git a/modules/ios/base/HPLog.mm b/modules/ios/base/HippyLog.mm similarity index 59% rename from modules/ios/base/HPLog.mm rename to modules/ios/base/HippyLog.mm index 09c57215706..c2881036d49 100644 --- a/modules/ios/base/HPLog.mm +++ b/modules/ios/base/HippyLog.mm @@ -20,17 +20,15 @@ * limitations under the License. */ -#import "HPLog.h" +#import "HippyLog.h" #import "HippyBridge.h" #import "HippyRedBox.h" -#include -#include #pragma mark NativeLog Methods -static NSString *const HPLogFunctionStack = @"HPLogFunctionStack"; +static NSString *const HippyLogFunctionStack = @"HippyLogFunctionStack"; -const char *HPLogLevels[] = { +const char *HippyLogLevels[] = { "trace", "info", "warn", @@ -38,74 +36,73 @@ "fatal", }; -#if HP_DEBUG -HPLogLevel HPDefaultLogThreshold = HPLogLevelTrace; +#if HIPPY_DEBUG +HippyLogLevel HPDefaultLogThreshold = HippyLogLevelTrace; #else -HPLogLevel HPDefaultLogThreshold = HPLogLevelError; +HippyLogLevel HPDefaultLogThreshold = HippyLogLevelError; #endif -static HPLogFunction HPCurrentLogFunction; -static HPLogLevel HPCurrentLogThreshold = HPDefaultLogThreshold; -static HPLogShowFunction HPLogShowFunc; +static HippyLogFunction HPCurrentLogFunction; +static HippyLogLevel HPCurrentLogThreshold = HPDefaultLogThreshold; -HPLogLevel HPGetLogThreshold() { +HippyLogLevel HippyGetLogThreshold() { return HPCurrentLogThreshold; } -void HPSetLogThreshold(HPLogLevel threshold) { +void HippySetLogThreshold(HippyLogLevel threshold) { HPCurrentLogThreshold = threshold; } -HPLogFunction HPDefaultLogFunction - = ^(HPLogLevel level, NSString *fileName, NSNumber *lineNumber, - NSString *message, NSArray *stack, NSDictionary *userInfo) { - NSString *log = HPFormatLog([NSDate date], level, fileName, lineNumber, message); - fprintf(stderr, "%s\n", log.UTF8String); - fflush(stderr); - }; +HippyLogFunction HippyDefaultLogFunction = ^(HippyLogLevel level, __unused HippyLogSource source, + NSString *fileName, NSNumber *lineNumber, NSString *message) { + NSString *log = HippyFormatLog([NSDate date], level, fileName, lineNumber, message); + fprintf(stderr, "%s\n", log.UTF8String); + fflush(stderr); +}; -void HPSetLogFunction(HPLogFunction logFunction) { +void HippySetLogFunction(HippyLogFunction logFunction) { HPCurrentLogFunction = logFunction; } -HPLogFunction HPGetLogFunction() { +HippyLogFunction HippyGetLogFunction() { if (!HPCurrentLogFunction) { - HPCurrentLogFunction = HPDefaultLogFunction; + HPCurrentLogFunction = HippyDefaultLogFunction; } return HPCurrentLogFunction; } -void HPAddLogFunction(HPLogFunction logFunction) { - HPLogFunction existing = HPGetLogFunction(); +void HippyAddLogFunction(HippyLogFunction logFunction) { + HippyLogFunction existing = HippyGetLogFunction(); if (existing) { - HPSetLogFunction(^(HPLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message, NSArray *stack, NSDictionary *userInfo) { - existing(level, fileName, lineNumber, message, stack, userInfo); - logFunction(level, fileName, lineNumber, message, stack, userInfo); + HippySetLogFunction(^(HippyLogLevel level, HippyLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { + existing(level, source, fileName, lineNumber, message); + logFunction(level, source, fileName, lineNumber, message); }); } else { - HPSetLogFunction(logFunction); + HippySetLogFunction(logFunction); } } -void HPPerformBlockWithLogFunction(void (^block)(void), HPLogFunction logFunction) { +void HippyPerformBlockWithLogFunction(void (^block)(void), HippyLogFunction logFunction) { NSMutableDictionary *threadDictionary = [NSThread currentThread].threadDictionary; - NSMutableArray *functionStack = threadDictionary[HPLogFunctionStack]; + NSMutableArray *functionStack = threadDictionary[HippyLogFunctionStack]; if (!functionStack) { functionStack = [NSMutableArray new]; - threadDictionary[HPLogFunctionStack] = functionStack; + threadDictionary[HippyLogFunctionStack] = functionStack; } [functionStack addObject:logFunction]; block(); [functionStack removeLastObject]; } -void HPPerformBlockWithLogPrefix(void (^block)(void), NSString *prefix) { - HPLogFunction logFunction = HPGetLogFunction(); +void HippyPerformBlockWithLogPrefix(void (^block)(void), NSString *prefix) { + HippyLogFunction logFunction = HippyGetLogFunction(); if (logFunction) { - HPPerformBlockWithLogFunction( - block, ^(HPLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message, NSArray *stack, NSDictionary *userInfo) { - logFunction(level, fileName, lineNumber, [prefix stringByAppendingString:message], stack, userInfo); - }); + HippyPerformBlockWithLogFunction(block, + ^(HippyLogLevel level, HippyLogSource source, + NSString *fileName, NSNumber *lineNumber, NSString *message) { + logFunction(level, source, fileName, lineNumber, [prefix stringByAppendingString:message]); + }); } } @@ -123,7 +120,7 @@ void HPPerformBlockWithLogPrefix(void (^block)(void), NSString *prefix) { return threadName; } -NSString *HPFormatLog(NSDate *timestamp, HPLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message) { +NSString *HippyFormatLog(NSDate *timestamp, HippyLogLevel level, NSString *fileName, NSNumber *lineNumber, NSString *message) { NSMutableString *log = [NSMutableString new]; if (timestamp) { static NSDateFormatter *formatter; @@ -135,7 +132,7 @@ void HPPerformBlockWithLogPrefix(void (^block)(void), NSString *prefix) { [log appendString:[formatter stringFromDate:timestamp]]; } if (level) { - [log appendFormat:@"[%s]", HPLogLevels[level]]; + [log appendFormat:@"[%s]", HippyLogLevels[level]]; } [log appendFormat:@"[tid:%@]", currentThreadName()]; @@ -155,18 +152,23 @@ void HPPerformBlockWithLogPrefix(void (^block)(void), NSString *prefix) { return log; } -void HPLogNativeInternal(HPLogLevel level, const char *fileName, int lineNumber, NSDictionary *userInfo, NSString *format, ...) { - HPLogFunction logFunction = HPGetLogFunction(); - BOOL log = HP_DEBUG || (logFunction != nil); - if (log && level >= HPGetLogThreshold()) { +void HippyLogNativeInternal(HippyLogLevel level, const char *fileName, int lineNumber, NSString *format, ...) { + HippyLogFunction logFunction = HippyGetLogFunction(); + BOOL log = HIPPY_DEBUG || (logFunction != nil); + if (log && level >= HippyGetLogThreshold()) { // Get message va_list args; va_start(args, format); NSString *message = [[NSString alloc] initWithFormat:format arguments:args]; va_end(args); - NSArray *callStacks = nil; -#if HP_DEBUG - if (level >= HPLOG_REDBOX_LEVEL) { + + // Call log function + if (logFunction) { + logFunction(level, HippyLogSourceNative, fileName ? @(fileName) : nil, lineNumber > 0 ? @(lineNumber) : nil, message); + } + +#if HIPPY_DEBUG + if (level >= HIPPYLOG_REDBOX_LEVEL) { NSArray *stackSymbols = [NSThread callStackSymbols]; NSMutableArray *stack = [NSMutableArray arrayWithCapacity:(stackSymbols.count - 1)]; [stackSymbols enumerateObjectsUsingBlock:^(NSString *frameSymbols, NSUInteger idx, __unused BOOL *stop) { @@ -182,18 +184,12 @@ void HPLogNativeInternal(HPLogLevel level, const char *fileName, int lineNumber, } } }]; - callStacks = [stack copy]; - dispatch_async(dispatch_get_main_queue(), ^{ // red box is thread safe, but by deferring to main queue we avoid a startup // race condition that causes the module to be accessed before it has loaded - [[HippyBridge currentBridge].redBox showErrorMessage:message withStack:stack]; + [((HippyBridge *)[HippyBridge currentBridge]).redBox showErrorMessage:message withStack:stack]; }); } #endif - // Call log function - if (logFunction) { - logFunction(level, fileName ? @(fileName) : nil, lineNumber > 0 ? @(lineNumber) : nil, message, callStacks, userInfo); - } } } diff --git a/modules/ios/base/HPParserUtils.h b/modules/ios/base/HippyParserUtils.h similarity index 59% rename from modules/ios/base/HPParserUtils.h rename to modules/ios/base/HippyParserUtils.h index e9d494ab3de..ae01b7c7e0d 100644 --- a/modules/ios/base/HPParserUtils.h +++ b/modules/ios/base/HippyParserUtils.h @@ -21,19 +21,19 @@ */ #import -#import "MacroDefines.h" +#import "HippyDefines.h" /** * Generic utility functions for parsing Objective-C source code. */ -HP_EXTERN BOOL HPParseReadChar(const char **input, char c); -HP_EXTERN BOOL HPParseReadString(const char **input, const char *string); -HP_EXTERN void HPParseSkipWhitespace(const char **input); -HP_EXTERN BOOL HPParseIdentifier(const char **input, NSString **string); +HIPPY_EXTERN BOOL HippyReadChar(const char **input, char c); +HIPPY_EXTERN BOOL HippyReadString(const char **input, const char *string); +HIPPY_EXTERN void HippySkipWhitespace(const char **input); +HIPPY_EXTERN BOOL HippyParseIdentifier(const char **input, NSString **string); /** - * Parse an Objective-C type into a form that can be used by HPConvert. - * This doesn't really belong here, but it's used by both HPConvert and - * which makes it difficult to find a better home for it. + * Parse an Objective-C type into a form that can be used by HippyConvert. + * This doesn't really belong here, but it's used by both HippyConvert and + * HippyModuleMethod, which makes it difficult to find a better home for it. */ -HP_EXTERN NSString *HPParseType(const char **input); +HIPPY_EXTERN NSString *HippyParseType(const char **input); diff --git a/modules/ios/base/HPParserUtils.m b/modules/ios/base/HippyParserUtils.m similarity index 63% rename from modules/ios/base/HPParserUtils.m rename to modules/ios/base/HippyParserUtils.m index 92ffc98023f..77b2f8ef71c 100644 --- a/modules/ios/base/HPParserUtils.m +++ b/modules/ios/base/HippyParserUtils.m @@ -20,10 +20,10 @@ * limitations under the License. */ -#import "HPParserUtils.h" -#import "HPLog.h" +#import "HippyParserUtils.h" +#import "HippyLog.h" -BOOL HPParseReadChar(const char **input, char c) { +BOOL HippyReadChar(const char **input, char c) { if (**input == c) { (*input)++; return YES; @@ -31,7 +31,7 @@ BOOL HPParseReadChar(const char **input, char c) { return NO; } -BOOL HPParseReadString(const char **input, const char *string) { +BOOL HippyReadString(const char **input, const char *string) { int i; for (i = 0; string[i] != 0; i++) { if (string[i] != (*input)[i]) { @@ -42,27 +42,27 @@ BOOL HPParseReadString(const char **input, const char *string) { return YES; } -void HPParseSkipWhitespace(const char **input) { +void HippySkipWhitespace(const char **input) { while (isspace(**input)) { (*input)++; } } -static BOOL HPParseIsIdentifierHead(const char c) { +static BOOL HippyParseIsIdentifierHead(const char c) { return isalpha(c) || c == '_'; } -static BOOL HPParseIsIdentifierTail(const char c) { +static BOOL HippyParseIsIdentifierTail(const char c) { return isalnum(c) || c == '_'; } -BOOL HPParseIdentifier(const char **input, NSString **string) { +BOOL HippyParseIdentifier(const char **input, NSString **string) { const char *start = *input; - if (!HPParseIsIdentifierHead(**input)) { + if (!HippyParseIsIdentifierHead(**input)) { return NO; } (*input)++; - while (HPParseIsIdentifierTail(**input)) { + while (HippyParseIsIdentifierTail(**input)) { (*input)++; } if (string) { @@ -71,7 +71,7 @@ BOOL HPParseIdentifier(const char **input, NSString **string) { return YES; } -static BOOL HPParseIsCollectionType(NSString *type) { +static BOOL HippyParseIsCollectionType(NSString *type) { static NSSet *collectionTypes; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -80,24 +80,24 @@ static BOOL HPParseIsCollectionType(NSString *type) { return [collectionTypes containsObject:type]; } -NSString *HPParseType(const char **input) { +NSString *HippyParseType(const char **input) { NSString *type; - HPParseIdentifier(input, &type); - HPParseSkipWhitespace(input); - if (HPParseReadChar(input, '<')) { - HPParseSkipWhitespace(input); - NSString *subtype = HPParseType(input); - if (HPParseIsCollectionType(type)) { + HippyParseIdentifier(input, &type); + HippySkipWhitespace(input); + if (HippyReadChar(input, '<')) { + HippySkipWhitespace(input); + NSString *subtype = HippyParseType(input); + if (HippyParseIsCollectionType(type)) { if ([type isEqualToString:@"NSDictionary"]) { // Dictionaries have both a key *and* value type, but the key type has // to be a string for JSON, so we only care about the value type - if (HP_DEBUG && ![subtype isEqualToString:@"NSString"]) { - HPLogError(@"%@ is not a valid key type for a JSON dictionary", subtype); + if (HIPPY_DEBUG && ![subtype isEqualToString:@"NSString"]) { + HippyLogError(@"%@ is not a valid key type for a JSON dictionary", subtype); } - HPParseSkipWhitespace(input); - HPParseReadChar(input, ','); - HPParseSkipWhitespace(input); - subtype = HPParseType(input); + HippySkipWhitespace(input); + HippyReadChar(input, ','); + HippySkipWhitespace(input); + subtype = HippyParseType(input); } if (![subtype isEqualToString:@"id"]) { type = [type stringByReplacingCharactersInRange:(NSRange) { 0, 2 /* "NS" */ } withString:subtype]; @@ -105,10 +105,10 @@ static BOOL HPParseIsCollectionType(NSString *type) { } else { // It's a protocol rather than a generic collection - ignore it } - HPParseSkipWhitespace(input); - HPParseReadChar(input, '>'); + HippySkipWhitespace(input); + HippyReadChar(input, '>'); } - HPParseSkipWhitespace(input); - HPParseReadChar(input, '*'); + HippySkipWhitespace(input); + HippyReadChar(input, '*'); return type; } diff --git a/modules/ios/base/HippyUtils.h b/modules/ios/base/HippyUtils.h new file mode 100644 index 00000000000..a1038c20b46 --- /dev/null +++ b/modules/ios/base/HippyUtils.h @@ -0,0 +1,145 @@ +/*! + * iOS SDK + * + * Tencent is pleased to support the open source community by making + * Hippy available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import +#import +#import "HippyDefines.h" + +NS_ASSUME_NONNULL_BEGIN + + +// Check is we are currently on the main queue (not to be confused with +// the main thread, which is not neccesarily the same thing) +// https://twitter.com/olebegemann/status/738656134731599872 +HIPPY_EXTERN BOOL HippyIsMainQueue(void); + +// Execute the specified block on the main queue. Unlike dispatch_async() +// this will execute immediately if we're already on the main queue. +HIPPY_EXTERN void HippyExecuteOnMainQueue(dispatch_block_t block); + +// Deprecated - do not use. +HIPPY_EXTERN void HippyExecuteOnMainThread(dispatch_block_t block, BOOL sync); + +// Method swizzling +HIPPY_EXTERN void HippySwapClassMethods(Class cls, SEL original, SEL replacement); +HIPPY_EXTERN void HippySwapInstanceMethods(Class cls, SEL original, SEL replacement); + +// Module subclass support +HIPPY_EXTERN BOOL HippyClassOverridesClassMethod(Class cls, SEL selector); +HIPPY_EXTERN BOOL HippyClassOverridesInstanceMethod(Class cls, SEL selector); + +// Returns YES if HP is running in a test environment +HIPPY_EXTERN BOOL HippyRunningInTestEnvironment(void); + +// Returns YES if HP is running in an iOS App Extension +HIPPY_EXTERN BOOL HippyRunningInAppExtension(void); + +// Returns the shared UIApplication instance, or nil if running in an App Extension +HIPPY_EXTERN UIApplication *__nullable HippySharedApplication(void); + +// Returns the current main window, useful if you need to access the root view +// or view controller +HIPPY_EXTERN UIWindow *__nullable HippyKeyWindow(void); + +// Returns the presented view controller, useful if you need +// e.g. to present a modal view controller or alert over it +HIPPY_EXTERN UIViewController *__nullable HippyPresentedViewController(void); + +// Does this device support force touch (aka 3D Touch)? +HIPPY_EXTERN BOOL HippyForceTouchAvailable(void); + + +#pragma mark - + +// JSON serialization/deserialization +HIPPY_EXTERN NSString *__nullable HippyJSONStringify(id __nullable jsonObject, NSError **error); +HIPPY_EXTERN id __nullable HippyJSONParse(NSString *__nullable jsonString, NSError **error); +HIPPY_EXTERN id __nullable HippyJSONParseMutable(NSString *__nullable jsonString, NSError **error); + +// Sanitize a JSON object by stripping invalid types and/or NaN values +HIPPY_EXTERN id HippyJSONClean(id object); + +// Get MD5 hash of a string +HIPPY_EXTERN NSString *HippyMD5Hash(NSString *string); + + +#pragma mark - + +// Create an NSError in the HippyErrorDomain +HIPPY_EXTERN NSError *HippyErrorWithMessage(NSString *message); + +// Create an NSError in the HippyErrorDomain +HIPPY_EXTERN NSError *HippyErrorWithMessageAndModuleName(NSString *message, NSString *__nullable moduleName); + +// Create an NSError with HippyFatalModuleName from another error +HIPPY_EXTERN NSError *HippyErrorFromErrorAndModuleName(NSError *error, NSString *__nullable moduleName); + +// Creates a standardized error object to return in callbacks +HIPPY_EXTERN NSDictionary *HippyMakeError(NSString *message, id __nullable toStringify, + NSDictionary *__nullable extraData); + +HIPPY_EXTERN NSDictionary *HippyMakeAndLogError(NSString *message, id __nullable toStringify, + NSDictionary *__nullable extraData); + +HIPPY_EXTERN NSDictionary *HippyJSErrorFromNSError(NSError *error); + +HIPPY_EXTERN NSDictionary *HippyJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error); + +// The default error code to use as the `code` property for callback error objects +HIPPY_EXTERN NSString *const HippyErrorUnspecified; + + +#pragma mark - + +// Convert nil values to NSNull, and vice-versa +#define HippyNullIfNil(value) (value ?: (id)kCFNull) +#define HippyNilIfNull(value) (value == (id)kCFNull ? nil : value) + +// Convert NaN or infinite values to zero, as these aren't JSON-safe +HIPPY_EXTERN double HippyZeroIfNaN(double value); + +// Converts a CGColor to a hex string +HIPPY_EXTERN NSString *HippyColorToHexString(CGColorRef color); + +/** + * convert string to UIColor + * colorString could be 'fff','#fff','ffffff','#ffffff','ffffffff','#ffffffff' + * or 'red', 'green','blue'.etc + */ +HIPPY_EXTERN UIColor *HippyConvertStringToColor(NSString *colorString); + +HIPPY_EXTERN UIColor *HippyConvertNumberToColor(NSInteger colorNumber); + +// Get standard localized string (if it exists) +HIPPY_EXTERN NSString *HippyUIKitLocalizedString(NSString *string); + +// URL manipulation +HIPPY_EXTERN NSString *__nullable HippyGetURLQueryParam(NSURL *__nullable URL, NSString *param); +HIPPY_EXTERN NSURL *__nullable HippyURLByReplacingQueryParam(NSURL *__nullable URL, NSString *param, NSString *__nullable value); +HIPPY_EXTERN NSURL *__nullable HippyURLWithString(NSString *__nonnull URLString, NSString *__nullable baseURLString); +HIPPY_EXTERN NSString *HippySchemeFromURLString(NSString *urlString); + +//Get String Encoding From HTTP URL Response +HIPPY_EXTERN NSStringEncoding HippyGetStringEncodingFromURLResponse(NSURLResponse *response); + +NS_ASSUME_NONNULL_END diff --git a/modules/ios/base/HPToolUtils.m b/modules/ios/base/HippyUtils.m similarity index 58% rename from modules/ios/base/HPToolUtils.m rename to modules/ios/base/HippyUtils.m index 803ab79bcff..aa987ed49ad 100644 --- a/modules/ios/base/HPToolUtils.m +++ b/modules/ios/base/HippyUtils.m @@ -20,15 +20,15 @@ * limitations under the License. */ -#import "HPAsserts.h" -#import "HPLog.h" -#import "HPToolUtils.h" - -#include +#import "HippyUtils.h" +#import "HippyAsserts.h" +#import "HippyLog.h" +#import +#import static NSString *colorDictionaryJSON = @"transparent:0x00000000,aliceblue:0xf0f8ffff,antiquewhite:0xfaebd7ff,aqua:0x00ffffff,aquamarine:0x7fffd4ff,azure:0xf0ffffff,beige:0xf5f5dcff,bisque:0xffe4c4ff,black:0x000000ff,blanchedalmond:0xffebcdff,blue:0x0000ffff,blueviolet:0x8a2be2ff,brown:0xa52a2aff,burlywood:0xdeb887ff,burntsienna:0xea7e5dff,cadetblue:0x5f9ea0ff,chartreuse:0x7fff00ff,chocolate:0xd2691eff,coral:0xff7f50ff,cornflowerblue:0x6495edff,cornsilk:0xfff8dcff,crimson:0xdc143cff,cyan:0x00ffffff,darkblue:0x00008bff,darkcyan:0x008b8bff,darkgoldenrod:0xb8860bff,darkgray:0xa9a9a9ff,darkgreen:0x006400ff,darkgrey:0xa9a9a9ff,darkkhaki:0xbdb76bff,darkmagenta:0x8b008bff,darkolivegreen:0x556b2fff,darkorange:0xff8c00ff,darkorchid:0x9932ccff,darkred:0x8b0000ff,darksalmon:0xe9967aff,darkseagreen:0x8fbc8fff,darkslateblue:0x483d8bff,darkslategray:0x2f4f4fff,darkslategrey:0x2f4f4fff,darkturquoise:0x00ced1ff,darkviolet:0x9400d3ff,deeppink:0xff1493ff,deepskyblue:0x00bfffff,dimgray:0x696969ff,dimgrey:0x696969ff,dodgerblue:0x1e90ffff,firebrick:0xb22222ff,floralwhite:0xfffaf0ff,forestgreen:0x228b22ff,fuchsia:0xff00ffff,gainsboro:0xdcdcdcff,ghostwhite:0xf8f8ffff,gold:0xffd700ff,goldenrod:0xdaa520ff,gray:0x808080ff,green:0x008000ff,greenyellow:0xadff2fff,grey:0x808080ff,honeydew:0xf0fff0ff,hotpink:0xff69b4ff,indianred:0xcd5c5cff,indigo:0x4b0082ff,ivory:0xfffff0ff,khaki:0xf0e68cff,lavender:0xe6e6faff,lavenderblush:0xfff0f5ff,lawngreen:0x7cfc00ff,lemonchiffon:0xfffacdff,lightblue:0xadd8e6ff,lightcoral:0xf08080ff,lightcyan:0xe0ffffff,lightgoldenrodyellow:0xfafad2ff,lightgray:0xd3d3d3ff,lightgreen:0x90ee90ff,lightgrey:0xd3d3d3ff,lightpink:0xffb6c1ff,lightsalmon:0xffa07aff,lightseagreen:0x20b2aaff,lightskyblue:0x87cefaff,lightslategray:0x778899ff,lightslategrey:0x778899ff,lightsteelblue:0xb0c4deff,lightyellow:0xffffe0ff,lime:0x00ff00ff,limegreen:0x32cd32ff,linen:0xfaf0e6ff,magenta:0xff00ffff,maroon:0x800000ff,mediumaquamarine:0x66cdaaff,mediumblue:0x0000cdff,mediumorchid:0xba55d3ff,mediumpurple:0x9370dbff,mediumseagreen:0x3cb371ff,mediumslateblue:0x7b68eeff,mediumspringgreen:0x00fa9aff,mediumturquoise:0x48d1ccff,mediumvioletred:0xc71585ff,midnightblue:0x191970ff,mintcream:0xf5fffaff,mistyrose:0xffe4e1ff,moccasin:0xffe4b5ff,navajowhite:0xffdeadff,navy:0x000080ff,oldlace:0xfdf5e6ff,olive:0x808000ff,olivedrab:0x6b8e23ff,orange:0xffa500ff,orangered:0xff4500ff,orchid:0xda70d6ff,palegoldenrod:0xeee8aaff,palegreen:0x98fb98ff,paleturquoise:0xafeeeeff,palevioletred:0xdb7093ff,papayawhip:0xffefd5ff,peachpuff:0xffdab9ff,peru:0xcd853fff,pink:0xffc0cbff,plum:0xdda0ddff,powderblue:0xb0e0e6ff,purple:0x800080ff,rebeccapurple:0x663399ff,red:0xff0000ff,rosybrown:0xbc8f8fff,royalblue:0x4169e1ff,saddlebrown:0x8b4513ff,salmon:0xfa8072ff,sandybrown:0xf4a460ff,seagreen:0x2e8b57ff,seashell:0xfff5eeff,sienna:0xa0522dff,silver:0xc0c0c0ff,skyblue:0x87ceebff,slateblue:0x6a5acdff,slategray:0x708090ff,slategrey:0x708090ff,snow:0xfffafaff,springgreen:0x00ff7fff,steelblue:0x4682b4ff,tan:0xd2b48cff,teal:0x008080ff,thistle:0xd8bfd8ff,tomato:0xff6347ff,turquoise:0x40e0d0ff,violet:0xee82eeff,wheat:0xf5deb3ff,white:0xffffffff,whitesmoke:0xf5f5f5ff,yellow:0xffff00ff,yellowgreen:0x9acd32ff"; -BOOL HPIsMainQueue() { +BOOL HippyIsMainQueue(void) { static void *mainQueueKey = &mainQueueKey; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -37,16 +37,16 @@ BOOL HPIsMainQueue() { return dispatch_get_specific(mainQueueKey) == mainQueueKey; } -void HPExecuteOnMainQueue(dispatch_block_t block) { - if (HPIsMainQueue()) { +void HippyExecuteOnMainQueue(dispatch_block_t block) { + if (HippyIsMainQueue()) { block(); } else { dispatch_async(dispatch_get_main_queue(), block); } } -void HPExecuteOnMainThread(dispatch_block_t block, BOOL sync) { - if (HPIsMainQueue()) { +void HippyExecuteOnMainThread(dispatch_block_t block, BOOL sync) { + if (HippyIsMainQueue()) { block(); } else if (sync) { dispatch_sync(dispatch_get_main_queue(), block); @@ -55,7 +55,7 @@ void HPExecuteOnMainThread(dispatch_block_t block, BOOL sync) { } } -void HPSwapClassMethods(Class cls, SEL original, SEL replacement) { +void HippySwapClassMethods(Class cls, SEL original, SEL replacement) { Method originalMethod = class_getClassMethod(cls, original); IMP originalImplementation = method_getImplementation(originalMethod); const char *originalArgTypes = method_getTypeEncoding(originalMethod); @@ -71,7 +71,7 @@ void HPSwapClassMethods(Class cls, SEL original, SEL replacement) { } } -void HPSwapInstanceMethods(Class cls, SEL original, SEL replacement) { +void HippySwapInstanceMethods(Class cls, SEL original, SEL replacement) { Method originalMethod = class_getInstanceMethod(cls, original); IMP originalImplementation = method_getImplementation(originalMethod); const char *originalArgTypes = method_getTypeEncoding(originalMethod); @@ -87,11 +87,11 @@ void HPSwapInstanceMethods(Class cls, SEL original, SEL replacement) { } } -BOOL HPClassOverridesClassMethod(Class cls, SEL selector) { - return HPClassOverridesInstanceMethod(object_getClass(cls), selector); +BOOL HippyClassOverridesClassMethod(Class cls, SEL selector) { + return HippyClassOverridesInstanceMethod(object_getClass(cls), selector); } -BOOL HPClassOverridesInstanceMethod(Class cls, SEL selector) { +BOOL HippyClassOverridesInstanceMethod(Class cls, SEL selector) { unsigned int numberOfMethods; Method *methods = class_copyMethodList(cls, &numberOfMethods); for (unsigned int i = 0; i < numberOfMethods; i++) { @@ -104,7 +104,7 @@ BOOL HPClassOverridesInstanceMethod(Class cls, SEL selector) { return NO; } -BOOL HPRunningInTestEnvironment(void) { +BOOL HippyRunningInTestEnvironment(void) { static BOOL isTestEnvironment = NO; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -113,23 +113,23 @@ BOOL HPRunningInTestEnvironment(void) { return isTestEnvironment; } -BOOL HPRunningInAppExtension(void) { +BOOL HippyRunningInAppExtension(void) { return [[[[NSBundle mainBundle] bundlePath] pathExtension] isEqualToString:@"appex"]; } -UIApplication *__nullable HPSharedApplication(void) { - if (HPRunningInAppExtension()) { +UIApplication *__nullable HippySharedApplication(void) { + if (HippyRunningInAppExtension()) { return nil; } return [[UIApplication class] performSelector:@selector(sharedApplication)]; } -UIWindow *__nullable HPKeyWindow(void) { - if (HPRunningInAppExtension()) { +UIWindow *__nullable HippyKeyWindow(void) { + if (HippyRunningInAppExtension()) { return nil; } UIWindow *keyWindow = nil; - UIApplication *application = HPSharedApplication(); + UIApplication *application = HippySharedApplication(); if (@available(iOS 13.0, *)) { NSArray *scenes = [[application connectedScenes] allObjects]; BOOL keyWindowFound = NO; @@ -166,12 +166,12 @@ BOOL HPRunningInAppExtension(void) { return keyWindow; } -UIViewController *__nullable HPPresentedViewController(void) { - if (HPRunningInAppExtension()) { +UIViewController *__nullable HippyPresentedViewController(void) { + if (HippyRunningInAppExtension()) { return nil; } - UIViewController *controller = HPKeyWindow().rootViewController; + UIViewController *controller = HippyKeyWindow().rootViewController; while (controller.presentedViewController) { controller = controller.presentedViewController; @@ -180,7 +180,7 @@ BOOL HPRunningInAppExtension(void) { return controller; } -BOOL HPForceTouchAvailable(void) { +BOOL HippyForceTouchAvailable(void) { static BOOL forceSupported; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -189,35 +189,35 @@ BOOL HPForceTouchAvailable(void) { BOOL forceTouchCapability = NO; if (@available(iOS 9.0, *)) { - forceTouchCapability = (HPKeyWindow() ?: [UIView new]).traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable; + forceTouchCapability = (HippyKeyWindow() ?: [UIView new]).traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable; } return forceSupported && forceTouchCapability; } -NSError *HPErrorWithMessage(NSString *message) { +NSError *HippyErrorWithMessage(NSString *message) { NSDictionary *errorInfo = @ { NSLocalizedDescriptionKey: message }; - return [[NSError alloc] initWithDomain:HPErrorDomain code:0 userInfo:errorInfo]; + return [[NSError alloc] initWithDomain:HippyErrorDomain code:0 userInfo:errorInfo]; } -NSError *HPErrorWithMessageAndModuleName(NSString *message, NSString *moduleName) { - NSDictionary *errorInfo = @ { NSLocalizedDescriptionKey: message, HPFatalModuleName: moduleName ?: @"unknown" }; - return [[NSError alloc] initWithDomain:HPErrorDomain code:0 userInfo:errorInfo]; +NSError *HippyErrorWithMessageAndModuleName(NSString *message, NSString *moduleName) { + NSDictionary *errorInfo = @ { NSLocalizedDescriptionKey: message, HippyFatalModuleName: moduleName ?: @"unknown" }; + return [[NSError alloc] initWithDomain:HippyErrorDomain code:0 userInfo:errorInfo]; } -NSError *HPErrorFromErrorAndModuleName(NSError *error, NSString *moduleName) { +NSError *HippyErrorFromErrorAndModuleName(NSError *error, NSString *moduleName) { NSDictionary *userInfo = [error userInfo]; if (userInfo) { NSMutableDictionary *ui = [NSMutableDictionary dictionaryWithDictionary:userInfo]; - [ui setObject:moduleName ?: @"unknown" forKey:HPFatalModuleName]; + [ui setObject:moduleName ?: @"unknown" forKey:HippyFatalModuleName]; userInfo = [NSDictionary dictionaryWithDictionary:ui]; } else { - userInfo = @ { HPFatalModuleName: moduleName ?: @"unknown" }; + userInfo = @ { HippyFatalModuleName: moduleName ?: @"unknown" }; } NSError *retError = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo]; return retError; } -double HPZeroIfNaN(double value) { +double HippyZeroIfNaN(double value) { return isnan(value) || isinf(value) ? 0 : value; } @@ -251,9 +251,9 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { case kCGColorSpaceModelLab: case kCGColorSpaceModelPattern: case kCGColorSpaceModelUnknown: { -#if HP_DEBUG +#if HIPPY_DEBUG // unsupported format - HPLogError(@"Unsupported color model: %i", model); + HippyLogError(@"Unsupported color model: %i", model); #endif rgba[0] = 0.0; @@ -268,7 +268,7 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { } } -NSString *HPColorToHexString(CGColorRef color) { +NSString *HippyColorToHexString(CGColorRef color) { CGFloat rgba[4]; HPGetRGBAColorComponents(color, rgba); uint8_t r = rgba[0] * 255; @@ -298,7 +298,7 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { unsigned int colorInteger; BOOL scanSuccess = [scan scanHexInt:&colorInteger]; if (scanSuccess) { - UIColor *tmpColor = HPConvertNumberToColor(colorInteger); + UIColor *tmpColor = HippyConvertNumberToColor(colorInteger); [tmpColorDic setObject:tmpColor forKey:key]; } } @@ -310,7 +310,7 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { return color; } -UIColor *HPConvertStringToColor(NSString *colorString) { +UIColor *HippyConvertStringToColor(NSString *colorString) { if (!colorString) { return nil; } @@ -361,12 +361,12 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { scanResult = colorInteger; } if (scanSuccess) { - color = HPConvertNumberToColor(scanResult); + color = HippyConvertNumberToColor(scanResult); } return color; } -UIColor *HPConvertNumberToColor(NSInteger colorNumber) { +UIColor *HippyConvertNumberToColor(NSInteger colorNumber) { NSInteger a = (colorNumber >> 24) & 0xFF; NSInteger r = (colorNumber >> 16) & 0xFF; NSInteger g = (colorNumber >> 8) & 0xFF; @@ -379,12 +379,12 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { } // (https://github.com/0xced/XCDFormInputAccessoryView/blob/master/XCDFormInputAccessoryView/XCDFormInputAccessoryView.m#L10-L14) -NSString *HPUIKitLocalizedString(NSString *string) { +NSString *HippyUIKitLocalizedString(NSString *string) { NSBundle *UIKitBundle = [NSBundle bundleForClass:[UIApplication class]]; return UIKitBundle ? [UIKitBundle localizedStringForKey:string value:string table:nil] : string; } -NSString *__nullable HPGetURLQueryParam(NSURL *__nullable URL, NSString *param) { +NSString *__nullable HippyGetURLQueryParam(NSURL *__nullable URL, NSString *param) { if (!URL) { return nil; } @@ -399,7 +399,7 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { return nil; } -NSURL *__nullable HPURLByReplacingQueryParam(NSURL *__nullable URL, NSString *param, NSString *__nullable value) { +NSURL *__nullable HippyURLByReplacingQueryParam(NSURL *__nullable URL, NSString *param, NSString *__nullable value) { if (!URL) { return nil; } @@ -431,9 +431,9 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { return components.URL; } -NSURL *__nullable HPURLWithString(NSString *URLString, NSString *baseURLString) { +NSURL *__nullable HippyURLWithString(NSString *URLString, NSString *baseURLString) { if (URLString) { - NSURL *baseURL = HPURLWithString(baseURLString, NULL); + NSURL *baseURL = HippyURLWithString(baseURLString, NULL); NSData *uriData = [URLString dataUsingEncoding:NSUTF8StringEncoding]; if (nil == uriData) { return nil; @@ -453,7 +453,7 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { return nil; } -NSString *HPSchemeFromURLString(NSString *urlString) { +NSString *HippySchemeFromURLString(NSString *urlString) { NSUInteger location = [urlString rangeOfString:@":"].location; if (NSNotFound == location || 0 == location) { return @""; @@ -461,7 +461,7 @@ static void HPGetRGBAColorComponents(CGColorRef color, CGFloat rgba[4]) { return [urlString substringToIndex:location]; } -NSStringEncoding HPGetStringEncodingFromURLResponse(NSURLResponse *response) { +NSStringEncoding HippyGetStringEncodingFromURLResponse(NSURLResponse *response) { NSString *textEncoding = [response textEncodingName]; if (!textEncoding) { return NSUTF8StringEncoding; @@ -470,3 +470,231 @@ NSStringEncoding HPGetStringEncodingFromURLResponse(NSURLResponse *response) { NSStringEncoding dataEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); return dataEncoding; } + + +NSString *const HippyErrorUnspecified = @"HippyErrorUnspecified"; + +static NSString *__nullable _HPJSONStringifyNoRetry(id __nullable jsonObject, NSError **error) { + if (!jsonObject) { + return nil; + } + + static SEL JSONKitSelector = NULL; + static NSSet *collectionTypes; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + SEL selector = NSSelectorFromString(@"JSONStringWithOptions:error:"); + if ([NSDictionary instancesRespondToSelector:selector]) { + JSONKitSelector = selector; + collectionTypes = [NSSet setWithObjects:[NSArray class], [NSMutableArray class], [NSDictionary class], [NSMutableDictionary class], nil]; + } + }); + + @try { + // Use JSONKit if available and object is not a fragment + if (JSONKitSelector && [collectionTypes containsObject:[jsonObject classForCoder]]) { + return ((NSString * (*)(id, SEL, int, NSError **)) objc_msgSend)(jsonObject, JSONKitSelector, 0, error); + } + + // Use Foundation JSON method + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:(NSJSONWritingOptions)NSJSONReadingAllowFragments error:error]; + + return jsonData ? [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] : nil; + } @catch (NSException *exception) { + // Convert exception to error + if (error) { + *error = [NSError errorWithDomain:HippyErrorDomain code:0 userInfo:@ { NSLocalizedDescriptionKey: exception.description ?: @"" }]; + } + return nil; + } +} + +NSString *__nullable HippyJSONStringify(id __nullable jsonObject, NSError **error) { + if (error) { + return _HPJSONStringifyNoRetry(jsonObject, error); + } else { + NSError *localError; + NSString *json = _HPJSONStringifyNoRetry(jsonObject, &localError); + if (localError) { + HippyLogError(@"HPJSONStringify() encountered the following error: %@", localError.localizedDescription); + // Sanitize the data, then retry. This is slow, but it prevents uncaught + // data issues from crashing in production + return _HPJSONStringifyNoRetry(HippyJSONClean(jsonObject), NULL); + } + return json; + } +} + +static id __nullable _HPJSONParse(NSString *__nullable jsonString, BOOL mutable, NSError **error) { + static SEL JSONKitSelector = NULL; + static SEL JSONKitMutableSelector = NULL; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + SEL selector = NSSelectorFromString(@"objectFromJSONStringWithParseOptions:error:"); + if ([NSString instancesRespondToSelector:selector]) { + JSONKitSelector = selector; + JSONKitMutableSelector = NSSelectorFromString(@"mutableObjectFromJSONStringWithParseOptions:error:"); + } + }); + + if (jsonString) { + // Use JSONKit if available and string is not a fragment + if (JSONKitSelector) { + NSInteger length = jsonString.length; + for (NSInteger i = 0; i < length; i++) { + unichar c = [jsonString characterAtIndex:i]; + if (strchr("{[", c)) { + static const int options = (1 << 2); // loose unicode + SEL selector = mutable ? JSONKitMutableSelector : JSONKitSelector; + return ((id(*)(id, SEL, int, NSError **))objc_msgSend)(jsonString, selector, options, error); + } + if (!strchr(" \r\n\t", c)) { + break; + } + } + } + + // Use Foundation JSON method + NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; + if (!jsonData) { + jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; + if (jsonData) { + HippyLogWarn(@"HPJSONParse received the following string, which could " + "not be losslessly converted to UTF8 data: '%@'", + jsonString); + } else { + NSString *errorMessage = @"HPJSONParse received invalid UTF8 data"; + if (error) { + *error = HippyErrorWithMessage(errorMessage); + } else { + HippyLogError(@"%@", errorMessage); + } + return nil; + } + } + NSJSONReadingOptions options = NSJSONReadingAllowFragments; + if (mutable) { + options |= NSJSONReadingMutableContainers; + } + return [NSJSONSerialization JSONObjectWithData:jsonData options:options error:error]; + } + return nil; +} + +id __nullable HippyJSONParse(NSString *__nullable jsonString, NSError **error) { + return _HPJSONParse(jsonString, NO, error); +} + +id __nullable HippyJSONParseMutable(NSString *__nullable jsonString, NSError **error) { + return _HPJSONParse(jsonString, YES, error); +} + +id HippyJSONClean(id object) { + static dispatch_once_t onceToken; + static NSSet *validLeafTypes; + dispatch_once(&onceToken, ^{ + validLeafTypes = [[NSSet alloc] initWithArray:@[ + [NSString class], + [NSMutableString class], + [NSNumber class], + [NSNull class], + ]]; + }); + + if ([validLeafTypes containsObject:[object classForCoder]]) { + if ([object isKindOfClass:[NSNumber class]]) { + return @(HippyZeroIfNaN([object doubleValue])); + } + if ([object isKindOfClass:[NSString class]]) { + if ([object UTF8String] == NULL) { + return (id)kCFNull; + } + } + return object; + } + + if ([object isKindOfClass:[NSDictionary class]]) { + __block BOOL copy = NO; + NSMutableDictionary *values = [[NSMutableDictionary alloc] initWithCapacity:[object count]]; + [object enumerateKeysAndObjectsUsingBlock:^(NSString *key, id item, __unused BOOL *stop) { + id value = HippyJSONClean(item); + values[key] = value; + copy |= value != item; + }]; + return copy ? values : object; + } + + if ([object isKindOfClass:[NSArray class]]) { + __block BOOL copy = NO; + __block NSArray *values = object; + [object enumerateObjectsUsingBlock:^(id item, NSUInteger idx, __unused BOOL *stop) { + id value = HippyJSONClean(item); + if (copy) { + [(NSMutableArray *)values addObject:value]; + } else if (value != item) { + // Converted value is different, so we'll need to copy the array + values = [[NSMutableArray alloc] initWithCapacity:values.count]; + for (NSUInteger i = 0; i < idx; i++) { + [(NSMutableArray *)values addObject:object[i]]; + } + [(NSMutableArray *)values addObject:value]; + copy = YES; + } + }]; + return values; + } + + return (id)kCFNull; +} + +NSString *HippyMD5Hash(NSString *string) { + const char *str = string.UTF8String; + unsigned char result[CC_MD5_DIGEST_LENGTH]; + CC_MD5(str, (CC_LONG)strlen(str), result); + + return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", result[0], result[1], result[2], result[3], + result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], + result[15]]; +} + +NSDictionary *HippyMakeError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData) { + if (toStringify) { + message = [message stringByAppendingString:[toStringify description]]; + } + + NSMutableDictionary *error = [extraData mutableCopy] ?: [NSMutableDictionary new]; + error[@"message"] = message; + return error; +} + +NSDictionary *HippyMakeAndLogError(NSString *message, id __nullable toStringify, NSDictionary *__nullable extraData) { + NSDictionary *error = HippyMakeError(message, toStringify, extraData); + HippyLogError(@"\nError: %@", error); + return error; +} + +NSDictionary *HippyJSErrorFromNSError(NSError *error) { + NSString *codeWithDomain = [NSString stringWithFormat:@"E%@%ld", error.domain.uppercaseString, (long)error.code]; + return HippyJSErrorFromCodeMessageAndNSError(codeWithDomain, error.localizedDescription, error); +} + +NSDictionary *HippyJSErrorFromCodeMessageAndNSError(NSString *code, NSString *message, NSError *__nullable error) { + NSString *errorMessage; + NSArray *stackTrace = [NSThread callStackSymbols]; + NSMutableDictionary *errorInfo = [NSMutableDictionary dictionaryWithObject:stackTrace forKey:@"nativeStackIOS"]; + + if (error) { + errorMessage = error.localizedDescription ?: @"Unknown error from a native module"; + errorInfo[@"domain"] = error.domain ?: HippyErrorDomain; + } else { + errorMessage = @"Unknown error from a native module"; + errorInfo[@"domain"] = HippyErrorDomain; + } + errorInfo[@"code"] = code ?: HippyErrorUnspecified; + errorInfo[@"userInfo"] = HippyNullIfNil(error.userInfo); + + // Allow for explicit overriding of the error message + errorMessage = message ?: errorMessage; + + return HippyMakeError(errorMessage, nil, errorInfo); +} diff --git a/modules/ios/base/MacroDefines.h b/modules/ios/base/MacroDefines.h deleted file mode 100644 index 6be51b67366..00000000000 --- a/modules/ios/base/MacroDefines.h +++ /dev/null @@ -1,72 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * HP available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if __OBJC__ -#import -#endif - -/** - * Make global functions usable in C++ - */ -#if defined(__cplusplus) -#define HP_EXTERN extern "C" __attribute__((visibility("default"))) -#else -#define HP_EXTERN extern __attribute__((visibility("default"))) -#endif - -/** - * The HP_DEBUG macro can be used to exclude error checking and logging code - * from release builds to improve performance and reduce binary size. - */ -#ifndef HP_DEBUG -#ifdef DEBUG -#define HP_DEBUG 1 -#else -#define HP_DEBUG 0 -#endif //#ifdef DEBUG -#endif //#ifndef HP_DEBUG - -/** - * The HP_DEV macro can be used to enable or disable development tools - * such as the debug executors, dev menu, red box, etc. - */ -#ifndef HP_DEV -#ifdef DEBUG -#define HP_DEV 1 -#else -#define HP_DEV 0 -#endif //#ifdef DEBUG -#endif //#ifndef HP_DEV - -#ifndef HP_NSASSERT -#define HP_NSASSERT HP_DEBUG -#endif //#ifndef HIPPY_NSASSERT - -/** - * Concat two literals. Supports macro expansions, - * e.g. HP_CONCAT(foo, __FILE__). - */ -#define HP_CONCAT2(A, B) A##B -#define HP_CONCAT(A, B) HP_CONCAT2(A, B) - -#define kRootViewDidAddContent @"RootViewDidAddContent" -#define kRootViewKey @"RootViewKey" diff --git a/modules/ios/base/NSObject+Render.h b/modules/ios/base/NSObject+Render.h index de33d40859e..2b3ad2d569d 100644 --- a/modules/ios/base/NSObject+Render.h +++ b/modules/ios/base/NSObject+Render.h @@ -32,7 +32,8 @@ class RenderManager; }; }; -@interface NSObject (Render) +// FIXME: remove this category +@interface UIView (HippyRenderManager) @property(nonatomic, assign) std::weak_ptr renderManager; diff --git a/modules/ios/base/NSObject+Render.mm b/modules/ios/base/NSObject+Render.mm index d6f5fa6dd49..fd4291d02d5 100644 --- a/modules/ios/base/NSObject+Render.mm +++ b/modules/ios/base/NSObject+Render.mm @@ -35,7 +35,7 @@ @implementation RenderManagerWrapper @end -@implementation NSObject (Render) +@implementation UIView (HippyRenderManager) - (void)setRenderManager:(std::weak_ptr)renderManager { RenderManagerWrapper *wrapper = [[RenderManagerWrapper alloc] init]; diff --git a/modules/ios/base/TypeConverter.h b/modules/ios/base/TypeConverter.h index ad6cee94f01..216ff2657dd 100644 --- a/modules/ios/base/TypeConverter.h +++ b/modules/ios/base/TypeConverter.h @@ -23,7 +23,7 @@ #import #import -#import "MacroDefines.h" +#import "HippyDefines.h" #include #include @@ -31,10 +31,10 @@ NS_ASSUME_NONNULL_BEGIN -HP_EXTERN NSDictionary *StringUnorderedMapToNSDictionary(const std::unordered_map &); +HIPPY_EXTERN NSDictionary *StringUnorderedMapToNSDictionary(const std::unordered_map &); std::unordered_map NSDictionaryToStringUnorderedMap(NSDictionary *dictionary); -HP_EXTERN NSURLResponse *ResponseMapToURLResponse(NSURL *url, const std::unordered_map &headerMap, size_t contentsLength); +HIPPY_EXTERN NSURLResponse *ResponseMapToURLResponse(NSURL *url, const std::unordered_map &headerMap, size_t contentsLength); NS_ASSUME_NONNULL_END diff --git a/modules/ios/base/TypeConverter.mm b/modules/ios/base/TypeConverter.mm index 355d5faee28..80d5d46e877 100644 --- a/modules/ios/base/TypeConverter.mm +++ b/modules/ios/base/TypeConverter.mm @@ -21,7 +21,7 @@ */ #import "TypeConverter.h" -#import "HPToolUtils.h" +#import "HippyUtils.h" NSDictionary *StringUnorderedMapToNSDictionary(const std::unordered_map &map) { NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:map.size()]; diff --git a/modules/ios/domutils/HPDomUtils.h b/modules/ios/domutils/HippyDomUtils.h similarity index 70% rename from modules/ios/domutils/HPDomUtils.h rename to modules/ios/domutils/HippyDomUtils.h index e43236a9f93..e4f4585375b 100644 --- a/modules/ios/domutils/HPDomUtils.h +++ b/modules/ios/domutils/HippyDomUtils.h @@ -23,7 +23,7 @@ #import #import -#import "MacroDefines.h" +#import "HippyDefines.h" #include @@ -36,14 +36,14 @@ class DomNode; NS_ASSUME_NONNULL_BEGIN -HP_EXTERN CGRect CGRectMakeFromLayoutResult(hippy::LayoutResult result); +HIPPY_EXTERN CGRect CGRectMakeFromLayoutResult(hippy::LayoutResult result); -HP_EXTERN UIEdgeInsets UIEdgeInsetsFromLayoutResult(hippy::LayoutResult result); +HIPPY_EXTERN UIEdgeInsets UIEdgeInsetsFromLayoutResult(hippy::LayoutResult result); -HP_EXTERN CGSize CGSizeMakeFromLayoutResult(hippy::LayoutResult result); +HIPPY_EXTERN CGSize CGSizeMakeFromLayoutResult(hippy::LayoutResult result); -HP_EXTERN CGRect CGRectMakeFromDomNode(const std::shared_ptr &domNode); +HIPPY_EXTERN CGRect CGRectMakeFromDomNode(const std::shared_ptr &domNode); -HP_EXTERN NSDictionary *StylesFromDomNode(const std::shared_ptr &domNode); +HIPPY_EXTERN NSDictionary *StylesFromDomNode(const std::shared_ptr &domNode); NS_ASSUME_NONNULL_END diff --git a/modules/ios/domutils/HPDomUtils.mm b/modules/ios/domutils/HippyDomUtils.mm similarity index 97% rename from modules/ios/domutils/HPDomUtils.mm rename to modules/ios/domutils/HippyDomUtils.mm index 4693b2215f0..1b50f554a52 100644 --- a/modules/ios/domutils/HPDomUtils.mm +++ b/modules/ios/domutils/HippyDomUtils.mm @@ -22,8 +22,8 @@ #import -#import "HPDomUtils.h" -#import "HPFootstoneUtils.h" +#import "HippyDomUtils.h" +#import "HippyFootstoneUtils.h" #include "dom/dom_listener.h" #include "dom/dom_node.h" diff --git a/modules/ios/domutils/HPOCToDomArgument.h b/modules/ios/domutils/HippyOCToDomArgument.h similarity index 95% rename from modules/ios/domutils/HPOCToDomArgument.h rename to modules/ios/domutils/HippyOCToDomArgument.h index 8c0fcf8d7c5..455943f93df 100644 --- a/modules/ios/domutils/HPOCToDomArgument.h +++ b/modules/ios/domutils/HippyOCToDomArgument.h @@ -36,7 +36,7 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface NSObject (HPOCToDomArgument) +@interface NSObject (HippyOCToDomArgument) @end diff --git a/modules/ios/domutils/HPOCToDomArgument.mm b/modules/ios/domutils/HippyOCToDomArgument.mm similarity index 88% rename from modules/ios/domutils/HPOCToDomArgument.mm rename to modules/ios/domutils/HippyOCToDomArgument.mm index 503cb8f818d..23b7ff6517e 100644 --- a/modules/ios/domutils/HPOCToDomArgument.mm +++ b/modules/ios/domutils/HippyOCToDomArgument.mm @@ -20,13 +20,13 @@ * limitations under the License. */ -#import "HPOCToDomArgument.h" +#import "HippyOCToDomArgument.h" -#import "HPOCToHippyValue.h" +#import "HippyOCToHippyValue.h" #include "dom/dom_argument.h" -@implementation NSObject (HPOCToDomArgument) +@implementation NSObject (HippyOCToDomArgument) - (hippy::DomArgument)toDomArgument { return hippy::DomArgument([self toHippyValue]); diff --git a/modules/ios/footstoneutils/HPFootstoneUtils.h b/modules/ios/footstoneutils/HippyFootstoneUtils.h similarity index 70% rename from modules/ios/footstoneutils/HPFootstoneUtils.h rename to modules/ios/footstoneutils/HippyFootstoneUtils.h index 60bee96a540..6802ee4bd11 100644 --- a/modules/ios/footstoneutils/HPFootstoneUtils.h +++ b/modules/ios/footstoneutils/HippyFootstoneUtils.h @@ -25,7 +25,7 @@ #include #include -#include "MacroDefines.h" +#include "HippyDefines.h" NS_ASSUME_NONNULL_BEGIN @@ -43,17 +43,17 @@ extern footstone::string_view NSStringToU8StringView(NSString *str); extern footstone::string_view NSStringToU16StringView(NSString *string); -HP_EXTERN NSString *StringViewToNSString(const footstone::string_view &view); +HIPPY_EXTERN NSString *StringViewToNSString(const footstone::string_view &view); -HP_EXTERN NSURL *StringViewToNSURL(const footstone::string_view &uri); +HIPPY_EXTERN NSURL *StringViewToNSURL(const footstone::string_view &uri); extern footstone::value::HippyValue OCTypeToDomValue(id value); //footstone::hippyValue -HP_EXTERN id DomValueToOCType(const footstone::value::HippyValue *const pDomValue); +HIPPY_EXTERN id DomValueToOCType(const footstone::value::HippyValue *const pDomValue); -HP_EXTERN NSDictionary *UnorderedMapDomValueToDictionary(const std::shared_ptr>> &domValuesObject); +HIPPY_EXTERN NSDictionary *UnorderedMapDomValueToDictionary(const std::shared_ptr>> &domValuesObject); -HP_EXTERN NSNumber *DomValueToNumber(const footstone::value::HippyValue *const pDomValue); +HIPPY_EXTERN NSNumber *DomValueToNumber(const footstone::value::HippyValue *const pDomValue); NS_ASSUME_NONNULL_END diff --git a/modules/ios/footstoneutils/HPFootstoneUtils.mm b/modules/ios/footstoneutils/HippyFootstoneUtils.mm similarity index 98% rename from modules/ios/footstoneutils/HPFootstoneUtils.mm rename to modules/ios/footstoneutils/HippyFootstoneUtils.mm index 39083567bad..aecf01e10c7 100644 --- a/modules/ios/footstoneutils/HPFootstoneUtils.mm +++ b/modules/ios/footstoneutils/HippyFootstoneUtils.mm @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "HPFootstoneUtils.h" -#import "HPToolUtils.h" +#import "HippyFootstoneUtils.h" +#import "HippyUtils.h" #include "footstone/hippy_value.h" #include "footstone/logging.h" @@ -84,7 +84,7 @@ string_view NSStringToU16StringView(NSString *string) { if (!uriString) { return nil; } - return HPURLWithString(uriString, nil); + return HippyURLWithString(uriString, nil); } #pragma mark HippyValue utils diff --git a/modules/ios/footstoneutils/HPOCToHippyValue.h b/modules/ios/footstoneutils/HippyOCToHippyValue.h similarity index 100% rename from modules/ios/footstoneutils/HPOCToHippyValue.h rename to modules/ios/footstoneutils/HippyOCToHippyValue.h diff --git a/modules/ios/footstoneutils/HPOCToHippyValue.mm b/modules/ios/footstoneutils/HippyOCToHippyValue.mm similarity index 98% rename from modules/ios/footstoneutils/HPOCToHippyValue.mm rename to modules/ios/footstoneutils/HippyOCToHippyValue.mm index 1856fc7bb69..56aefcf564f 100644 --- a/modules/ios/footstoneutils/HPOCToHippyValue.mm +++ b/modules/ios/footstoneutils/HippyOCToHippyValue.mm @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "HPOCToHippyValue.h" +#import "HippyOCToHippyValue.h" #include "footstone/hippy_value.h" diff --git a/modules/ios/image/HPDefaultImageProvider.h b/modules/ios/image/HippyDefaultImageProvider.h similarity index 86% rename from modules/ios/image/HPDefaultImageProvider.h rename to modules/ios/image/HippyDefaultImageProvider.h index cafa3010108..4df2057dfc8 100644 --- a/modules/ios/image/HPDefaultImageProvider.h +++ b/modules/ios/image/HippyDefaultImageProvider.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,9 +21,9 @@ */ #import -#import "HPImageProviderProtocol.h" +#import "HippyImageProviderProtocol.h" -@interface HPDefaultImageProvider : NSObject +@interface HippyDefaultImageProvider : NSObject @property (nonatomic, assign) BOOL downSample; @property (nonatomic, assign) CGSize imageViewSize; diff --git a/modules/ios/image/HPDefaultImageProvider.m b/modules/ios/image/HippyDefaultImageProvider.m similarity index 97% rename from modules/ios/image/HPDefaultImageProvider.m rename to modules/ios/image/HippyDefaultImageProvider.m index 4c8b5f334e1..d870be66fd1 100644 --- a/modules/ios/image/HPDefaultImageProvider.m +++ b/modules/ios/image/HippyDefaultImageProvider.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,11 +21,11 @@ */ #import -#import "HPDefaultImageProvider.h" +#import "HippyDefaultImageProvider.h" #import "NSData+DataType.h" #import -@interface HPDefaultImageProvider () { +@interface HippyDefaultImageProvider () { NSData *_data; UIImage *_image; CGImageSourceRef _imageSourceRef; @@ -33,7 +33,7 @@ @interface HPDefaultImageProvider () { @end -@implementation HPDefaultImageProvider +@implementation HippyDefaultImageProvider @synthesize imageDataPath; diff --git a/modules/ios/image/HPImageProviderProtocol.h b/modules/ios/image/HippyImageProviderProtocol.h similarity index 97% rename from modules/ios/image/HPImageProviderProtocol.h rename to modules/ios/image/HippyImageProviderProtocol.h index f6ebaf37eb4..60877dec7f4 100644 --- a/modules/ios/image/HPImageProviderProtocol.h +++ b/modules/ios/image/HippyImageProviderProtocol.h @@ -24,7 +24,7 @@ @class UIImage; -@protocol HPImageProviderProtocol +@protocol HippyImageProviderProtocol @required diff --git a/modules/ios/image/NSData+DataType.h b/modules/ios/image/NSData+DataType.h index 05a8ab6c728..f029b8a7ece 100644 --- a/modules/ios/image/NSData+DataType.h +++ b/modules/ios/image/NSData+DataType.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/modules/ios/image/NSData+DataType.m b/modules/ios/image/NSData+DataType.m index d245261a6bf..226240d1110 100644 --- a/modules/ios/image/NSData+DataType.m +++ b/modules/ios/image/NSData+DataType.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/modules/ios/logutils/HPLogUtils.mm b/modules/ios/logutils/HPLogUtils.mm deleted file mode 100644 index 31e20af065f..00000000000 --- a/modules/ios/logutils/HPLogUtils.mm +++ /dev/null @@ -1,98 +0,0 @@ -/* - * - * Tencent is pleased to support the open source community by making - * Hippy available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#import "HPLogUtils.h" - -#include -#include - -#include "footstone/log_level.h" -#include "footstone/logging.h" - -using LogSeverity = footstone::LogSeverity; - -static HPLogLevel logSeverityToLogLevel(LogSeverity severity) { - HPLogLevel level = HPLogLevelInfo; - switch (severity) { - case LogSeverity::TDF_LOG_WARNING: - level = HPLogLevelWarning; - break; - case LogSeverity::TDF_LOG_ERROR: - level = HPLogLevelError; - break; - case LogSeverity::TDF_LOG_FATAL: - level = HPLogLevelFatal; - break; - default: - break; - } - return level; -} - -static BOOL GetFileNameAndLineNumberFromLogMessage(NSString *message, NSString **fileName, int *lineNumber) { - //[INFO:cubic_bezier_animation.cc(146)] animation exec_time_ = 514, delay = 500, duration = 1000 - NSUInteger locationOfColon = [message rangeOfString:@":"].location; - if (NSNotFound == locationOfColon) { - return NO; - } - NSUInteger locationOfLeftBracket = [message rangeOfString:@"("].location; - if (NSNotFound == locationOfLeftBracket) { - return NO; - } - if (locationOfLeftBracket <= locationOfColon) { - return NO; - } - NSString *name = [message substringWithRange:NSMakeRange(locationOfColon + 1, locationOfLeftBracket - locationOfColon - 1)]; - *fileName = [name copy]; - NSUInteger locationOfRightBracket = [message rangeOfString:@")"].location; - if (NSNotFound == locationOfRightBracket || locationOfRightBracket <= locationOfLeftBracket) { - return YES; - } - NSString *number = [message substringWithRange:NSMakeRange(locationOfLeftBracket + 1, locationOfRightBracket - locationOfLeftBracket - 1)]; - *lineNumber = [number intValue]; - return YES; -} - -static void registerTDFLogHandler() { - static std::once_flag flag; - std::call_once(flag, [](){ - auto logFunction = [](const std::ostringstream &stream, LogSeverity serverity) { - @autoreleasepool { - std::string string = stream.str(); - if (string.length()) { - NSString *message = [NSString stringWithUTF8String:string.c_str()]; - NSString *fileName = nil; - int lineNumber = 0; - if (GetFileNameAndLineNumberFromLogMessage(message, &fileName, &lineNumber)) { - HPLogNativeInternal(logSeverityToLogLevel(serverity), [fileName UTF8String], lineNumber, nil, @"%@", message); - } - } - } - }; - footstone::LogMessage::InitializeDelegate(logFunction); - }); -} - -void HPSetTDFLogFunction(HPLogFunction logFunction) { - registerTDFLogHandler(); - HPSetLogFunction(logFunction); -} diff --git a/modules/vfs/ios/NSURLResponse+ToUnorderedMap.h b/modules/vfs/ios/NSURLResponse+ToUnorderedMap.h index 56fc974d481..d7068444fac 100644 --- a/modules/vfs/ios/NSURLResponse+ToUnorderedMap.h +++ b/modules/vfs/ios/NSURLResponse+ToUnorderedMap.h @@ -21,7 +21,7 @@ */ #import -#import "MacroDefines.h" +#import "HippyDefines.h" #include @@ -44,4 +44,4 @@ constexpr char kStatusCode[] = "statusCode"; @end -HP_EXTERN NSURLResponse *ResponseMapToURLResponse(NSURL *url, const std::unordered_map &headerMap, size_t contentsLength); +HIPPY_EXTERN NSURLResponse *ResponseMapToURLResponse(NSURL *url, const std::unordered_map &headerMap, size_t contentsLength); diff --git a/modules/vfs/ios/NSURLSessionDataProgress.mm b/modules/vfs/ios/NSURLSessionDataProgress.mm index 83110cf88b2..bc86ff0c52b 100644 --- a/modules/vfs/ios/NSURLSessionDataProgress.mm +++ b/modules/vfs/ios/NSURLSessionDataProgress.mm @@ -23,7 +23,7 @@ #import "NSURLSessionDataProgress.h" #import "TypeConverter.h" #import "NSURLResponse+ToUnorderedMap.h" -#import "HPFootstoneUtils.h" +#import "HippyFootstoneUtils.h" #include "vfs/job_response.h" #include "vfs/request_job.h" diff --git a/modules/vfs/ios/VFSUriHandler.mm b/modules/vfs/ios/VFSUriHandler.mm index 7a939ab0fc5..c2d78d1e8b5 100644 --- a/modules/vfs/ios/VFSUriHandler.mm +++ b/modules/vfs/ios/VFSUriHandler.mm @@ -22,7 +22,7 @@ #import -#import "HPFootstoneUtils.h" +#import "HippyFootstoneUtils.h" #import "NSURLResponse+ToUnorderedMap.h" #import "NSURLSessionDataProgress.h" #import "TypeConverter.h" diff --git a/modules/vfs/ios/VFSUriLoader.mm b/modules/vfs/ios/VFSUriLoader.mm index 21acd05e77c..4f94e0dbf4a 100644 --- a/modules/vfs/ios/VFSUriLoader.mm +++ b/modules/vfs/ios/VFSUriLoader.mm @@ -20,8 +20,8 @@ * */ -#import "HPFootstoneUtils.h" -#import "HPToolUtils.h" +#import "HippyFootstoneUtils.h" +#import "HippyUtils.h" #import "TypeConverter.h" #import "VFSUriLoader.h" #import "VFSUriHandler.h" diff --git a/renderer/native/ios/renderer/HippyComponent.h b/renderer/native/ios/renderer/HippyComponent.h new file mode 100644 index 00000000000..671789f0b40 --- /dev/null +++ b/renderer/native/ios/renderer/HippyComponent.h @@ -0,0 +1,103 @@ +/*! + * iOS SDK + * + * Tencent is pleased to support the open source community by making + * Hippy available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import + +/** + * These block types can be used for mapping input event handlers from JS to view + * properties. Unlike JS method callbacks, these can be called multiple times. + */ +typedef void (^HippyDirectEventBlock)(NSDictionary *body); + +/** + * Logical node in a tree of application components. Both `NativeRenderObject` and + * `UIView` conforms to this. Allows us to write utilities that reason about + * trees generally. + */ +@protocol HippyComponent + +@property (nonatomic, strong) NSNumber *hippyTag; +@property (nonatomic, strong) NSNumber *rootTag; +@property (nonatomic, copy) NSString *tagName; +@property (nonatomic, copy) NSString *viewName; +@property (nonatomic, copy) NSDictionary *props; +@property (nonatomic, assign) CGRect frame; + +@property(nonatomic, readwrite)__kindof id parentComponent; + +- (NSArray<__kindof id> *)subcomponents; + +/// <#Description#> +/// - Parameters: +/// - subview: <#subview description#> +/// - atIndex: <#atIndex description#> +- (void)insertHippySubview:(id)subview atIndex:(NSInteger)atIndex; + +/// <#Description#> +/// - Parameter subview: <#subview description#> +- (void)removeHippySubview:(id)subview; + +/// <#Description#> +/// - Parameters: +/// - subview: <#subview description#> +/// - atIndex: <#atIndex description#> +- (void)moveHippySubview:(id)subview toIndex:(NSInteger)atIndex; + +/// <#Description#> +- (void)removeFromHippySuperview; + +/// <#Description#> +/// - Parameter frame: <#frame description#> +- (void)hippySetFrame:(CGRect)frame; + +/// <#Description#> +/// - Parameter point: <#point description#> +- (NSNumber *)hippyTagAtPoint:(CGPoint)point; + +/// View/ShadowView is a root view +- (BOOL)isHippyRootView; + + +@optional + +/// Called each time props have been set. +/// Not all props have to be set - Hippy can set only changed ones. +/// - Parameter changedProps: String names of all set props. +- (void)didSetProps:(NSArray *)changedProps; + +/// Called each time subviews have been updated +- (void)didUpdateHippySubviews; + +/// TODO: Deprecated +/// This method is called after layout has been performed for all views known +/// to the HippyViewManager. It is only called on UIViews, not shadow views. +- (void)hippyBridgeDidFinishTransaction; + +@end + + +/// Hippy use multiple of 10 as tag of root view +/// - Parameter hippyTag: hippy tag +static inline BOOL HippyIsHippyRootView(NSNumber *hippyTag) { + return hippyTag.integerValue % 10 == 0; +} diff --git a/renderer/native/ios/renderer/NativeRenderComponentData.h b/renderer/native/ios/renderer/HippyComponentData.h similarity index 63% rename from renderer/native/ios/renderer/NativeRenderComponentData.h rename to renderer/native/ios/renderer/HippyComponentData.h index 17efb8b4af6..56d541af26c 100644 --- a/renderer/native/ios/renderer/NativeRenderComponentData.h +++ b/renderer/native/ios/renderer/HippyComponentData.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,33 +21,32 @@ */ #import - -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" #import "NativeRenderDefines.h" -@class NativeRenderObjectView, NativeRenderViewManager; +@class HippyShadowView, HippyViewManager; @class UIView; -@interface NativeRenderComponentData : NSObject +@interface HippyComponentData : NSObject @property (nonatomic, readonly) Class managerClass; @property (nonatomic, copy, readonly) NSString *name; -@property (nonatomic, weak, readonly) NativeRenderViewManager *manager; +@property (nonatomic, weak, readonly) HippyViewManager *manager; -- (instancetype)initWithViewManager:(NativeRenderViewManager *)viewManager viewName:(NSString *)viewName; +- (instancetype)initWithViewManager:(HippyViewManager *)viewManager viewName:(NSString *)viewName; - (UIView *)createViewWithTag:(NSNumber *)tag; - (UIView *)createViewWithTag:(NSNumber *)tag initProps:(NSDictionary *)props; -- (NativeRenderObjectView *)createRenderObjectViewWithTag:(NSNumber *)tag; -- (void)setProps:(NSDictionary *)props forView:(id)view; -- (void)setProps:(NSDictionary *)props forRenderObjectView:(NativeRenderObjectView *)renderObject; +- (HippyShadowView *)createRenderObjectViewWithTag:(NSNumber *)tag; +- (void)setProps:(NSDictionary *)props forView:(id)view; +- (void)setProps:(NSDictionary *)props forShadowView:(HippyShadowView *)renderObject; - (NSDictionary *)eventNameMap; - (NSDictionary *)methodsByName; -- (NativeRenderRenderUIBlock)uiBlockToAmendWithRenderObjectViewRegistry:(NSDictionary *)registry; +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(NSDictionary *)registry; @end diff --git a/renderer/native/ios/renderer/NativeRenderComponentData.mm b/renderer/native/ios/renderer/HippyComponentData.mm similarity index 76% rename from renderer/native/ios/renderer/NativeRenderComponentData.mm rename to renderer/native/ios/renderer/HippyComponentData.mm index d2e699c18f0..518171f627c 100644 --- a/renderer/native/ios/renderer/NativeRenderComponentData.mm +++ b/renderer/native/ios/renderer/HippyComponentData.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,20 +21,20 @@ */ #import -#import "NativeRenderComponentData.h" -#import "NativeRenderObjectView.h" -#import "NativeRenderViewManager.h" -#import "HPConvert.h" -#import "HPToolUtils.h" -#import "UIView+NativeRender.h" +#import "HippyComponentData.h" +#import "HippyShadowView.h" +#import "HippyViewManager.h" +#import "HippyConvert.h" +#import "HippyUtils.h" +#import "UIView+Hippy.h" -typedef void (^NativeRenderPropBlock)(id view, id json); +typedef void (^HippyPropBlock)(id view, id json); @interface NativeRenderComponentProp : NSObject { } @property (nonatomic, copy, readonly) NSString *type; -@property (nonatomic, copy) NativeRenderPropBlock propBlock; +@property (nonatomic, copy) HippyPropBlock propBlock; @end @@ -49,31 +49,31 @@ - (instancetype)initWithType:(NSString *)type { @end -@interface NativeRenderComponentData () { - id _defaultView; // Only needed for NATIVE_RENDER_CUSTOM_VIEW_PROPERTY - NSMutableDictionary *_viewPropBlocks; - NSMutableDictionary *_renderObjectPropBlocks; +@interface HippyComponentData () { + id _defaultView; // Only needed for HIPPY_CUSTOM_VIEW_PROPERTY + NSMutableDictionary *_viewPropBlocks; + NSMutableDictionary *_shadowPropBlocks; NSMutableDictionary *_eventNameMap; BOOL _implementsUIBlockToAmendWithRenderObjectRegistry; - __weak NativeRenderViewManager *_manager; + __weak HippyViewManager *_manager; NSDictionary *_methodsByName; } @end -@implementation NativeRenderComponentData +@implementation HippyComponentData -//NativeRenderViewManager is base class of all ViewManager class -//we use a variable to cache NativeRenderViewManager's event name map +//HippyViewManager is base class of all ViewManager class +//we use a variable to cache HippyViewManager's event name map static NSDictionary *gBaseViewManagerDic = nil; -- (instancetype)initWithViewManager:(NativeRenderViewManager *)viewManager viewName:(NSString *)viewName { +- (instancetype)initWithViewManager:(HippyViewManager *)viewManager viewName:(NSString *)viewName { self = [super init]; if (self) { _managerClass = [viewManager class]; _manager = viewManager; _viewPropBlocks = [NSMutableDictionary new]; - _renderObjectPropBlocks = [NSMutableDictionary new]; + _shadowPropBlocks = [NSMutableDictionary new]; NSString *name = viewName; if (name.length == 0) { name = NSStringFromClass(_managerClass); @@ -86,10 +86,10 @@ - (instancetype)initWithViewManager:(NativeRenderViewManager *)viewManager viewN _implementsUIBlockToAmendWithRenderObjectRegistry = NO; Class cls = _managerClass; - while (cls != [NativeRenderViewManager class]) { + while (cls != [HippyViewManager class]) { _implementsUIBlockToAmendWithRenderObjectRegistry = _implementsUIBlockToAmendWithRenderObjectRegistry - || HPClassOverridesInstanceMethod(cls, @selector(uiBlockToAmendWithRenderObjectRegistry:)); + || HippyClassOverridesInstanceMethod(cls, @selector(uiBlockToAmendWithShadowViewRegistry:)); cls = [cls superclass]; } } @@ -97,9 +97,9 @@ - (instancetype)initWithViewManager:(NativeRenderViewManager *)viewManager viewN } - (UIView *)createViewWithTag:(NSNumber *)tag { - NSAssert(HPIsMainQueue(), @"This function must be called on the main thread"); + NSAssert(HippyIsMainQueue(), @"This function must be called on the main thread"); UIView *view = [self.manager view]; - view.componentTag = tag; + view.hippyTag = tag; view.multipleTouchEnabled = YES; view.userInteractionEnabled = YES; // required for touch handling view.layer.allowsGroupOpacity = YES; // required for touch handling @@ -107,10 +107,10 @@ - (UIView *)createViewWithTag:(NSNumber *)tag { } - (UIView *)createViewWithTag:(NSNumber *)tag initProps:(NSDictionary *)props { - NSAssert(HPIsMainQueue(), @"This function must be called on the main thread"); + NSAssert(HippyIsMainQueue(), @"This function must be called on the main thread"); self.manager.props = props; UIView *view = [self.manager view]; - view.componentTag = tag; + view.hippyTag = tag; view.rootTag = props[@"rootTag"]; view.multipleTouchEnabled = YES; view.userInteractionEnabled = YES; // required for touch handling @@ -118,27 +118,27 @@ - (UIView *)createViewWithTag:(NSNumber *)tag initProps:(NSDictionary *)props { return view; } -- (NativeRenderObjectView *)createRenderObjectViewWithTag:(NSNumber *)tag { - NativeRenderObjectView *renderObject = [self.manager nativeRenderObjectView]; - renderObject.componentTag = tag; +- (HippyShadowView *)createRenderObjectViewWithTag:(NSNumber *)tag { + HippyShadowView *renderObject = [self.manager hippyShadowView]; + renderObject.hippyTag = tag; renderObject.viewName = _name; return renderObject; } -- (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutableDictionary *)propBlocks { - BOOL renderObject = (propBlocks == _renderObjectPropBlocks); - NativeRenderPropBlock propBlock = propBlocks[name]; +- (HippyPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutableDictionary *)propBlocks { + BOOL isShadowView = (propBlocks == _shadowPropBlocks); + HippyPropBlock propBlock = propBlocks[name]; if (!propBlock) { - __weak NativeRenderComponentData *weakSelf = self; + __weak HippyComponentData *weakSelf = self; // Get type SEL type = NULL; NSString *keyPath = nil; - SEL selector = NSSelectorFromString([NSString stringWithFormat:@"propConfig%@_%@", renderObject ? @"RenderObject" : @"", name]); + SEL selector = NSSelectorFromString([NSString stringWithFormat:@"propConfig%@_%@", isShadowView ? @"Shadow" : @"", name]); NSAssert(selector, @"no propConfig setter selector found for property %@", name); if ([_managerClass respondsToSelector:selector]) { NSArray *typeAndKeyPath = ((NSArray * (*)(id, SEL)) objc_msgSend)(_managerClass, selector); - type = HPConvertSelectorForType(typeAndKeyPath[0]); + type = HippyConvertSelectorForType(typeAndKeyPath[0]); keyPath = typeAndKeyPath.count > 1 ? typeAndKeyPath[1] : nil; } else { propBlock = ^(__unused id view, __unused id json) { @@ -151,20 +151,20 @@ - (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutabl if ([keyPath isEqualToString:@"__custom__"]) { // Get custom setter. There is no default view in the shadow case, so the selector is different. NSString *selectorString; - if (!renderObject) { - selectorString = [NSString stringWithFormat:@"set_%@:for%@View:withDefaultView:", name, renderObject ? @"Render" : @""]; + if (!isShadowView) { + selectorString = [NSString stringWithFormat:@"set_%@:for%@View:withDefaultView:", name, isShadowView ? @"Shadow" : @""]; } else { - selectorString = [NSString stringWithFormat:@"set_%@:forRenderObject:", name]; + selectorString = [NSString stringWithFormat:@"set_%@:forShadowView:", name]; } SEL customSetter = NSSelectorFromString(selectorString); NSAssert(customSetter, @"no __custom__ setter selector found for property %@", name); - propBlock = ^(id view, id json) { - NativeRenderComponentData *strongSelf = weakSelf; + propBlock = ^(id view, id json) { + HippyComponentData *strongSelf = weakSelf; if (!strongSelf) { return; } - json = HPNilIfNull(json); - if (!renderObject) { + json = HippyNilIfNull(json); + if (!isShadowView) { if (!json && !strongSelf->_defaultView) { // Only create default view if json is null strongSelf->_defaultView = [strongSelf createViewWithTag:nil]; @@ -193,19 +193,19 @@ - (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutabl // Build setter block void (^setterBlock)(id target, id json) = nil; - if (type == NSSelectorFromString(@"NativeRenderDirectEventBlock:")) { + if (type == NSSelectorFromString(@"HippyDirectEventBlock:")) { //TODO //The component event response logic no longer executes this code } else { // Ordinary property handlers - NSMethodSignature *typeSignature = [[HPConvert class] methodSignatureForSelector:type]; + NSMethodSignature *typeSignature = [[HippyConvert class] methodSignatureForSelector:type]; if (!typeSignature) { - HPLogError(@"No +[HPConvert %@] function found.", NSStringFromSelector(type)); - return ^(__unused id view, __unused id json) { + HippyLogError(@"No +[HippyConvert %@] function found.", NSStringFromSelector(type)); + return ^(__unused id view, __unused id json) { }; } switch (typeSignature.methodReturnType[0]) { -#define NATIVE_RENDER_CASE(_value, _type) \ +#define HIPPY_CASE(_value, _type) \ case _value: { \ __block BOOL setDefaultValue = NO; \ __block _type defaultValue; \ @@ -221,7 +221,7 @@ - (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutabl setDefaultValue = YES; \ } \ if ([target respondsToSelector:setter]) { \ - set(target, setter, convert([HPConvert class], type, json)); \ + set(target, setter, convert([HippyConvert class], type, json)); \ } \ } else if (setDefaultValue) { \ if ([target respondsToSelector:setter]) { \ @@ -231,39 +231,39 @@ - (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutabl }; \ break; \ } - - NATIVE_RENDER_CASE(_C_SEL, SEL) - NATIVE_RENDER_CASE(_C_CHARPTR, const char *) - NATIVE_RENDER_CASE(_C_CHR, char) - NATIVE_RENDER_CASE(_C_UCHR, unsigned char) - NATIVE_RENDER_CASE(_C_SHT, short) - NATIVE_RENDER_CASE(_C_USHT, unsigned short) - NATIVE_RENDER_CASE(_C_INT, int) - NATIVE_RENDER_CASE(_C_UINT, unsigned int) - NATIVE_RENDER_CASE(_C_LNG, long) - NATIVE_RENDER_CASE(_C_ULNG, unsigned long) - NATIVE_RENDER_CASE(_C_LNG_LNG, long long) - NATIVE_RENDER_CASE(_C_ULNG_LNG, unsigned long long) - NATIVE_RENDER_CASE(_C_FLT, float) - NATIVE_RENDER_CASE(_C_DBL, double) - NATIVE_RENDER_CASE(_C_BOOL, BOOL) - NATIVE_RENDER_CASE(_C_PTR, void *) - NATIVE_RENDER_CASE(_C_ID, id) - + + HIPPY_CASE(_C_SEL, SEL) + HIPPY_CASE(_C_CHARPTR, const char *) + HIPPY_CASE(_C_CHR, char) + HIPPY_CASE(_C_UCHR, unsigned char) + HIPPY_CASE(_C_SHT, short) + HIPPY_CASE(_C_USHT, unsigned short) + HIPPY_CASE(_C_INT, int) + HIPPY_CASE(_C_UINT, unsigned int) + HIPPY_CASE(_C_LNG, long) + HIPPY_CASE(_C_ULNG, unsigned long) + HIPPY_CASE(_C_LNG_LNG, long long) + HIPPY_CASE(_C_ULNG_LNG, unsigned long long) + HIPPY_CASE(_C_FLT, float) + HIPPY_CASE(_C_DBL, double) + HIPPY_CASE(_C_BOOL, BOOL) + HIPPY_CASE(_C_PTR, void *) + HIPPY_CASE(_C_ID, id) + case _C_STRUCT_B: default: { NSInvocation *typeInvocation = [NSInvocation invocationWithMethodSignature:typeSignature]; typeInvocation.selector = type; - typeInvocation.target = [HPConvert class]; - + typeInvocation.target = [HippyConvert class]; + __block NSInvocation *targetInvocation = nil; __block NSMutableData *defaultValue = nil; - + setterBlock = ^(id target, id json) { if (!target) { return; } - + // Get default value if (!defaultValue) { if (!json) { @@ -284,7 +284,7 @@ - (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutabl [sourceInvocation getReturnValue:defaultValue.mutableBytes]; } } - + // Get value BOOL freeValueOnCompletion = NO; void *value = defaultValue.mutableBytes; @@ -295,7 +295,7 @@ - (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutabl [typeInvocation invoke]; [typeInvocation getReturnValue:value]; } - + // Set value if (!targetInvocation) { NSMethodSignature *signature = [target methodSignatureForSelector:setter]; @@ -314,7 +314,7 @@ - (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutabl } } } - + propBlock = ^(__unused id view, __unused id json) { // Follow keypath id target = view; @@ -323,54 +323,54 @@ - (NativeRenderPropBlock)propBlockForKey:(NSString *)name inDictionary:(NSMutabl } // Set property with json if (setterBlock) { - setterBlock(target, HPNilIfNull(json)); + setterBlock(target, HippyNilIfNull(json)); } }; } - - if (HP_DEBUG) { + + if (HIPPY_DEBUG) { // Provide more useful log feedback if there's an error - NativeRenderPropBlock unwrappedBlock = propBlock; - propBlock = ^(id view, id json) { + HippyPropBlock unwrappedBlock = propBlock; + propBlock = ^(id view, id json) { NSString *logPrefix = - [NSString stringWithFormat:@"Error setting property '%@' of %@ with tag #%@: ", name, weakSelf.name, view.componentTag]; - - HPPerformBlockWithLogPrefix(^{ + [NSString stringWithFormat:@"Error setting property '%@' of %@ with tag #%@: ", name, weakSelf.name, view.hippyTag]; + + HippyPerformBlockWithLogPrefix(^{ unwrappedBlock(view, json); }, logPrefix); }; } - + propBlocks[name] = [propBlock copy]; } return propBlock; } -- (void)setProps:(NSDictionary *)props forView:(id)view { +- (void)setProps:(NSDictionary *)props forView:(id)view { if (!view) { return; } - + [props enumerateKeysAndObjectsUsingBlock:^(NSString *key, id json, __unused BOOL *stop) { - NativeRenderPropBlock block = [self propBlockForKey:key inDictionary:self->_viewPropBlocks]; + HippyPropBlock block = [self propBlockForKey:key inDictionary:self->_viewPropBlocks]; block(view, json); }]; - + if ([view respondsToSelector:@selector(didSetProps:)]) { [view didSetProps:[props allKeys]]; } } -- (void)setProps:(NSDictionary *)props forRenderObjectView:(NativeRenderObjectView *)renderObject { +- (void)setProps:(NSDictionary *)props forShadowView:(HippyShadowView *)renderObject { if (!renderObject) { return; } - + [props enumerateKeysAndObjectsUsingBlock:^(NSString *key, id json, __unused BOOL *stop) { - NativeRenderPropBlock propBlock = [self propBlockForKey:key inDictionary:_renderObjectPropBlocks]; + HippyPropBlock propBlock = [self propBlockForKey:key inDictionary:_shadowPropBlocks]; propBlock(renderObject, json); }]; - + if ([renderObject respondsToSelector:@selector(didSetProps:)]) { [renderObject didSetProps:[props allKeys]]; } @@ -384,10 +384,10 @@ - (void)setProps:(NSDictionary *)props forRenderObjectView:(Nati static dispatch_once_t onceToken; static Class viewManagerMetaClass = nil; dispatch_once(&onceToken, ^{ - viewManagerMetaClass = object_getClass([NativeRenderViewManager class]); + viewManagerMetaClass = object_getClass([HippyViewManager class]); }); while ([metaClass isSubclassOfClass:viewManagerMetaClass]) { - //if metaclass is NativeRenderViewManager's meta class,we try to get event name map from cache if exists + //if metaclass is HippyViewManager's meta class,we try to get event name map from cache if exists if (metaClass == viewManagerMetaClass && gBaseViewManagerDic) { [_eventNameMap addEntriesFromDictionary:gBaseViewManagerDic]; } @@ -402,7 +402,7 @@ - (void)setProps:(NSDictionary *)props forRenderObjectView:(Nati if (nameRange.length) { NSString *name = [methodName substringFromIndex:nameRange.location + 1]; NSString *type = ((NSArray * (*)(id, SEL)) objc_msgSend)(_managerClass, selector)[0]; - if ([type isEqualToString:@"NativeRenderDirectEventBlock"]) { + if ([type isEqualToString:@"HippyDirectEventBlock"]) { //remove 'on' prefix if exists NSString *nameNoOn = name; if ([nameNoOn hasPrefix:@"on"]) { @@ -416,7 +416,7 @@ - (void)setProps:(NSDictionary *)props forRenderObjectView:(Nati } free(methods); if (metaClass == viewManagerMetaClass) { - //if metaclass is NativeRenderViewManager's meta class,we try to save event name map from cache + //if metaclass is HippyViewManager's meta class,we try to save event name map from cache gBaseViewManagerDic = [_eventNameMap copy]; } } @@ -443,7 +443,7 @@ - (void)methods { for (unsigned int i = 0; i < methodCount; i++) { Method method = methods[i]; SEL selector = method_getName(method); - if ([NSStringFromSelector(selector) hasPrefix:@"__render_export__"]) { + if ([NSStringFromSelector(selector) hasPrefix:@"__hippy_export__"]) { IMP imp = method_getImplementation(method); NSArray *entries = ((NSArray * (*)(id, SEL)) imp)(_managerClass, selector); NSString *JSMethodName = [self JSMethodNameFromEntries:entries]; @@ -476,11 +476,11 @@ - (NSString *)JSMethodNameFromEntries:(NSArray *)entries { } - (NSString *)selectorStringFromSignature:(NSString *)signature { -// signature = @"createView:(nonnull NSNumber *)componentTag viewName:(NSString *)viewName rootTag:(nonnull NSNumber *)rootTag tagName:(NSString *)tagName props:(NSDictionary *)props"; -// signature = @"startBatch"; -// signature = @"endBatch:"; -// signature = @"startBatch:::"; -// signature = @"startBatch:_::"; + // signature = @"createView:(nonnull NSNumber *)hippyTag viewName:(NSString *)viewName rootTag:(nonnull NSNumber *)rootTag tagName:(NSString *)tagName props:(NSDictionary *)props"; + // signature = @"startBatch"; + // signature = @"endBatch:"; + // signature = @"startBatch:::"; + // signature = @"startBatch:_::"; NSArray *colonsComponent = [signature componentsSeparatedByString:@":"]; NSUInteger colonsComponentCount = [colonsComponent count]; NSMutableString *selString = [NSMutableString stringWithCapacity:64]; @@ -509,9 +509,9 @@ - (NSString *)selectorStringFromSignature:(NSString *)signature { return [selString copy]; } -- (NativeRenderRenderUIBlock)uiBlockToAmendWithRenderObjectViewRegistry:(NSDictionary *)registry { +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(NSDictionary *)registry { if (_implementsUIBlockToAmendWithRenderObjectRegistry) { - return [[self manager] uiBlockToAmendWithRenderObjectRegistry:registry]; + return [[self manager] uiBlockToAmendWithShadowViewRegistry:registry]; } return nil; } diff --git a/renderer/native/ios/renderer/NativeRenderComponentMap.h b/renderer/native/ios/renderer/HippyComponentMap.h similarity index 68% rename from renderer/native/ios/renderer/NativeRenderComponentMap.h rename to renderer/native/ios/renderer/HippyComponentMap.h index b36995ed93f..9db9b21c5bd 100644 --- a/renderer/native/ios/renderer/NativeRenderComponentMap.h +++ b/renderer/native/ios/renderer/HippyComponentMap.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,7 +22,7 @@ #import -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" #include @@ -34,11 +34,11 @@ class RootNode; NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderComponentMap : NSObject +@interface HippyComponentMap : NSObject @property(nonatomic, assign) BOOL requireInMainThread; -- (void)addRootComponent:(id)component +- (void)addRootComponent:(id)component rootNode:(std::weak_ptr)rootNode forTag:(NSNumber *)tag; @@ -46,23 +46,23 @@ NS_ASSUME_NONNULL_BEGIN - (BOOL)containRootComponentWithTag:(NSNumber *)tag; -- (NSArray> *)rootComponents; +- (NSArray> *)rootComponents; -- (__kindof id)rootComponentForTag:(NSNumber *)tag; +- (__kindof id)rootComponentForTag:(NSNumber *)tag; - (std::weak_ptr)rootNodeForTag:(NSNumber *)tag; -- (void)addComponent:(__kindof id)component +- (void)addComponent:(__kindof id)component forRootTag:(NSNumber *)tag; -- (void)removeComponent:(__kindof id)component +- (void)removeComponent:(__kindof id)component forRootTag:(NSNumber *)tag; - (void)removeComponentByComponentTag:(NSNumber *)componentTag onRootTag:(NSNumber *)rootTag; -- (NSMutableDictionary> *)componentsForRootTag:(NSNumber *)tag; +- (NSMutableDictionary> *)componentsForRootTag:(NSNumber *)tag; -- (__kindof id)componentForTag:(NSNumber *)componentTag +- (__kindof id)componentForTag:(NSNumber *)componentTag onRootTag:(NSNumber *)tag; @end diff --git a/renderer/native/ios/renderer/NativeRenderComponentMap.mm b/renderer/native/ios/renderer/HippyComponentMap.mm similarity index 74% rename from renderer/native/ios/renderer/NativeRenderComponentMap.mm rename to renderer/native/ios/renderer/HippyComponentMap.mm index ff6c197284d..c3b70e2c6d6 100644 --- a/renderer/native/ios/renderer/NativeRenderComponentMap.mm +++ b/renderer/native/ios/renderer/HippyComponentMap.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,27 +20,27 @@ * limitations under the License. */ -#import "NativeRenderComponentMap.h" +#import "HippyComponentMap.h" #include "dom/root_node.h" using RootNode = hippy::RootNode; -@interface NativeRenderComponentMap () { - NSMutableDictionary> *> *_componentsMap; - NSMutableDictionary> *_rootComponentsMap; +@interface HippyComponentMap () { + NSMapTable> *_rootComponentsMap; + NSMutableDictionary> *> *_componentsMap; std::unordered_map> _rootNodesMap; } @end -@implementation NativeRenderComponentMap +@implementation HippyComponentMap - (instancetype)init { self = [super init]; if (self) { - _componentsMap = [NSMutableDictionary dictionaryWithCapacity:256]; - _rootComponentsMap = [NSMutableDictionary dictionaryWithCapacity:8]; + _rootComponentsMap = [NSMapTable strongToWeakObjectsMapTable]; + _componentsMap = [NSMutableDictionary dictionary]; _rootNodesMap.reserve(8); } return self; @@ -50,13 +50,13 @@ - (BOOL)threadCheck { return _requireInMainThread ? [NSThread isMainThread] : YES; } -- (void)addRootComponent:(id)component +- (void)addRootComponent:(id)component rootNode:(std::weak_ptr)rootNode forTag:(NSNumber *)tag { NSAssert(component && tag, @"component &&tag must not be null in method %@", NSStringFromSelector(_cmd)); NSAssert([self threadCheck], @"%@ method needs run in main thread", NSStringFromSelector(_cmd)); if (component && tag && ![_componentsMap objectForKey:tag]) { - NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:256]; + NSMutableDictionary *dic = [NSMutableDictionary dictionary]; [dic setObject:component forKey:tag]; [_componentsMap setObject:dic forKey:tag]; [_rootComponentsMap setObject:component forKey:tag]; @@ -78,11 +78,11 @@ - (BOOL)containRootComponentWithTag:(NSNumber *)tag { return nil != rootComponent; } -- (NSArray> *)rootComponents { - return [_rootComponentsMap allValues]; +- (NSArray> *)rootComponents { + return [[_rootComponentsMap objectEnumerator] allObjects]; } -- (__kindof id)rootComponentForTag:(NSNumber *)tag { +- (__kindof id)rootComponentForTag:(NSNumber *)tag { NSAssert(tag, @"tag must not be null in method %@", NSStringFromSelector(_cmd)); NSAssert([self threadCheck], @"%@ method needs run in main thread", NSStringFromSelector(_cmd)); return [_rootComponentsMap objectForKey:tag]; @@ -92,23 +92,23 @@ - (BOOL)containRootComponentWithTag:(NSNumber *)tag { return _rootNodesMap[[tag intValue]]; } -- (void)addComponent:(__kindof id)component forRootTag:(NSNumber *)tag { +- (void)addComponent:(__kindof id)component forRootTag:(NSNumber *)tag { NSAssert(tag, @"component and tag must not be null in method %@", NSStringFromSelector(_cmd)); - NSAssert([component componentTag], @"component's tag must not be null in %@", NSStringFromSelector(_cmd)); + NSAssert([component hippyTag], @"component's tag must not be null in %@", NSStringFromSelector(_cmd)); NSAssert([self threadCheck], @"%@ method needs run in main thread", NSStringFromSelector(_cmd)); if (component && tag) { id map = [_componentsMap objectForKey:tag]; - [map setObject:component forKey:[component componentTag]]; + [map setObject:component forKey:[component hippyTag]]; } } -- (void)removeComponent:(__kindof id)component forRootTag:(NSNumber *)tag { +- (void)removeComponent:(__kindof id)component forRootTag:(NSNumber *)tag { NSAssert(tag, @"component and tag must not be null in method %@", NSStringFromSelector(_cmd)); - NSAssert([component componentTag], @"component's tag must not be null in %@", NSStringFromSelector(_cmd)); + NSAssert([component hippyTag], @"component's tag must not be null in %@", NSStringFromSelector(_cmd)); NSAssert([self threadCheck], @"%@ method needs run in main thread", NSStringFromSelector(_cmd)); if (component && tag) { id map = [_componentsMap objectForKey:tag]; - [map removeObjectForKey:[component componentTag]]; + [map removeObjectForKey:[component hippyTag]]; } } @@ -122,7 +122,7 @@ - (void)removeComponentByComponentTag:(NSNumber *)componentTag onRootTag:(NSNumb } } -- (NSMutableDictionary> *)componentsForRootTag:(NSNumber *)tag { +- (NSMutableDictionary> *)componentsForRootTag:(NSNumber *)tag { NSAssert(tag, @"tag must not be null in method %@", NSStringFromSelector(_cmd)); NSAssert([self threadCheck], @"%@ method needs run in main thread", NSStringFromSelector(_cmd)); if (tag) { @@ -132,7 +132,7 @@ - (void)removeComponentByComponentTag:(NSNumber *)componentTag onRootTag:(NSNumb return nil; } -- (__kindof id)componentForTag:(NSNumber *)componentTag +- (__kindof id)componentForTag:(NSNumber *)componentTag onRootTag:(NSNumber *)tag { NSAssert(componentTag && tag, @"componentTag && tag must not be null in method %@", NSStringFromSelector(_cmd)); NSAssert([self threadCheck], @"%@ method needs run in main thread", NSStringFromSelector(_cmd)); @@ -145,13 +145,13 @@ - (void)removeComponentByComponentTag:(NSNumber *)componentTag onRootTag:(NSNumb - (NSString *)description { NSMutableString *description = [NSMutableString stringWithCapacity:256]; - [description appendFormat:@"> *rootComponentsArray = [self rootComponents]; + [description appendFormat:@"> *rootComponentsArray = [self rootComponents]; [description appendFormat:@"%ld root component(s): ", [rootComponentsArray count]]; long index = 1; - for (id object in rootComponentsArray) { + for (id object in rootComponentsArray) { NSMutableString *objectDescription = [NSMutableString stringWithCapacity:64]; - NSNumber *componentTag = [object componentTag]; + NSNumber *componentTag = [object hippyTag]; NSUInteger count = [[self componentsForRootTag:componentTag] count]; [objectDescription appendFormat:@"%ld-;", index++, object, componentTag, count]; [description appendString:objectDescription]; diff --git a/renderer/native/ios/renderer/NativeRenderFont.h b/renderer/native/ios/renderer/HippyFont.h similarity index 92% rename from renderer/native/ios/renderer/NativeRenderFont.h rename to renderer/native/ios/renderer/HippyFont.h index 45bdacb99e9..1950555f33a 100644 --- a/renderer/native/ios/renderer/NativeRenderFont.h +++ b/renderer/native/ios/renderer/HippyFont.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,9 +22,9 @@ #import -#import "HPConvert.h" +#import "HippyConvert.h" -@interface NativeRenderFont : NSObject +@interface HippyFont : NSObject /** * Update a font with a given font-family, size, weight and style. @@ -46,7 +46,7 @@ @end -@interface HPConvert (NativeRenderFont) +@interface HippyConvert (NativeRenderFont) + (UIFont *)UIFont:(id)json; diff --git a/renderer/native/ios/renderer/NativeRenderFont.m b/renderer/native/ios/renderer/HippyFont.m similarity index 90% rename from renderer/native/ios/renderer/NativeRenderFont.m rename to renderer/native/ios/renderer/HippyFont.m index 75815c39438..b327884667f 100644 --- a/renderer/native/ios/renderer/NativeRenderFont.m +++ b/renderer/native/ios/renderer/HippyFont.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,15 +22,15 @@ #import -#import "NativeRenderFont.h" -#import "HPLog.h" +#import "HippyFont.h" +#import "HippyLog.h" #if !defined(__IPHONE_8_2) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_2 // These constants are defined in iPhone SDK 8.2, but the app cannot run on // iOS < 8.2 unless we redefine them here. If you target iOS 8.2 or above // as a base target, the standard constants will be used instead. -// These constants can only be removed when NativeRender Native drops iOS8 support. +// These constants can only be removed when Hippy Native drops iOS8 support. #define UIFontWeightUltraLight -0.8 #define UIFontWeightThin -0.6 @@ -117,14 +117,14 @@ static BOOL isCondensedFont(UIFont *font) { return font; } -@implementation HPConvert (NativeRenderFont) +@implementation HippyConvert (NativeRenderFont) + (UIFont *)UIFont:(id)json { json = [self NSDictionary:json]; - return [NativeRenderFont updateFont:nil withFamily:[HPConvert NSString:json[@"fontFamily"]] size:[HPConvert NSNumber:json[@"fontSize"]] - weight:[HPConvert NSString:json[@"fontWeight"]] - style:[HPConvert NSString:json[@"fontStyle"]] - variant:[HPConvert NSStringArray:json[@"fontVariant"]] + return [HippyFont updateFont:nil withFamily:[HippyConvert NSString:json[@"fontFamily"]] size:[HippyConvert NSNumber:json[@"fontSize"]] + weight:[HippyConvert NSString:json[@"fontWeight"]] + style:[HippyConvert NSString:json[@"fontStyle"]] + variant:[HippyConvert NSStringArray:json[@"fontVariant"]] scaleMultiplier:1]; } @@ -180,8 +180,8 @@ + (NativeRenderFontVariantDescriptor *)NativeRenderFontVariantDescriptor:(id)jso }; }); NativeRenderFontVariantDescriptor *value = mapping[json]; - if (HP_DEBUG && !value && [json description].length > 0) { - HPLogError(@"Invalid NativeRenderFontVariantDescriptor '%@'. should be one of: %@", json, + if (HIPPY_DEBUG && !value && [json description].length > 0) { + HippyLogError(@"Invalid NativeRenderFontVariantDescriptor '%@'. should be one of: %@", json, [[mapping allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]); } return value; @@ -191,10 +191,10 @@ + (NativeRenderFontVariantDescriptor *)NativeRenderFontVariantDescriptor:(id)jso @end -@implementation NativeRenderFont +@implementation HippyFont + (void)initialize { - if (self == [NativeRenderFont class]) { + if (self == [HippyFont class]) { fontCache = [NSCache new]; } } @@ -231,13 +231,13 @@ + (UIFont *)updateFont:(UIFont *)font } // Get font attributes - fontSize = [HPConvert CGFloat:size] ?: fontSize; + fontSize = [HippyConvert CGFloat:size] ?: fontSize; if (scaleMultiplier > 0.0 && scaleMultiplier != 1.0) { fontSize = round(fontSize * scaleMultiplier); } - familyName = [HPConvert NSString:family] ?: familyName; - isItalic = style ? [HPConvert NativeRenderFontStyle:style] : isItalic; - fontWeight = weight ? [HPConvert NativeRenderFontWeight:weight] : fontWeight; + familyName = [HippyConvert NSString:family] ?: familyName; + isItalic = style ? [HippyConvert NativeRenderFontStyle:style] : isItalic; + fontWeight = weight ? [HippyConvert NativeRenderFontWeight:weight] : fontWeight; BOOL didFindFont = NO; @@ -290,7 +290,7 @@ + (UIFont *)updateFont:(UIFont *)font } else { // Not a valid font or family - HPLogError(@"Unrecognized font family '%@'", familyName); + HippyLogError(@"Unrecognized font family '%@'", familyName); if (@available(iOS 8.2, *)) { font = [UIFont systemFontOfSize:fontSize weight:fontWeight]; } else if (fontWeight > UIFontWeightRegular) { @@ -317,7 +317,7 @@ + (UIFont *)updateFont:(UIFont *)font } // Apply font variants to font object if (variant) { - NSArray *fontFeatures = [HPConvert NativeRenderFontVariantDescriptorArray:variant]; + NSArray *fontFeatures = [HippyConvert NativeRenderFontVariantDescriptorArray:variant]; UIFontDescriptor *fontDescriptor = [font.fontDescriptor fontDescriptorByAddingAttributes:@{ UIFontDescriptorFeatureSettingsAttribute: fontFeatures }]; font = [UIFont fontWithDescriptor:fontDescriptor size:fontSize]; diff --git a/renderer/native/ios/renderer/HippyRootView.h b/renderer/native/ios/renderer/HippyRootView.h new file mode 100644 index 00000000000..b7ad9746ca3 --- /dev/null +++ b/renderer/native/ios/renderer/HippyRootView.h @@ -0,0 +1,128 @@ +/*! + * iOS SDK + * + * Tencent is pleased to support the open source community by making + * Hippy available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import +#import "HippyRootViewDelegate.h" + +@class HippyBridge; + +/** + * This enum is used to define size flexibility type of the root view. + * If a dimension is flexible, the view will recalculate that dimension + * so the content fits. Recalculations are performed when the root's frame, + * size flexibility mode or content size changes. After a recalculation, + * rootViewDidChangeIntrinsicSize method of the HippyRootViewDelegate will be called. + */ +typedef NS_ENUM(NSInteger, HippyRootViewSizeFlexibility) { + HippyRootViewSizeFlexibilityNone = 0, + HippyRootViewSizeFlexibilityWidth, + HippyRootViewSizeFlexibilityHeight, + HippyRootViewSizeFlexibilityWidthAndHeight, +}; + + +/// This notification is sent when the first subviews are added to the root view +/// after the application has loaded. This is used to hide the `loadingView`, and +/// is a good indicator that the application is ready to use. +extern NSString *const HippyContentDidAppearNotification; + +/// Business bundle loading completion notification +/// This notification is for compatibility with hippy2 and is not recommended for further use +extern NSString *const HippySecondaryBundleDidLoadNotification DEPRECATED_MSG_ATTRIBUTE("Use HippyRootView's delegate"); + + + +/// Native view used to host Hippy-managed views within the app. +/// Can be used just like any ordinary UIView. +/// You can have multiple HippyRootViews on screen at once, +/// all controlled by the same JavaScript application. +@interface HippyRootView : UIView + +/// The delegate of hippyRootView. +@property (nonatomic, weak) id delegate; + +/// The name of the JavaScript module to execute within the +/// specified scriptURL (required). Setting this will not have +/// any immediate effect, but it must be done prior to loading the script. +@property (nonatomic, copy, readonly) NSString *moduleName; + +/// The bridge used by the root view. Bridges can be shared between multiple +/// root views, so you can use this property to initialize another HippyRootView. +@property (nonatomic, strong, readonly) HippyBridge *bridge; + +/// The properties to apply to the view. Use this property to update +/// application properties and rerender the view. Initialized with +/// initialProperties argument of the initializer. +/// Set this property only on the main thread. +@property (nonatomic, copy, readwrite) NSDictionary *appProperties; + +/// The backing view controller of the root view. +@property (nonatomic, weak) UIViewController *hippyViewController; + + +/// Create HippyRootView instance +/// +/// @param bridge the hippyBridge instance +/// @param moduleName module name +/// @param initialProperties application properties, see appProperties property. +/// @param delegate HippyRootViewDelegate +- (instancetype)initWithBridge:(HippyBridge *)bridge + moduleName:(NSString *)moduleName + initialProperties:(NSDictionary *)initialProperties + delegate:(id)delegate; + +/// Create HippyRootView instance +/// & Load the business BundleURL +/// & Run application +/// +/// @param bridge the hippyBridge instance +/// @param businessURL the bundleURL to load +/// @param moduleName module name +/// @param initialProperties application properties, see appProperties property. +/// @param delegate HippyRootViewDelegate +- (instancetype)initWithBridge:(HippyBridge *)bridge + businessURL:(NSURL *)businessURL + moduleName:(NSString *)moduleName + initialProperties:(NSDictionary *)initialProperties + delegate:(id)delegate; + + +/// Run Hippy! +/// This is the Hippy program entry. +/// +/// Note: If init with businessURL, not need to call this method again. +- (void)runHippyApplication; + + +#pragma mark - + +/// This method should be called when the host controller's view's size is changed +/// (i.e. for the root view controller when its window rotates or is resized). +/// +/// Note that `useViewWillTransitionMethodToMonitorOrientation` flag must be set when init bridge, +/// otherwise calling this function takes no effect. +/// +/// - Parameter size: the new size +- (void)onHostControllerTransitionedToSize:(CGSize)size; + + +@end diff --git a/renderer/native/ios/renderer/HippyRootView.mm b/renderer/native/ios/renderer/HippyRootView.mm new file mode 100644 index 00000000000..f94a931d259 --- /dev/null +++ b/renderer/native/ios/renderer/HippyRootView.mm @@ -0,0 +1,344 @@ +/*! + * iOS SDK + * + * Tencent is pleased to support the open source community by making + * Hippy available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "HippyRootView.h" +#import "HippyAsserts.h" +#import "HippyView.h" +#import "UIView+Hippy.h" +#import "NativeRenderDefines.h" +#import "HippyInvalidating.h" +#import "HippyBridge.h" +#import "HippyDeviceBaseInfo.h" +#include + + +NSString *const HippyContentDidAppearNotification = @"HippyContentDidAppearNotification"; +NSString *const HippySecondaryBundleDidLoadNotification = @"HippySecondaryBundleDidLoadNotification"; + +NSNumber *AllocRootViewTag(void) { + static NSString * const token = @"allocateRootTag"; + @synchronized (token) { + static NSUInteger rootTag = 0; + return @(rootTag += 10); + } +} + + +@interface HippyRootContentView : HippyView + +@property (nonatomic, readonly) BOOL contentHasAppeared; +//@property (nonatomic, strong) HippyTouchHandler *touchHandler; +@property (nonatomic, assign) int64_t startTimpStamp; + +- (instancetype)initWithFrame:(CGRect)frame + bridge:(HippyBridge *)bridge + hippyTag:(NSNumber *)hippyTag + sizeFlexiblity:(HippyRootViewSizeFlexibility)sizeFlexibility NS_DESIGNATED_INITIALIZER; + +@end + + +@interface HippyRootView () { + BOOL _contentHasAppeared; +} + +@property (nonatomic, strong) HippyRootContentView *contentView; +@property (nonatomic, strong) NSDictionary *shareOptions; + +@end + + +@implementation HippyRootView + +HIPPY_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +HIPPY_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (NSCoder *)aDecoder) + +- (instancetype)initWithBridge:(HippyBridge *)bridge + moduleName:(NSString *)moduleName + initialProperties:(NSDictionary *)initialProperties + delegate:(id)delegate { + //HippyAssertMainQueue(); + HippyAssert(bridge, @"A bridge instance is required to create an HippyRootView"); + HippyAssert(moduleName, @"A moduleName is required to create an HippyRootView"); + + if ((self = [super initWithFrame:CGRectZero])) { + self.backgroundColor = [UIColor clearColor]; + + _bridge = bridge; + if (!_bridge.moduleName) { + _bridge.moduleName = moduleName; + } + _moduleName = moduleName; + _appProperties = [initialProperties copy]; + _delegate = delegate; + self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + + // [[NSNotificationCenter defaultCenter] addObserver:self + // selector:@selector(javaScriptDidLoad:) + // name:HippyJavaScriptDidLoadNotification + // object:_bridge]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(javaScriptDidFailToLoad:) + name:HippyJavaScriptDidFailToLoadNotification + object:nil]; + + // [_bridge.performanceLogger markStartForTag:HippyPLTTI]; + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyRootView Init %p", self); + } + return self; +} + +- (instancetype)initWithBridge:(HippyBridge *)bridge + businessURL:(NSURL *)businessURL + moduleName:(NSString *)moduleName + initialProperties:(NSDictionary *)initialProperties + delegate:(id)delegate { + NSParameterAssert(businessURL); + + if (self = [self initWithBridge:bridge + moduleName:moduleName + initialProperties:initialProperties + delegate:delegate]) { + if (!bridge.isValid) { + if (delegate && [delegate respondsToSelector:@selector(rootView:didLoadFinish:)]) { + [delegate rootView:self didLoadFinish:NO]; + } + } else { + __weak __typeof(self)weakSelf = self; + [bridge loadBundleURL:businessURL completion:^(NSURL * _Nullable url, NSError * _Nullable error) { + dispatch_async(dispatch_get_main_queue(), ^{ + __strong __typeof(weakSelf)strongSelf = weakSelf; + // 抛出业务包(BusinessBundle aka SecondaryBundle)加载完成通知, for hippy2兼容 + NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithDictionary:@{ @"url": url, + @"bridge": strongSelf.bridge }]; + if (error) [userInfo setObject:error forKey:@"error"]; + [[NSNotificationCenter defaultCenter] postNotificationName:HippySecondaryBundleDidLoadNotification + object:strongSelf.bridge userInfo:userInfo]; + + if ([delegate respondsToSelector:@selector(rootView:didLoadFinish:)]) { + [delegate rootView:strongSelf didLoadFinish:(error == nil)]; + } + }); + if (!error) { + [weakSelf runHippyApplication]; + } + }]; + } + } + return self; +} + +- (void)dealloc { + [_contentView invalidate]; + if ([_delegate respondsToSelector:@selector(rootViewWillBePurged:)]) { + [_delegate rootViewWillBePurged:self]; + } + [_bridge unloadInstanceForRootView:self.hippyTag]; + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyRootView dealloc %p", self); +} + +- (void)contentViewInvalidated { + [_contentView removeFromSuperview]; + _contentView = nil; +} + + +- (void)runHippyApplication { + // [_bridge.performanceLogger markStartForTag:HippyPLRunApplication]; + + __weak __typeof(self)weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + __strong __typeof(weakSelf)strongSelf = weakSelf; + + [strongSelf.contentView removeFromSuperview]; + // todo: ContentRootView sizeFlexibility feature + HippyRootContentView *contentView = [[HippyRootContentView alloc] initWithFrame:strongSelf.bounds + bridge:strongSelf.bridge + hippyTag:strongSelf.hippyTag + sizeFlexiblity:HippyRootViewSizeFlexibilityWidthAndHeight]; + + // 注册RootView + [strongSelf.bridge setRootView:contentView]; + [strongSelf.bridge loadInstanceForRootView:strongSelf.hippyTag withProperties:strongSelf.appProperties]; + strongSelf.contentView = contentView; + [strongSelf insertSubview:contentView atIndex:0]; + HippyLogInfo(@"[Hippy_OC_Log][Life_Circle],Running application %@ (%@)", strongSelf.moduleName, strongSelf.appProperties); + }); +} + +- (UIViewController *)hippyViewController { + return _hippyViewController ?: [super hippyViewController]; +} + +- (BOOL)canBecomeFirstResponder { + return YES; +} + +- (void)cancelTouches { + // [[_contentView touchHandler] cancelTouch]; +} + +- (NSNumber *)hippyTag { + HippyAssertMainQueue(); + if (!super.hippyTag) { + self.hippyTag = AllocRootViewTag(); + } + return super.hippyTag; +} + +- (void)bridgeDidReload { + HippyAssertMainQueue(); + // Clear the hippyTag so it can be re-assigned + self.hippyTag = nil; +} + + +#pragma mark - Notification Handlers + +- (void)javaScriptDidFailToLoad:(NSNotification *)notification { + HippyBridge *bridge = notification.userInfo[@"bridge"]; + NSError *error = notification.userInfo[@"error"]; + if (bridge == self.bridge && error) { + NSError *retError = HippyErrorFromErrorAndModuleName(error, self.bridge.moduleName); + HippyFatal(retError); + } +} + +#pragma mark - + +- (void)layoutSubviews { + [super layoutSubviews]; + _contentView.frame = self.bounds; +} + +- (void)setAppProperties:(NSDictionary *)appProperties { + HippyAssertMainQueue(); + + if ([_appProperties isEqualToDictionary:appProperties]) { + return; + } + + _appProperties = [appProperties copy]; + + if (_bridge.valid) { + [self runHippyApplication]; + } +} + + +#pragma mark - App UI State Related + +- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { + [super traitCollectionDidChange:previousTraitCollection]; + if (@available(iOS 12.0, *)) { + // on dark mode change + UIUserInterfaceStyle currentStyle = self.traitCollection.userInterfaceStyle; + if (currentStyle != previousTraitCollection.userInterfaceStyle) { + BOOL isNightMode = (UIUserInterfaceStyleDark == currentStyle); + if (self.bridge.isOSNightMode != isNightMode) { + [self.bridge setOSNightMode:isNightMode withRootViewTag:self.hippyTag]; + } + } + } +} + +static NSString *const HippyHostControllerSizeKeyNewSize = @"NewSize"; +- (void)onHostControllerTransitionedToSize:(CGSize)size { + [NSNotificationCenter.defaultCenter postNotificationName:HippyDimensionsShouldUpdateNotification + object:self + userInfo:@{HippyHostControllerSizeKeyNewSize : @(size)}]; +} + +@end + + + +#pragma mark - HippyRootContentView + +@implementation HippyRootContentView { + __weak HippyBridge *_bridge; + UIColor *_backgroundColor; +} + +- (instancetype)initWithFrame:(CGRect)frame + bridge:(HippyBridge *)bridge + hippyTag:(NSNumber *)hippyTag + sizeFlexiblity:(HippyRootViewSizeFlexibility)sizeFlexibility { + if ((self = [super initWithFrame:frame])) { + _bridge = bridge; + self.hippyTag = hippyTag; + + // FIXME: HippyTouchHandler + // _touchHandler = [[HippyTouchHandler alloc] initWithRootView:self bridge:bridge]; + // [self addGestureRecognizer:_touchHandler]; + + self.layer.backgroundColor = NULL; + _startTimpStamp = CACurrentMediaTime() * 1000; + } + return self; +} + +HIPPY_NOT_IMPLEMENTED(-(instancetype)initWithFrame : (CGRect)frame) +HIPPY_NOT_IMPLEMENTED(-(instancetype)initWithCoder : (nonnull NSCoder *)aDecoder) + + +// FIXME: check +//- (void)setFrame:(CGRect)frame { +// CGRect originFrame = self.frame; +// if (!CGRectEqualToRect(originFrame, frame)) { +// super.frame = frame; +// if (self.hippyTag && _bridge.isValid) { +// [_bridge.uiManager setFrame:frame fromOriginFrame:originFrame forView:self]; +// } +// } +//} + +#pragma mark - HippyComponent Method + +- (void)insertHippySubview:(UIView *)subview atIndex:(NSInteger)atIndex { + [super insertHippySubview:subview atIndex:atIndex]; + // [_bridge.performanceLogger markStopForTag:HippyPLTTI]; + + __weak __typeof(self)weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (strongSelf && !strongSelf->_contentHasAppeared) { + strongSelf->_contentHasAppeared = YES; + // int64_t cost = [strongSelf.bridge.performanceLogger durationForTag:HippyPLTTI]; + [[NSNotificationCenter defaultCenter] postNotificationName:HippyContentDidAppearNotification + object:self userInfo:@{ + // @"cost": @(cost) + }]; + } + }); +} + +- (void)invalidate { + if (self.userInteractionEnabled) { + self.userInteractionEnabled = NO; + [(HippyRootView *)self.superview contentViewInvalidated]; + } +} + + +@end diff --git a/renderer/native/ios/renderer/HippyRootViewDelegate.h b/renderer/native/ios/renderer/HippyRootViewDelegate.h new file mode 100644 index 00000000000..7dad3386221 --- /dev/null +++ b/renderer/native/ios/renderer/HippyRootViewDelegate.h @@ -0,0 +1,41 @@ +/*! + * iOS SDK + * + * Tencent is pleased to support the open source community by making + * Hippy available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@class HippyRootView; + +@protocol HippyRootViewDelegate + +@optional + +/** + * Called after finish load the bundle. + */ +- (void)rootView:(HippyRootView *)rootView didLoadFinish:(BOOL)success; + +/** + * Called when rootview dealloc. + */ +- (void)rootViewWillBePurged:(HippyRootView *)rootView; + +@end diff --git a/renderer/native/ios/renderer/NativeRenderImpl.h b/renderer/native/ios/renderer/HippyUIManager.h similarity index 77% rename from renderer/native/ios/renderer/NativeRenderImpl.h rename to renderer/native/ios/renderer/HippyUIManager.h index 1ec5331edd2..1fa540a5a14 100644 --- a/renderer/native/ios/renderer/NativeRenderImpl.h +++ b/renderer/native/ios/renderer/HippyUIManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,16 +21,16 @@ */ #import - -#import "HPInvalidating.h" +#import "HippyBridge.h" +#import "HippyInvalidating.h" #import "NativeRenderDefines.h" - +#import "HippyBridgeModule.h" #include #include #include -@class NativeRenderAnimationViewParams, NativeRenderObjectView, NativeRenderImpl,NativeRenderViewManager; -@class NativeRenderReusePool, NativeRenderComponentMap; +@class NativeRenderAnimationViewParams, HippyShadowView, HippyUIManager,HippyViewManager; +@class NativeRenderReusePool, HippyComponentMap; class VFSUriLoader; namespace hippy { @@ -51,12 +51,12 @@ class HippyValue; } } -@protocol HPImageProviderProtocol; +@protocol HippyImageProviderProtocol; /** * The NativeRenderUIManager is the module responsible for updating the view hierarchy. */ -@interface NativeRenderImpl : NSObject +@interface HippyUIManager : NSObject - (instancetype)init NS_UNAVAILABLE; @@ -64,30 +64,28 @@ class HippyValue; @property(nonatomic, assign) BOOL uiCreationLazilyEnabled; -@property(nonatomic, assign) std::weak_ptr VFSUriLoader; -@property(nonatomic, assign) std::weak_ptr renderManager; -@property(nonatomic, readonly) std::weak_ptr domManager; -@property(nonatomic, readonly) NativeRenderComponentMap *viewRegistry; - -- (void)addImageProviderClass:(Class)cls; -- (NSArray> *)imageProviderClasses; +@property (nonatomic, weak) HippyBridge *bridge; +@property (nonatomic, assign) std::weak_ptr VFSUriLoader; +@property (nonatomic, assign) std::weak_ptr renderManager; +@property (nonatomic, readonly) std::weak_ptr domManager; +@property (nonatomic, readonly) HippyComponentMap *viewRegistry; /** - * Gets the view associated with a componentTag. + * Gets the view associated with a hippyTag. */ - (UIView *)viewForComponentTag:(NSNumber *)componentTag onRootTag:(NSNumber *)rootTag; /** - * Get the shadow view associated with a componentTag + * Get the shadow view associated with a hippyTag */ -- (NativeRenderObjectView *)renderObjectForcomponentTag:(NSNumber *)componentTag +- (HippyShadowView *)renderObjectForcomponentTag:(NSNumber *)componentTag onRootTag:(NSNumber *)rootTag; /** * Update the frame of a view. This might be in response to a screen rotation - * or some other layout event outside of the NativeRender-managed view hierarchy. + * or some other layout event outside of the Hippy-managed view hierarchy. */ - (void)setFrame:(CGRect)frame forRootView:(UIView *)view; @@ -95,11 +93,11 @@ class HippyValue; * Schedule a block to be executed on the UI thread. Useful if you need to execute * view logic after all currently queued view updates have completed. */ -- (void)addUIBlock:(NativeRenderRenderUIBlock)block; +- (void)addUIBlock:(HippyViewManagerUIBlock)block; /** * In some cases we might want to trigger layout from native side. - * NativeRender won't be aware of this, so we need to make sure it happens. + * Hippy won't be aware of this, so we need to make sure it happens. */ - (void)setNeedsLayoutForRootNodeTag:(NSNumber *)tag; @@ -115,24 +113,24 @@ class HippyValue; - (void)updateView:(NSNumber *)componentTag onRootTag:(NSNumber *)rootTag props:(NSDictionary *)pros; -- (__kindof NativeRenderViewManager *)renderViewManagerForViewName:(NSString *)viewName; +- (__kindof HippyViewManager *)renderViewManagerForViewName:(NSString *)viewName; /** * Manully create views recursively from hippy tag * - * @param componentTag hippy tag corresponding to UIView + * @param hippyTag hippy tag corresponding to UIView * @return view created by hippy tag */ -- (UIView *)createViewRecursivelyFromcomponentTag:(NSNumber *)componentTag +- (UIView *)createViewRecursivelyFromcomponentTag:(NSNumber *)hippyTag onRootTag:(NSNumber *)rootTag; /** * Manully create views recursively from renderObject * - * @param renderObject NativeRenderObjectView corresponding to UIView - * @return view created by NativeRenderObjectView + * @param renderObject HippyShadowView corresponding to UIView + * @return view created by HippyShadowView */ -- (UIView *)createViewRecursivelyFromRenderObject:(NativeRenderObjectView *)renderObject; +- (UIView *)createViewRecursivelyFromRenderObject:(HippyShadowView *)renderObject; /** * set dom manager for NativeRenderUIManager which holds a weak reference to domManager @@ -193,7 +191,7 @@ class HippyValue; * * @param functionName Function Name to be invoked * @param viewName Name of target view whose function invokes - * @param componentTag id of target view whose function invokes + * @param hippyTag id of target view whose function invokes * @param params parameters of function to be invoked * @param cb A callback for the return value of function * @@ -201,7 +199,7 @@ class HippyValue; */ - (id)dispatchFunction:(const std::string &)functionName viewName:(const std::string &)viewName - viewTag:(int32_t)componentTag + viewTag:(int32_t)hippyTag onRootNode:(std::weak_ptr)rootNode params:(const footstone::value::HippyValue &)params callback:(hippy::CallFunctionCallback)cb; @@ -245,10 +243,23 @@ class HippyValue; */ - (void)invalidate; -#if HP_DEBUG +#if HIPPY_DEBUG @property(nonatomic, assign) std::unordered_map>> domNodesMap; - (std::shared_ptr)domNodeForTag:(int32_t)dom_tag onRootNode:(int32_t)root_tag; - (std::vector>)childrenForNodeTag:(int32_t)tag onRootNode:(int32_t)root_tag; #endif @end + + +/** + * This category makes the current HippyUIManager instance available via the + * HippyBridge, which is useful for HippyBridgeModules or HippyViewManagers that + * need to access the HippyUIManager. + */ +@interface HippyBridge (HippyUIManager) + +/// The current HippyUIManager instance +@property (nonatomic, readonly) HippyUIManager *uiManager; + +@end diff --git a/renderer/native/ios/renderer/NativeRenderImpl.mm b/renderer/native/ios/renderer/HippyUIManager.mm similarity index 77% rename from renderer/native/ios/renderer/NativeRenderImpl.mm rename to renderer/native/ios/renderer/HippyUIManager.mm index dc3f150ea23..9dae617ccfb 100644 --- a/renderer/native/ios/renderer/NativeRenderImpl.mm +++ b/renderer/native/ios/renderer/HippyUIManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,30 +20,30 @@ * limitations under the License. */ -#import "HPAsserts.h" -#import "HPDomUtils.h" -#import "HPFootstoneUtils.h" -#import "HPOCToDomArgument.h" -#import "HPOCToHippyValue.h" -#import "HPImageProviderProtocol.h" -#import "HPToolUtils.h" -#import "NativeRenderComponentProtocol.h" -#import "NativeRenderComponentData.h" -#import "NativeRenderComponentMap.h" -#import "NativeRenderImpl.h" +#import "HippyAsserts.h" +#import "HippyDomUtils.h" +#import "HippyFootstoneUtils.h" +#import "HippyOCToDomArgument.h" +#import "HippyOCToHippyValue.h" +#import "HippyImageProviderProtocol.h" +#import "HippyUtils.h" +#import "HippyComponent.h" +#import "HippyComponentData.h" +#import "HippyComponentMap.h" +#import "HippyUIManager.h" #import "NativeRenderObjectRootView.h" -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" #import "NativeRenderUtils.h" -#import "NativeRenderView.h" -#import "NativeRenderViewManager.h" +#import "HippyView.h" +#import "HippyViewManager.h" #import "RenderVsyncManager.h" #import "UIView+DomEvent.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "UIView+Render.h" #import "NSObject+Render.h" - -#include - +#import "HippyBridgeModule.h" +#import "HippyModulesSetup.h" +#import "NativeRenderManager.h" #include "dom/root_node.h" #include "objc/runtime.h" @@ -60,24 +60,25 @@ using DomEvent = hippy::DomEvent; using RootNode = hippy::RootNode; -static NSMutableArray *NativeRenderViewManagerClasses = nil; -NSArray *NativeRenderGetViewManagerClasses(void) { - return NativeRenderViewManagerClasses; -} - -HP_EXTERN void NativeRenderRegisterView(Class); -void NativeRenderRegisterView(Class moduleClass) { - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - NativeRenderViewManagerClasses = [NSMutableArray new]; - }); - HPAssert([moduleClass respondsToSelector:@selector(viewName)], @"%@ must respond to selector viewName", NSStringFromClass(moduleClass)); - [NativeRenderViewManagerClasses addObject:moduleClass]; +static NSMutableArray *HippyViewManagerClasses = nil; +NSArray *HippyGetViewManagerClasses(void) { + if (!HippyViewManagerClasses) { + NSArray *classes = HippyGetModuleClasses(); + NSMutableArray *viewManagerClasses = [NSMutableArray array]; + for (id aClass in classes) { + if ([aClass isSubclassOfClass:HippyViewManager.class]) { + [viewManagerClasses addObject:aClass]; + } + } + HippyViewManagerClasses = viewManagerClasses; + } + return HippyViewManagerClasses; } static NSString *GetViewNameFromViewManagerClass(Class cls) { - HPAssert([cls respondsToSelector:@selector(viewName)], @"%@ must respond to selector viewName", NSStringFromClass(cls)); - NSString *viewName = [cls performSelector:@selector(viewName)]; + HippyAssert([cls respondsToSelector:@selector(moduleName)], + @"%@ must respond to selector moduleName", NSStringFromClass(cls)); + NSString *viewName = [cls performSelector:@selector(moduleName)]; return viewName; } @@ -144,51 +145,48 @@ - (void)removeAllObjects { @end -static void NativeRenderTraverseViewNodes(id view, void (^block)(id)) { - if (view.componentTag) { +static void NativeRenderTraverseViewNodes(id view, void (^block)(id)) { + if (view.hippyTag) { block(view); - for (id subview in view.subcomponents) { + for (id subview in view.subcomponents) { NativeRenderTraverseViewNodes(subview, block); } } } -#define AssertMainQueue() NSAssert(HPIsMainQueue(), @"This function must be called on the main thread") +#define AssertMainQueue() NSAssert(HippyIsMainQueue(), @"This function must be called on the main thread") NSString *const NativeRenderUIManagerDidRegisterRootViewNotification = @"NativeRenderUIManagerDidRegisterRootViewNotification"; NSString *const NativeRenderUIManagerRootViewTagKey = @"NativeRenderUIManagerRootViewKey"; NSString *const NativeRenderUIManagerKey = @"NativeRenderUIManagerKey"; NSString *const NativeRenderUIManagerDidEndBatchNotification = @"NativeRenderUIManagerDidEndBatchNotification"; -@interface NativeRenderImpl() { - NSMutableArray *_pendingUIBlocks; +@interface HippyUIManager() { + NSMutableArray *_pendingUIBlocks; - NativeRenderComponentMap *_renderObjectRegistry; - NativeRenderComponentMap *_viewRegistry; + HippyComponentMap *_viewRegistry; + HippyComponentMap *_shadowViewRegistry; // Keyed by viewName - NSMutableDictionary *_componentDataByName; + NSMutableDictionary *_componentDataByName; // Listeners such as ScrollView/ListView etc. witch will listen to start layout event // The implementation here needs to be improved to provide a registration mechanism. - NSHashTable> *_componentTransactionListeners; + NSHashTable> *_componentTransactionListeners; std::weak_ptr _domManager; std::mutex _renderQueueLock; NSMutableDictionary *_viewManagers; NSArray *_extraComponents; - std::weak_ptr _VFSUriLoader; - NSMutableArray> *_imageProviders; - std::mutex _imageProviderMutex; + NSMutableArray> *_imageProviders; std::function _rootViewSizeChangedCb; - std::weak_ptr _renderManager; } @end -@implementation NativeRenderImpl +@implementation HippyUIManager @synthesize domManager = _domManager; @@ -207,8 +205,8 @@ - (void)dealloc { } - (void)initContext { - _renderObjectRegistry = [[NativeRenderComponentMap alloc] init]; - _viewRegistry = [[NativeRenderComponentMap alloc] init]; + _shadowViewRegistry = [[HippyComponentMap alloc] init]; + _viewRegistry = [[HippyComponentMap alloc] init]; _viewRegistry.requireInMainThread = YES; _pendingUIBlocks = [NSMutableArray new]; _componentTransactionListeners = [NSHashTable weakObjectsHashTable]; @@ -221,7 +219,7 @@ - (void)invalidate { _pendingUIBlocks = nil; __weak __typeof(self) weakSelf = self; dispatch_async(dispatch_get_main_queue(), ^{ - NativeRenderImpl *strongSelf = weakSelf; + HippyUIManager *strongSelf = weakSelf; if (strongSelf) { strongSelf->_viewRegistry = nil; [strongSelf->_componentTransactionListeners removeAllObjects]; @@ -257,16 +255,16 @@ - (void)domNodeForComponentTag:(int32_t)componentTag } } -- (NativeRenderComponentMap *)renderObjectRegistry { - if (!_renderObjectRegistry) { - _renderObjectRegistry = [[NativeRenderComponentMap alloc] init]; +- (HippyComponentMap *)renderObjectRegistry { + if (!_shadowViewRegistry) { + _shadowViewRegistry = [[HippyComponentMap alloc] init]; } - return _renderObjectRegistry; + return _shadowViewRegistry; } -- (NativeRenderComponentMap *)viewRegistry { +- (HippyComponentMap *)viewRegistry { if (!_viewRegistry) { - _viewRegistry = [[NativeRenderComponentMap alloc] init]; + _viewRegistry = [[HippyComponentMap alloc] init]; } return _viewRegistry; } @@ -282,9 +280,9 @@ - (UIView *)viewForComponentTag:(NSNumber *)componentTag return [_viewRegistry componentForTag:componentTag onRootTag:rootTag]; } -- (NativeRenderObjectView *)renderObjectForcomponentTag:(NSNumber *)componentTag +- (HippyShadowView *)renderObjectForcomponentTag:(NSNumber *)componentTag onRootTag:(NSNumber *)rootTag { - return [_renderObjectRegistry componentForTag:componentTag onRootTag:rootTag]; + return [_shadowViewRegistry componentForTag:componentTag onRootTag:rootTag]; } - (std::weak_ptr)renderManager { @@ -297,14 +295,14 @@ - (NativeRenderObjectView *)renderObjectForcomponentTag:(NSNumber *)componentTag #pragma mark - #pragma mark View Manager -- (NativeRenderComponentData *)componentDataForViewName:(NSString *)viewName { +- (HippyComponentData *)componentDataForViewName:(NSString *)viewName { if (viewName) { - NativeRenderComponentData *componentData = _componentDataByName[viewName]; + HippyComponentData *componentData = _componentDataByName[viewName]; if (!componentData) { - NativeRenderViewManager *viewManager = [self renderViewManagerForViewName:viewName]; + HippyViewManager *viewManager = [self renderViewManagerForViewName:viewName]; NSAssert(viewManager, @"No view manager found for %@", viewName); if (viewManager) { - componentData = [[NativeRenderComponentData alloc] initWithViewManager:viewManager viewName:viewName]; + componentData = [[HippyComponentData alloc] initWithViewManager:viewManager viewName:viewName]; _componentDataByName[viewName] = componentData; } } @@ -316,10 +314,10 @@ - (NativeRenderComponentData *)componentDataForViewName:(NSString *)viewName { - (void)registerRootView:(UIView *)rootView asRootNode:(std::weak_ptr)rootNode { AssertMainQueue(); - NSNumber *componentTag = rootView.componentTag; - NSAssert(NativeRenderIsRootView(componentTag), @"View %@ with tag #%@ is not a root view", rootView, componentTag); + NSNumber *componentTag = rootView.hippyTag; + NSAssert(HippyIsHippyRootView(componentTag), @"View %@ with tag #%@ is not a root view", rootView, componentTag); -#if HP_DEBUG +#if HIPPY_DEBUG NSAssert(![_viewRegistry containRootComponentWithTag:componentTag], @"RootView Tag already exists. Added %@ twice", componentTag); #endif // Register view @@ -332,22 +330,22 @@ - (void)registerRootView:(UIView *)rootView asRootNode:(std::weak_ptr) UIColor *backgroundColor = [rootView backgroundColor]; NSString *rootViewClassName = NSStringFromClass([rootView class]); // Register shadow view - __weak NativeRenderImpl *weakSelf = self; + __weak HippyUIManager *weakSelf = self; std::function registerRootViewFunction = [weakSelf, componentTag, frame, backgroundColor, rootViewClassName, rootNode](){ @autoreleasepool { - NativeRenderImpl *strongSelf = weakSelf; + HippyUIManager *strongSelf = weakSelf; if (!strongSelf) { return; } std::lock_guard lock([strongSelf renderQueueLock]); NativeRenderObjectRootView *renderObject = [[NativeRenderObjectRootView alloc] init]; - renderObject.componentTag = componentTag; + renderObject.hippyTag = componentTag; renderObject.frame = frame; renderObject.backgroundColor = backgroundColor; renderObject.viewName = rootViewClassName; renderObject.rootNode = rootNode; renderObject.domNode = rootNode; - [strongSelf->_renderObjectRegistry addRootComponent:renderObject rootNode:rootNode forTag:componentTag]; + [strongSelf->_shadowViewRegistry addRootComponent:renderObject rootNode:rootNode forTag:componentTag]; NSDictionary *userInfo = @{ NativeRenderUIManagerRootViewTagKey: componentTag, NativeRenderUIManagerKey: strongSelf}; [[NSNotificationCenter defaultCenter] postNotificationName:NativeRenderUIManagerDidRegisterRootViewNotification @@ -366,7 +364,7 @@ - (void)unregisterRootViewFromTag:(NSNumber *)rootTag { } std::lock_guard lock([self renderQueueLock]); [_viewRegistry removeRootComponentWithTag:rootTag]; - [_renderObjectRegistry removeRootComponentWithTag:rootTag]; + [_shadowViewRegistry removeRootComponentWithTag:rootTag]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { @@ -375,7 +373,7 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N CGRect oriFrame = [change[NSKeyValueChangeOldKey] CGRectValue]; if (!CGRectEqualToRect(curFrame, oriFrame)) { UIView *rootView = (UIView *)object; - NSNumber *rootTag = [rootView componentTag]; + NSNumber *rootTag = [rootView hippyTag]; auto rootNode = [_viewRegistry rootNodeForTag:rootTag].lock(); auto domManager = _domManager.lock(); if (rootNode && domManager) { @@ -385,10 +383,10 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N }; auto value = std::make_shared([params toHippyValue]); auto event = std::make_shared("onSizeChanged", rootNode, NO, NO, value); - __weak NativeRenderImpl *weakSelf = self; + __weak HippyUIManager *weakSelf = self; std::function func = [weakSelf, rootNode, event, rootTag](){ rootNode->HandleEvent(event); - NativeRenderImpl *strongSelf = weakSelf; + HippyUIManager *strongSelf = weakSelf; if (strongSelf) { [strongSelf domEventDidHandle:"onSizeChanged" forNode:[rootTag intValue] onRoot:[rootTag intValue]]; } @@ -404,7 +402,7 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N - (void)setFrame:(CGRect)frame forRootView:(UIView *)view { AssertMainQueue(); - NSNumber *componentTag = view.componentTag; + NSNumber *componentTag = view.hippyTag; auto domManager = _domManager.lock(); if (!domManager) { return; @@ -414,14 +412,14 @@ - (void)setFrame:(CGRect)frame forRootView:(UIView *)view { if (!weakSelf) { return; } - NativeRenderImpl *strongSelf = weakSelf; - NativeRenderObjectView *renderObject = [strongSelf->_renderObjectRegistry rootComponentForTag:componentTag]; + HippyUIManager *strongSelf = weakSelf; + HippyShadowView *renderObject = [strongSelf->_shadowViewRegistry rootComponentForTag:componentTag]; if (renderObject == nil) { return; } if (!CGRectEqualToRect(frame, renderObject.frame)) { renderObject.frame = frame; - std::weak_ptr rootNode = [strongSelf->_renderObjectRegistry rootNodeForTag:componentTag]; + std::weak_ptr rootNode = [strongSelf->_shadowViewRegistry rootNodeForTag:componentTag]; [strongSelf batchOnRootNode:rootNode]; } }}; @@ -431,16 +429,16 @@ - (void)setFrame:(CGRect)frame forRootView:(UIView *)view { /** * Unregisters views from registries */ -- (void)purgeChildren:(NSArray> *)children +- (void)purgeChildren:(NSArray> *)children onRootTag:(NSNumber *)rootTag - fromRegistry:(NSMutableDictionary> *)registry { - for (id child in children) { - NativeRenderTraverseViewNodes(registry[child.componentTag], ^(id subview) { - NSAssert(![subview isNativeRenderRootView], @"Root views should not be unregistered"); + fromRegistry:(NSMutableDictionary> *)registry { + for (id child in children) { + NativeRenderTraverseViewNodes(registry[child.hippyTag], ^(id subview) { + NSAssert(![subview isHippyRootView], @"Root views should not be unregistered"); if ([subview respondsToSelector:@selector(invalidate)]) { [subview performSelector:@selector(invalidate)]; } - [registry removeObjectForKey:subview.componentTag]; + [registry removeObjectForKey:subview.hippyTag]; }); } } @@ -448,64 +446,64 @@ - (void)purgeChildren:(NSArray> *)children - (void)purgeViewsFromComponentTags:(NSArray *)componentTags onRootTag:(NSNumber *)rootTag { for (NSNumber *componentTag in componentTags) { UIView *view = [self viewForComponentTag:componentTag onRootTag:rootTag]; - NativeRenderComponentMap *componentMap = _viewRegistry; - NativeRenderTraverseViewNodes(view, ^(id subview) { - NSAssert(![subview isNativeRenderRootView], @"Root views should not be unregistered"); + HippyComponentMap *componentMap = _viewRegistry; + NativeRenderTraverseViewNodes(view, ^(id subview) { + NSAssert(![subview isHippyRootView], @"Root views should not be unregistered"); [componentMap removeComponent:subview forRootTag:rootTag]; }); } } -- (void)removeChildren:(NSArray> *)children fromContainer:(id)container { - for (id removedChild in children) { - [container removeNativeRenderSubview:removedChild]; +- (void)removeChildren:(NSArray> *)children fromContainer:(id)container { + for (id removedChild in children) { + [container removeHippySubview:removedChild]; } } - (UIView *)createViewRecursivelyFromcomponentTag:(NSNumber *)componentTag onRootTag:(NSNumber *)rootTag { - NativeRenderObjectView *renderObject = [_renderObjectRegistry componentForTag:componentTag onRootTag:rootTag]; + HippyShadowView *renderObject = [_shadowViewRegistry componentForTag:componentTag onRootTag:rootTag]; return [self createViewRecursivelyFromRenderObject:renderObject]; } -- (UIView *)createViewFromRenderObject:(NativeRenderObjectView *)renderObject { +- (UIView *)createViewFromRenderObject:(HippyShadowView *)renderObject { AssertMainQueue(); - HPAssert(renderObject.viewName, @"view name is needed for creating a view"); - NativeRenderComponentData *componentData = [self componentDataForViewName:renderObject.viewName]; + HippyAssert(renderObject.viewName, @"view name is needed for creating a view"); + HippyComponentData *componentData = [self componentDataForViewName:renderObject.viewName]; UIView *view = [self createViewByComponentData:componentData - componentTag:renderObject.componentTag + componentTag:renderObject.hippyTag rootTag:renderObject.rootTag properties:renderObject.props viewName:renderObject.viewName]; view.renderManager = [self renderManager]; - [view nativeRenderSetFrame:renderObject.frame]; + [view hippySetFrame:renderObject.frame]; const std::vector &eventNames = [renderObject allEventNames]; for (auto &event : eventNames) { [self addEventNameInMainThread:event - forDomNodeId:[renderObject.componentTag intValue] + forDomNodeId:[renderObject.hippyTag intValue] onRootNode:renderObject.rootNode]; } return view; } -- (UIView *)createViewRecursivelyFromRenderObject:(NativeRenderObjectView *)renderObject { +- (UIView *)createViewRecursivelyFromRenderObject:(HippyShadowView *)renderObject { AssertMainQueue(); std::lock_guard lock([self renderQueueLock]); return [self createViewRecursiveFromRenderObjectWithNOLock:renderObject]; } -- (UIView *)createViewRecursiveFromRenderObjectWithNOLock:(NativeRenderObjectView *)renderObject { +- (UIView *)createViewRecursiveFromRenderObjectWithNOLock:(HippyShadowView *)renderObject { UIView *view = [self createViewFromRenderObject:renderObject]; NSUInteger index = 0; - for (NativeRenderObjectView *subRenderObject in renderObject.subcomponents) { + for (HippyShadowView *subRenderObject in renderObject.subcomponents) { UIView *subview = [self createViewRecursiveFromRenderObjectWithNOLock:subRenderObject]; - [view insertNativeRenderSubview:subview atIndex:index]; + [view insertHippySubview:subview atIndex:index]; index++; } - view.nativeRenderObjectView = renderObject; + view.hippyShadowView = renderObject; view.renderManager = [self renderManager]; [view clearSortedSubviews]; - [view didUpdateNativeRenderSubviews]; + [view didUpdateHippySubviews]; NSMutableSet *applierBlocks = [NSMutableSet setWithCapacity:256]; [renderObject amendLayoutBeforeMount:applierBlocks]; if (applierBlocks.count) { @@ -530,14 +528,14 @@ - (NSDictionary *)createRenderObjectFromNode:(const std::shared_ptrGetViewName().c_str()]; NSString *tagName = [NSString stringWithUTF8String:domNode->GetTagName().c_str()]; NSMutableDictionary *props = [StylesFromDomNode(domNode) mutableCopy]; - NativeRenderComponentData *componentData = [self componentDataForViewName:viewName]; - NativeRenderObjectView *renderObject = [componentData createRenderObjectViewWithTag:componentTag]; + HippyComponentData *componentData = [self componentDataForViewName:viewName]; + HippyShadowView *renderObject = [componentData createRenderObjectViewWithTag:componentTag]; renderObject.rootNode = rootNode; NSAssert(componentData && renderObject, @"componentData and renderObject must not be nil"); [props setValue: rootTag forKey: @"rootTag"]; // Register shadow view if (renderObject) { - renderObject.componentTag = componentTag; + renderObject.hippyTag = componentTag; renderObject.rootTag = rootTag; renderObject.viewName = viewName; renderObject.tagName = tagName; @@ -547,13 +545,13 @@ - (NSDictionary *)createRenderObjectFromNode:(const std::shared_ptrGetLayoutResult(); renderObject.frame = CGRectMakeFromLayoutResult(domNode->GetLayoutResult()); - [componentData setProps:props forRenderObjectView:renderObject]; - [_renderObjectRegistry addComponent:renderObject forRootTag:rootTag]; + [componentData setProps:props forShadowView:renderObject]; + [_shadowViewRegistry addComponent:renderObject forRootTag:rootTag]; } return props; } -- (UIView *)createViewByComponentData:(NativeRenderComponentData *)componentData +- (UIView *)createViewByComponentData:(HippyComponentData *)componentData componentTag:(NSNumber *)componentTag rootTag:(NSNumber *)rootTag properties:(NSDictionary *)props @@ -569,7 +567,7 @@ - (UIView *)createViewByComponentData:(NativeRenderComponentData *)componentData * otherwise hippySubviews will be inserted multiple times. */ if (view && canBeRetrievedFromCache) { - [view resetNativeRenderSubviews]; + [view resetHippySubviews]; } else { view = [componentData createViewWithTag:componentTag initProps:props]; @@ -580,7 +578,7 @@ - (UIView *)createViewByComponentData:(NativeRenderComponentData *)componentData view.renderManager = [self renderManager]; [componentData setProps:props forView:view]; // Must be done before bgColor to prevent wrong default - if ([view respondsToSelector:@selector(nativeRenderComponentDidFinishTransaction)]) { + if ([view respondsToSelector:@selector(hippyBridgeDidFinishTransaction)]) { [self->_componentTransactionListeners addObject:view]; } [_viewRegistry addComponent:view forRootTag:rootTag]; @@ -591,38 +589,39 @@ - (UIView *)createViewByComponentData:(NativeRenderComponentData *)componentData - (void)updateView:(nonnull NSNumber *)componentTag onRootTag:(NSNumber *)rootTag props:(NSDictionary *)props { - NativeRenderObjectView *renderObject = [_renderObjectRegistry componentForTag:componentTag onRootTag:rootTag]; + HippyShadowView *renderObject = [_shadowViewRegistry componentForTag:componentTag onRootTag:rootTag]; if (!renderObject) { return; } - NativeRenderComponentData *componentData = [self componentDataForViewName:renderObject.viewName]; + HippyComponentData *componentData = [self componentDataForViewName:renderObject.viewName]; NSDictionary *newProps = props; NSDictionary *virtualProps = props; newProps = [renderObject mergeProps:props]; virtualProps = renderObject.props; - [componentData setProps:newProps forRenderObjectView:renderObject]; + [componentData setProps:newProps forShadowView:renderObject]; [renderObject dirtyPropagation:NativeRenderUpdateLifecyclePropsDirtied]; - [self addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[componentTag]; [componentData setProps:newProps forView:view]; }]; } #pragma mark Render Context Implementation -- (__kindof NativeRenderViewManager *)renderViewManagerForViewName:(NSString *)viewName { + +- (__kindof HippyViewManager *)renderViewManagerForViewName:(NSString *)viewName { if (!_viewManagers) { _viewManagers = [NSMutableDictionary dictionaryWithCapacity:64]; if (_extraComponents) { for (Class cls in _extraComponents) { NSString *viewName = GetViewNameFromViewManagerClass(cls); - HPAssert(![_viewManagers objectForKey:viewName], + HippyAssert(![_viewManagers objectForKey:viewName], @"duplicated component %@ for class %@ and %@", viewName, NSStringFromClass(cls), NSStringFromClass([_viewManagers objectForKey:viewName])); [_viewManagers setObject:cls forKey:viewName]; } } - NSArray *classes = NativeRenderGetViewManagerClasses(); + NSArray *classes = HippyGetViewManagerClasses(); NSMutableDictionary *defaultViewManagerClasses = [NSMutableDictionary dictionaryWithCapacity:[classes count]]; for (Class cls in classes) { NSString *viewName = GetViewNameFromViewManagerClass(cls); @@ -635,9 +634,9 @@ - (__kindof NativeRenderViewManager *)renderViewManagerForViewName:(NSString *)v } id object = [_viewManagers objectForKey:viewName]; if (object_isClass(object)) { - NativeRenderViewManager *viewManager = [object new]; - viewManager.renderImpl = self; - NSAssert([viewManager isKindOfClass:[NativeRenderViewManager class]], @"It must be a NativeRenderViewManager instance"); + HippyViewManager *viewManager = [object new]; + viewManager.bridge = self.bridge; + NSAssert([viewManager isKindOfClass:[HippyViewManager class]], @"It must be a HippyViewManager instance"); [_viewManagers setObject:viewManager forKey:viewName]; object = viewManager; } @@ -650,7 +649,7 @@ - (__kindof NativeRenderViewManager *)renderViewManagerForViewName:(NSString *)v #pragma mark Schedule Block -- (void)addUIBlock:(NativeRenderRenderUIBlock)block { +- (void)addUIBlock:(HippyViewManagerUIBlock)block { if (!block || !_viewRegistry) { return; } @@ -658,12 +657,12 @@ - (void)addUIBlock:(NativeRenderRenderUIBlock)block { [_pendingUIBlocks addObject:block]; } -- (void)amendPendingUIBlocksWithStylePropagationUpdateForRenderObject:(NativeRenderObjectView *)topView { +- (void)amendPendingUIBlocksWithStylePropagationUpdateForRenderObject:(HippyShadowView *)topView { NSMutableSet *applierBlocks = [NSMutableSet setWithCapacity:256]; [topView collectUpdatedProperties:applierBlocks parentProperties:@{}]; if (applierBlocks.count) { - [self addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { for (NativeRenderApplierBlock block in applierBlocks) { block(viewRegistry); } @@ -681,11 +680,11 @@ - (void)flushUIBlocksOnRootNode:(std::weak_ptr)rootNode { } unsigned int rand = arc4random(); HP_PERF_LOG("flushUIBlocksOnRootNode(random id:%u", rand); - + int32_t rootTag = strongRootNode->GetId(); - NSArray *previousPendingUIBlocks = _pendingUIBlocks; + NSArray *previousPendingUIBlocks = _pendingUIBlocks; _pendingUIBlocks = [NSMutableArray new]; - __weak NativeRenderImpl *weakManager = self; + __weak HippyUIManager *weakManager = self; if (previousPendingUIBlocks.count) { // Execute the previously queued UI blocks dispatch_async(dispatch_get_main_queue(), ^{ @@ -693,23 +692,21 @@ - (void)flushUIBlocksOnRootNode:(std::weak_ptr)rootNode { HP_PERF_LOG("flushUIBlocksOnRootNode on main thread(random id:%u)",rand); int cnt = 0; - NativeRenderImpl *strongSelf = weakManager; + HippyUIManager *strongSelf = weakManager; NSDictionary *viewReg = [strongSelf->_viewRegistry componentsForRootTag:@(rootTag)]; @try { - for (NativeRenderRenderUIBlock block in previousPendingUIBlocks) { + for (HippyViewManagerUIBlock block in previousPendingUIBlocks) { block(strongSelf, viewReg); ++cnt; } } @catch (NSException *exception) { } HP_PERF_LOG("flushUIBlocksOnRootNode on main thread done, block count:%d(random id:%u)", cnt, rand); - } }); } HP_PERF_LOG("flushUIBlocksOnRootNode End(random id:%u)",rand); - } #pragma mark - @@ -730,7 +727,7 @@ - (void)createRenderNodes:(std::vector> &&)nodes if (!strongRootNode) { return; } -#if HP_DEBUG +#if HIPPY_DEBUG auto &nodeMap = _domNodesMap[strongRootNode->GetId()]; for (auto node : nodes) { nodeMap[node->GetId()] = node; @@ -739,48 +736,48 @@ - (void)createRenderNodes:(std::vector> &&)nodes NSNumber *rootNodeTag = @(strongRootNode->GetId()); std::lock_guard lock([self renderQueueLock]); NativeRenderViewsRelation *manager = [[NativeRenderViewsRelation alloc] init]; - NSMutableDictionary *dicProps = [NSMutableDictionary dictionaryWithCapacity:nodes.size()]; +// NSMutableDictionary *dicProps = [NSMutableDictionary dictionaryWithCapacity:nodes.size()]; for (const std::shared_ptr &node : nodes) { const auto& render_info = node->GetRenderInfo(); [manager addViewTag:render_info.id forSuperViewTag:render_info.pid atIndex:render_info.index]; NSDictionary *nodeProps = [self createRenderObjectFromNode:node onRootNode:rootNode]; - [dicProps setObject:nodeProps forKey:@(node->GetId())]; +// [dicProps setObject:nodeProps forKey:@(node->GetId())]; } [manager enumerateViewsHierarchy:^(int32_t tag, const std::vector &subviewTags, const std::vector &subviewIndices) { NSAssert(subviewTags.size() == subviewIndices.size(), @"subviewTags count must be equal to subviewIndices count"); - NativeRenderObjectView *superRenderObject = [self->_renderObjectRegistry componentForTag:@(tag) onRootTag:rootNodeTag]; + HippyShadowView *superRenderObject = [self->_shadowViewRegistry componentForTag:@(tag) onRootTag:rootNodeTag]; for (NSUInteger index = 0; index < subviewTags.size(); index++) { - NativeRenderObjectView *subRenderObject = [self->_renderObjectRegistry componentForTag:@(subviewTags[index]) onRootTag:rootNodeTag]; - [superRenderObject insertNativeRenderSubview:subRenderObject atIndex:subviewIndices[index]]; + HippyShadowView *subRenderObject = [self->_shadowViewRegistry componentForTag:@(subviewTags[index]) onRootTag:rootNodeTag]; + [superRenderObject insertHippySubview:subRenderObject atIndex:subviewIndices[index]]; } - [superRenderObject didUpdateNativeRenderSubviews]; + [superRenderObject didUpdateHippySubviews]; }]; for (const std::shared_ptr &node : nodes) { NSNumber *componentTag = @(node->GetId()); - NativeRenderObjectView *renderObject = [_renderObjectRegistry componentForTag:componentTag onRootTag:rootNodeTag]; + HippyShadowView *renderObject = [_shadowViewRegistry componentForTag:componentTag onRootTag:rootNodeTag]; if (NativeRenderCreationTypeInstantly == [renderObject creationType] && !_uiCreationLazilyEnabled) { - [self addUIBlock:^(NativeRenderImpl *renderContext, __unused NSDictionary *viewRegistry) { - UIView *view = [renderContext createViewFromRenderObject:renderObject]; - view.nativeRenderObjectView = renderObject; - view.renderManager = [renderContext renderManager]; + [self addUIBlock:^(HippyUIManager *uiManager, __unused NSDictionary *viewRegistry) { + UIView *view = [uiManager createViewFromRenderObject:renderObject]; + view.hippyShadowView = renderObject; + view.renderManager = [uiManager renderManager]; }]; } } [manager enumerateViewsHierarchy:^(int32_t tag, const std::vector &subviewTags, const std::vector &subviewIndices) { auto subViewTags_ = subviewTags; auto subViewIndices_ = subviewIndices; - NativeRenderObjectView *renderObject = [self->_renderObjectRegistry componentForTag:@(tag) onRootTag:rootNodeTag]; + HippyShadowView *renderObject = [self->_shadowViewRegistry componentForTag:@(tag) onRootTag:rootNodeTag]; if (NativeRenderCreationTypeInstantly == [renderObject creationType] && !self->_uiCreationLazilyEnabled) { - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *superView = viewRegistry[@(tag)]; for (NSUInteger index = 0; index < subViewTags_.size(); index++) { UIView *subview = viewRegistry[@(subViewTags_[index])]; if (subview) { - [superView insertNativeRenderSubview:subview atIndex:subViewIndices_[index]]; + [superView insertHippySubview:subview atIndex:subViewIndices_[index]]; } } [superView clearSortedSubviews]; - [superView didUpdateNativeRenderSubviews]; + [superView didUpdateHippySubviews]; }]; } }]; @@ -792,7 +789,7 @@ - (void)updateRenderNodes:(std::vector>&&)nodes if (!strongRootNode) { return; } -#if HP_DEBUG +#if HIPPY_DEBUG auto &nodeMap = _domNodesMap[strongRootNode->GetId()]; for (auto node : nodes) { nodeMap[node->GetId()] = node; @@ -824,7 +821,7 @@ - (void)deleteRenderNodesIds:(std::vector> &&)no if (!strongRootNode) { return; } -#if HP_DEBUG +#if HIPPY_DEBUG auto &nodeMap = _domNodesMap[strongRootNode->GetId()]; for (auto node : nodes) { nodeMap[node->GetId()] = nullptr; @@ -832,21 +829,21 @@ - (void)deleteRenderNodesIds:(std::vector> &&)no #endif std::lock_guard lock([self renderQueueLock]); NSNumber *rootTag = @(strongRootNode->GetId()); - NSMutableDictionary *currentRegistry = [_renderObjectRegistry componentsForRootTag:rootTag]; + NSMutableDictionary *currentRegistry = [_shadowViewRegistry componentsForRootTag:rootTag]; for (auto dom_node : nodes) { int32_t tag = dom_node->GetRenderInfo().id; - NativeRenderObjectView *renderObject = [currentRegistry objectForKey:@(tag)]; + HippyShadowView *renderObject = [currentRegistry objectForKey:@(tag)]; [renderObject dirtyPropagation:NativeRenderUpdateLifecycleLayoutDirtied]; if (renderObject) { - [renderObject removeFromNativeRenderSuperview]; + [renderObject removeFromHippySuperview]; [self purgeChildren:@[renderObject] onRootTag:rootTag fromRegistry:currentRegistry]; } } - __weak NativeRenderImpl *weakSelf = self; + __weak HippyUIManager *weakSelf = self; auto strongNodes = std::move(nodes); - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderImpl *strongSelf = weakSelf; + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { + HippyUIManager *strongSelf = weakSelf; if (!strongSelf) { return; } @@ -862,14 +859,14 @@ - (void)deleteRenderNodesIds:(std::vector> &&)no continue; } [parentViews addObject:parentView]; - [view removeFromNativeRenderSuperview]; + [view removeFromHippySuperview]; [views addObject:view]; } NSMutableDictionary *currentViewRegistry = [strongSelf->_viewRegistry componentsForRootTag:rootTag]; [strongSelf purgeChildren:views onRootTag:rootTag fromRegistry:currentViewRegistry]; for (UIView *view in parentViews) { [view clearSortedSubviews]; - [view didUpdateNativeRenderSubviews]; + [view didUpdateHippySubviews]; } }]; } @@ -885,22 +882,22 @@ - (void)renderMoveViews:(const std::vector &&)ids } int32_t rootTag = strongRootNode->GetId(); - NativeRenderObjectView *fromObjectView = [_renderObjectRegistry componentForTag:@(fromContainer) + HippyShadowView *fromObjectView = [_shadowViewRegistry componentForTag:@(fromContainer) onRootTag:@(rootTag)]; - NativeRenderObjectView *toObjectView = [_renderObjectRegistry componentForTag:@(toContainer) + HippyShadowView *toObjectView = [_shadowViewRegistry componentForTag:@(toContainer) onRootTag:@(rootTag)]; for (int32_t componentTag : ids) { - NativeRenderObjectView *view = [_renderObjectRegistry componentForTag:@(componentTag) onRootTag:@(rootTag)]; - HPAssert(fromObjectView == [view parentComponent], @"parent of object view with tag %d is not object view with tag %d", componentTag, fromContainer); - [view removeFromNativeRenderSuperview]; - [toObjectView insertNativeRenderSubview:view atIndex:index]; + HippyShadowView *view = [_shadowViewRegistry componentForTag:@(componentTag) onRootTag:@(rootTag)]; + HippyAssert(fromObjectView == [view parentComponent], @"parent of object view with tag %d is not object view with tag %d", componentTag, fromContainer); + [view removeFromHippySuperview]; + [toObjectView insertHippySubview:view atIndex:index]; } [fromObjectView dirtyPropagation:NativeRenderUpdateLifecycleLayoutDirtied]; [toObjectView dirtyPropagation:NativeRenderUpdateLifecycleLayoutDirtied]; - [fromObjectView didUpdateNativeRenderSubviews]; - [toObjectView didUpdateNativeRenderSubviews]; + [fromObjectView didUpdateHippySubviews]; + [toObjectView didUpdateHippySubviews]; auto strongTags = std::move(ids); - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *fromView = [viewRegistry objectForKey:@(fromContainer)]; UIView *toView = [viewRegistry objectForKey:@(toContainer)]; for (int32_t tag : strongTags) { @@ -908,14 +905,14 @@ - (void)renderMoveViews:(const std::vector &&)ids if (!view) { continue; } - HPAssert(fromView == [view parentComponent], @"parent of object view with tag %d is not object view with tag %d", tag, fromContainer); - [view removeFromNativeRenderSuperview]; - [toView insertNativeRenderSubview:view atIndex:index]; + HippyAssert(fromView == [view parentComponent], @"parent of object view with tag %d is not object view with tag %d", tag, fromContainer); + [view removeFromHippySuperview]; + [toView insertHippySubview:view atIndex:index]; } [fromView clearSortedSubviews]; - [fromView didUpdateNativeRenderSubviews]; + [fromView didUpdateHippySubviews]; [toView clearSortedSubviews]; - [toView didUpdateNativeRenderSubviews]; + [toView didUpdateHippySubviews]; }]; } @@ -927,21 +924,21 @@ - (void)renderMoveNodes:(std::vector> &&)nodes } int32_t rootTag = strongRootNode->GetId(); std::lock_guard lock([self renderQueueLock]); - NativeRenderObjectView *parentObjectView = nil; + HippyShadowView *parentObjectView = nil; for (auto &node : nodes) { int32_t index = node->GetRenderInfo().index; int32_t componentTag = node->GetId(); - NativeRenderObjectView *objectView = [_renderObjectRegistry componentForTag:@(componentTag) onRootTag:@(rootTag)]; + HippyShadowView *objectView = [_shadowViewRegistry componentForTag:@(componentTag) onRootTag:@(rootTag)]; [objectView dirtyPropagation:NativeRenderUpdateLifecycleLayoutDirtied]; - HPAssert(!parentObjectView || parentObjectView == [objectView parentComponent], @"try to move object view on different parent object view"); + HippyAssert(!parentObjectView || parentObjectView == [objectView parentComponent], @"try to move object view on different parent object view"); if (!parentObjectView) { parentObjectView = [objectView parentComponent]; } - [parentObjectView moveNativeRenderSubview:objectView toIndex:index]; + [parentObjectView moveHippySubview:objectView toIndex:index]; } - [parentObjectView didUpdateNativeRenderSubviews]; + [parentObjectView didUpdateHippySubviews]; auto strongNodes = std::move(nodes); - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *superView = nil; for (auto node : strongNodes) { int32_t index = node->GetIndex(); @@ -950,14 +947,14 @@ - (void)renderMoveNodes:(std::vector> &&)nodes if (!view) { continue; } - HPAssert(!superView || superView == [view parentComponent], @"try to move views on different parent views"); + HippyAssert(!superView || superView == [view parentComponent], @"try to move views on different parent views"); if (!superView) { superView = [view parentComponent]; } - [superView moveNativeRenderSubview:view toIndex:index]; + [superView moveHippySubview:view toIndex:index]; } [superView clearSortedSubviews]; - [superView didUpdateNativeRenderSubviews]; + [superView didUpdateHippySubviews]; }]; } @@ -974,19 +971,19 @@ - (void)updateNodesLayout:(const std::vector(layoutInfoTuple); CGRect frame = CGRectMakeFromLayoutResult(layoutResult); - NativeRenderObjectView *renderObject = [_renderObjectRegistry componentForTag:componentTag onRootTag:rootTag]; + HippyShadowView *renderObject = [_shadowViewRegistry componentForTag:componentTag onRootTag:rootTag]; if (renderObject) { [renderObject dirtyPropagation:NativeRenderUpdateLifecycleLayoutDirtied]; renderObject.frame = frame; renderObject.nodeLayoutResult = layoutResult; - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[componentTag]; /* do not use frame directly, because shadow view's frame possibly changed manually in - * [NativeRenderObjectView collectRenderObjectHaveNewLayoutResults] + * [HippyShadowView collectRenderObjectHaveNewLayoutResults] * This is a Wrong example: * [view hippySetFrame:frame] */ - [view nativeRenderSetFrame:renderObject.frame]; + [view hippySetFrame:renderObject.frame]; }]; } } @@ -1032,7 +1029,7 @@ - (id)dispatchFunction:(const std::string &)functionName [finalParams addObject:[NSNull null]]; } if (cb) { - RenderUIResponseSenderBlock senderBlock = ^(id senderParams) { + HippyPromiseResolveBlock senderBlock = ^(id senderParams) { std::shared_ptr domArgument = std::make_shared([senderParams toDomArgument]); cb(domArgument); }; @@ -1040,8 +1037,8 @@ - (id)dispatchFunction:(const std::string &)functionName } NSString *nativeModuleName = [NSString stringWithUTF8String:viewName.c_str()]; - NativeRenderViewManager *viewManager = [self renderViewManagerForViewName:nativeModuleName]; - NativeRenderComponentData *componentData = [self componentDataForViewName:nativeModuleName]; + HippyViewManager *viewManager = [self renderViewManagerForViewName:nativeModuleName]; + HippyComponentData *componentData = [self componentDataForViewName:nativeModuleName]; NSValue *selectorPointer = [componentData.methodsByName objectForKey:name]; SEL selector = (SEL)[selectorPointer pointerValue]; if (!selector) { @@ -1065,8 +1062,8 @@ - (id)dispatchFunction:(const std::string &)functionName return nil; } @catch (NSException *exception) { NSString *message = [NSString stringWithFormat:@"Exception '%@' was thrown while invoking %@ on component target %@ with params %@", exception, name, nativeModuleName, finalParams]; - NSError *error = HPErrorWithMessage(message); - HPFatal(error, nil); + NSError *error = HippyErrorWithMessage(message); + HippyFatal(error); return nil; } } @@ -1085,35 +1082,30 @@ - (void)addEventName:(const std::string &)name forDomNodeId:(int32_t)node_id return; } int32_t root_id = strongRootNode->GetId(); - NativeRenderObjectView *renderObject = [self renderObjectForcomponentTag:@(node_id) onRootTag:@(root_id)]; + HippyShadowView *renderObject = [self renderObjectForcomponentTag:@(node_id) onRootTag:@(root_id)]; [renderObject addEventName:name]; if (name == hippy::kClickEvent) { - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderImpl *uiManager = (NativeRenderImpl *)renderContext; + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { [uiManager addClickEventListenerForView:node_id onRootNode:rootNode]; }]; } else if (name == hippy::kLongClickEvent) { - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderImpl *uiManager = (NativeRenderImpl *)renderContext; + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { [uiManager addLongClickEventListenerForView:node_id onRootNode:rootNode]; }]; } else if (name == hippy::kTouchStartEvent || name == hippy::kTouchMoveEvent || name == hippy::kTouchEndEvent || name == hippy::kTouchCancelEvent) { std::string name_ = name; - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderImpl *uiManager = (NativeRenderImpl *)renderContext; + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { [uiManager addTouchEventListenerForType:name_ forView:node_id onRootNode:rootNode]; }]; } else if (name == hippy::kShowEvent || name == hippy::kDismissEvent) { std::string name_ = name; - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderImpl *uiManager = (NativeRenderImpl *)renderContext; + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { [uiManager addShowEventListenerForType:name_ forView:node_id onRootNode:rootNode]; }]; } else if (name == hippy::kPressIn || name == hippy::kPressOut) { std::string name_ = name; - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderImpl *uiManager = (NativeRenderImpl *)renderContext; + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { [uiManager addPressEventListenerForType:name_ forView:node_id onRootNode:rootNode]; }]; } else if (name == kVSyncKey) { @@ -1142,8 +1134,7 @@ - (void)addEventName:(const std::string &)name forDomNodeId:(int32_t)node_id } else { std::string name_ = name; - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderImpl *uiManager = (NativeRenderImpl *)renderContext; + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { [uiManager addPropertyEvent:name_ forDomNode:node_id onRootNode:rootNode]; }]; } @@ -1374,8 +1365,7 @@ - (void)removeEventName:(const std::string &)eventName eventName == hippy::kShowEvent || eventName == hippy::kDismissEvent || eventName == hippy::kPressIn || eventName == hippy::kPressOut) { std::string name_ = eventName; - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderImpl *uiManager = (NativeRenderImpl *)renderContext; + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = [uiManager viewForComponentTag:@(componentTag) onRootTag:@(root_id)]; [view removeViewEvent:viewEventTypeFromName(name_.c_str())]; }]; @@ -1390,7 +1380,7 @@ - (void)removeEventName:(const std::string &)eventName }]; } else { std::string name_ = eventName; - [self addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = [viewRegistry objectForKey:@(componentTag)]; [view removePropertyEvent:name_.c_str()]; }]; @@ -1415,7 +1405,7 @@ - (void)addPropertyEvent:(const std::string &)name forDomNode:(int32_t)node_id std::string name_ = name; NSDictionary *componentDataByName = [_componentDataByName copy]; NSString *viewName = view.viewName; - NativeRenderComponentData *component = componentDataByName[viewName]; + HippyComponentData *component = componentDataByName[viewName]; NSDictionary *eventMap = [component eventNameMap]; NSString *mapToEventName = [eventMap objectForKey:[NSString stringWithUTF8String:name_.c_str()]]; if (mapToEventName) { @@ -1457,21 +1447,20 @@ - (void)layoutAndMountOnRootNode:(std::weak_ptr)rootNode { return; } int32_t root_id = strongRootNode->GetId(); - NativeRenderObjectView *rootView = [_renderObjectRegistry rootComponentForTag:@(root_id)]; + HippyShadowView *rootView = [_shadowViewRegistry rootComponentForTag:@(root_id)]; NSMutableSet *uiBlocks = [NSMutableSet setWithCapacity:128]; [rootView amendLayoutBeforeMount:uiBlocks]; if (uiBlocks.count) { - [self addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { for (NativeRenderApplierBlock block in uiBlocks) { block(viewRegistry); } }]; } - [self addUIBlock:^(NativeRenderImpl *renderContext, __unused NSDictionary *viewRegistry) { - NativeRenderImpl *uiManager = (NativeRenderImpl *)renderContext; - NSSet> *nodes = [uiManager->_componentTransactionListeners copy]; - for (id node in nodes) { - [node nativeRenderComponentDidFinishTransaction]; + [self addUIBlock:^(HippyUIManager *uiManager, __unused NSDictionary *viewRegistry) { + NSSet> *nodes = [uiManager->_componentTransactionListeners copy]; + for (id node in nodes) { + [node hippyBridgeDidFinishTransaction]; } }]; [self flushUIBlocksOnRootNode:rootNode]; @@ -1480,7 +1469,7 @@ - (void)layoutAndMountOnRootNode:(std::weak_ptr)rootNode { - (void)setNeedsLayoutForRootNodeTag:(NSNumber *)tag { // If there is an active batch layout will happen when batch finished, so we will wait for that. // Otherwise we immidiately trigger layout. - auto rootNode = [_renderObjectRegistry rootNodeForTag:tag]; + auto rootNode = [_shadowViewRegistry rootNodeForTag:tag]; [self layoutAndMountOnRootNode:rootNode]; } @@ -1494,30 +1483,6 @@ - (NSDictionary *)mergeProps:(NSDictionary *)newProps oldProps:(NSDictionary *)o return tmpProps; } -- (void)addImageProviderClass:(Class)cls { - HPAssertParam(cls); - std::lock_guard lock(_imageProviderMutex); - if (!_imageProviders) { - _imageProviders = [NSMutableArray arrayWithCapacity:8]; - } - [_imageProviders addObject:cls]; -} -- (NSArray> *)imageProviderClasses { - std::lock_guard lock(_imageProviderMutex); - if (!_imageProviders) { - _imageProviders = [NSMutableArray arrayWithCapacity:8]; - } - return [_imageProviders copy]; -} - -- (void)setVFSUriLoader:(std::weak_ptr)loader { - _VFSUriLoader = loader; -} - -- (std::weak_ptr)VFSUriLoader { - return _VFSUriLoader; -} - - (void)setRootViewSizeChangedEvent:(std::function)cb { _rootViewSizeChangedCb = cb; } @@ -1527,7 +1492,7 @@ - (void)domEventDidHandle:(const std::string &)eventName forNode:(int32_t)tag on } #pragma mark Debug Methods -#if HP_DEBUG +#if HIPPY_DEBUG - (std::shared_ptr)domNodeForTag:(int32_t)dom_tag onRootNode:(int32_t)root_tag { auto find = _domNodesMap.find(root_tag); if (_domNodesMap.end() == find) { @@ -1548,3 +1513,18 @@ - (void)domEventDidHandle:(const std::string &)eventName forNode:(int32_t)tag on @end + +@implementation HippyBridge (HippyUIManager) + +- (HippyUIManager *)uiManager { + auto renderManager = [self renderManager]; + if (renderManager) { + auto nativeRenderManager = std::static_pointer_cast(renderManager); + return nativeRenderManager->GetHippyUIManager(); + } + return nil; +} + +@end + + diff --git a/renderer/native/ios/renderer/NativeRenderComponentProtocol.h b/renderer/native/ios/renderer/NativeRenderComponentProtocol.h deleted file mode 100644 index d24a9332be3..00000000000 --- a/renderer/native/ios/renderer/NativeRenderComponentProtocol.h +++ /dev/null @@ -1,81 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * NativeRender available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import -#import - -/** - * These block types can be used for mapping input event handlers from JS to view - * properties. Unlike JS method callbacks, these can be called multiple times. - */ -typedef void (^NativeRenderDirectEventBlock)(NSDictionary *body); - -/** - * Logical node in a tree of application components. Both `NativeRenderObject` and - * `UIView` conforms to this. Allows us to write utilities that reason about - * trees generally. - */ -@protocol NativeRenderComponentProtocol - -@property (nonatomic, copy) NSString *viewName; -@property (nonatomic, copy) NSDictionary *props; -@property (nonatomic, assign) CGRect frame; - -@property(nonatomic, strong) NSNumber *componentTag; -@property (nonatomic, strong) NSNumber *rootTag; -@property (nonatomic, copy) NSString *tagName; -@property(nonatomic, readwrite)__kindof id parentComponent; - -- (NSArray<__kindof id> *)subcomponents; - -- (void)insertNativeRenderSubview:(id)subview atIndex:(NSInteger)atIndex; -- (void)removeNativeRenderSubview:(id)subview; -- (void)moveNativeRenderSubview:(id)subview toIndex:(NSInteger)atIndex; -- (void)removeFromNativeRenderSuperview; -- (void)nativeRenderSetFrame:(CGRect)frame; -- (NSNumber *)componentTagAtPoint:(CGPoint)point; - -// View/NativeRenderObjectView is a root view -- (BOOL)isNativeRenderRootView; - -@optional - -/** - * Called each time props have been set. - * Not all props have to be set - NativeRender can set only changed ones. - * @param changedProps String names of all set props. - */ -- (void)didSetProps:(NSArray *)changedProps; - -/** - * Called each time subviews have been updated - */ -- (void)didUpdateNativeRenderSubviews; - -- (void)nativeRenderComponentDidFinishTransaction; - -@end - -// hippy use multiple of 10 as tag of root view -static inline BOOL NativeRenderIsRootView(NSNumber *componentTag) { - return componentTag.integerValue % 10 == 0; -} diff --git a/renderer/native/ios/renderer/NativeRenderDefines.h b/renderer/native/ios/renderer/NativeRenderDefines.h index 265890a18eb..7bad664813a 100644 --- a/renderer/native/ios/renderer/NativeRenderDefines.h +++ b/renderer/native/ios/renderer/NativeRenderDefines.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,39 +22,31 @@ #ifndef NativeRenderDefines_h #define NativeRenderDefines_h -#import "MacroDefines.h" +#import "HippyDefines.h" -@class NativeRenderImpl, UIView, NSDictionary; +@class HippyUIManager, UIView, NSDictionary; -#define NATIVE_RENDER_EXPORT_VIEW(js_name) \ - HP_EXTERN void NativeRenderRegisterView(Class); \ - +(NSString *)viewName { \ - return @ #js_name; \ - } \ - +(void)load { \ - NativeRenderRegisterView(self); \ - } -typedef void (^NativeRenderRenderUIBlock)(NativeRenderImpl *renderContext, NSDictionary *viewRegistry); +typedef void (^HippyViewManagerUIBlock)(HippyUIManager *uiManager, NSDictionary *viewRegistry); /** * Posted whenever a new root view is registered with NativeRenderUIManager. The userInfo property * will contain a NativeRenderUIManagerRootViewKey with the registered root view. */ -HP_EXTERN NSString *const NativeRenderUIManagerDidRegisterRootViewNotification; +HIPPY_EXTERN NSString *const NativeRenderUIManagerDidRegisterRootViewNotification; /** * Key for the root view property in the above notifications */ -HP_EXTERN NSString *const NativeRenderUIManagerRootViewTagKey; +HIPPY_EXTERN NSString *const NativeRenderUIManagerRootViewTagKey; /** * Key for Render UIManager */ -HP_EXTERN NSString *const NativeRenderUIManagerKey; +HIPPY_EXTERN NSString *const NativeRenderUIManagerKey; /** * Posted whenever endBatch is called */ -HP_EXTERN NSString *const NativeRenderUIManagerDidEndBatchNotification; +HIPPY_EXTERN NSString *const NativeRenderUIManagerDidEndBatchNotification; #endif /* NativeRenderDefines_h */ diff --git a/renderer/native/ios/renderer/NativeRenderManager.h b/renderer/native/ios/renderer/NativeRenderManager.h index 89043bc7e59..e1a1011905b 100644 --- a/renderer/native/ios/renderer/NativeRenderManager.h +++ b/renderer/native/ios/renderer/NativeRenderManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -28,7 +28,7 @@ #include "dom/render_manager.h" -@class UIView, NativeRenderImpl; +@class UIView, HippyUIManager; class VFSUriLoader; namespace hippy { @@ -37,7 +37,7 @@ class RootNode; } } -@protocol HPImageProviderProtocol; +@protocol HippyImageProviderProtocol; /** * NativeRenderManager is used to manager view creation, update and delete for Native UI @@ -46,7 +46,7 @@ class NativeRenderManager : public hippy::RenderManager ,public std::enable_shar public: NativeRenderManager(); - NativeRenderManager(NativeRenderImpl *uiManager): hippy::RenderManager("NativeRenderManager"), renderImpl_(uiManager){} + NativeRenderManager(HippyUIManager *uiManager): hippy::RenderManager("NativeRenderManager"), renderImpl_(uiManager){} ~NativeRenderManager(); @@ -190,20 +190,19 @@ class NativeRenderManager : public hippy::RenderManager ,public std::enable_shar */ void SetUICreationLazilyEnabled(bool enabled); - /** - * Image provider method - * Users adds or obtains image providers in the following methods - */ - void AddImageProviderClass(Class cls); - - NSArray> *GetImageProviderClasses(); - /** * Set vfs uri loader of CPP version * *@param loader vfs url loader instance */ void SetVFSUriLoader(std::shared_ptr loader); + + /** + * Set HippyBridge pointer to renderManager + * + *@param bridge HippyBridge instance + */ + void SetHippyBridge(HippyBridge *bridge); /** * Set root view size changed event callback @@ -213,14 +212,14 @@ class NativeRenderManager : public hippy::RenderManager ,public std::enable_shar void SetRootViewSizeChangedEvent(std::function cb); /** - * Get NativeRenderImpl variable + * Get HippyUIManager variable * - * @return A NativeRenderImpl instance + * @return A HippyUIManager instance */ - NativeRenderImpl *GetNativeRenderImpl(); + HippyUIManager *GetHippyUIManager(); private: - NativeRenderImpl *renderImpl_; + HippyUIManager *renderImpl_; }; #endif /* NativeRenderManager_h */ diff --git a/renderer/native/ios/renderer/NativeRenderManager.mm b/renderer/native/ios/renderer/NativeRenderManager.mm index 9aab83441ef..45cf4231e05 100644 --- a/renderer/native/ios/renderer/NativeRenderManager.mm +++ b/renderer/native/ios/renderer/NativeRenderManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" #import "NativeRenderManager.h" #import "NativeRenderObjectText.h" #import "RenderVsyncManager.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" #include "dom/dom_manager.h" #include "dom/layout_node.h" @@ -42,13 +42,13 @@ } void NativeRenderManager::Initialize() { - renderImpl_ = [[NativeRenderImpl alloc] initWithRenderManager:weak_from_this()]; + renderImpl_ = [[HippyUIManager alloc] initWithRenderManager:weak_from_this()]; } void NativeRenderManager::CreateRenderNode(std::weak_ptr root_node, std::vector> &&nodes) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ createRenderNodes:std::move(nodes) onRootNode:root_node]; } } @@ -56,7 +56,7 @@ void NativeRenderManager::UpdateRenderNode(std::weak_ptr root_node, std::vector>&& nodes) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ updateRenderNodes:std::move(nodes) onRootNode:root_node]; } } @@ -64,7 +64,7 @@ void NativeRenderManager::DeleteRenderNode(std::weak_ptr root_node, std::vector>&& nodes) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ deleteRenderNodesIds:std::move(nodes) onRootNode:root_node]; } } @@ -72,7 +72,7 @@ void NativeRenderManager::UpdateLayout(std::weak_ptr root_node, const std::vector>& nodes) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); using DomNodeUpdateInfoTuple = std::tuple; std::vector nodes_infos; nodes_infos.reserve(nodes.size()); @@ -92,7 +92,7 @@ int32_t to_pid, int32_t index) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ renderMoveViews:std::move(moved_ids) fromContainer:from_pid toContainer:to_pid @@ -104,7 +104,7 @@ void NativeRenderManager::MoveRenderNode(std::weak_ptr root_node, std::vector>&& nodes) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ renderMoveNodes:std::move(nodes) onRootNode:root_node]; } } @@ -112,7 +112,7 @@ void NativeRenderManager::EndBatch(std::weak_ptr root_node) { @autoreleasepool { HP_PERF_LOG("NativeRenderManager::EndBatch"); - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ batchOnRootNode:root_node]; HP_PERF_LOG("NativeRenderManager::EndBatch End"); @@ -131,7 +131,7 @@ std::weak_ptr dom_node, const std::string& name) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); auto node = dom_node.lock(); if (node) { int32_t tag = node->GetId(); @@ -144,7 +144,7 @@ std::weak_ptr dom_node, const std::string &name) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); auto node = dom_node.lock(); if (node) { int32_t node_id = node->GetId(); @@ -155,7 +155,7 @@ void NativeRenderManager::RemoveVSyncEventListener(std::weak_ptr root_node) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ removeVSyncEventOnRootNode:root_node]; } } @@ -166,7 +166,7 @@ const DomArgument& param, uint32_t cb) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); std::shared_ptr node = dom_node.lock(); if (node) { HippyValue hippy_value; @@ -181,70 +181,61 @@ void NativeRenderManager::RegisterExtraComponent(NSArray *extraComponents) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ registerExtraComponent:extraComponents]; } } void NativeRenderManager::RegisterRootView(UIView *view, std::weak_ptr root_node) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ registerRootView:view asRootNode:root_node]; } } void NativeRenderManager::UnregisterRootView(uint32_t id) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ unregisterRootViewFromTag:@(id)]; } } NSArray *NativeRenderManager::rootViews() { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); return [renderImpl_ rootViews]; } } void NativeRenderManager::SetDomManager(std::weak_ptr dom_manager) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); [renderImpl_ setDomManager:dom_manager]; } } void NativeRenderManager::SetUICreationLazilyEnabled(bool enabled) { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); renderImpl_.uiCreationLazilyEnabled = enabled; } -void NativeRenderManager::AddImageProviderClass(Class cls) { - @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); - [renderImpl_ addImageProviderClass:cls]; - } -} - -NSArray> *NativeRenderManager::GetImageProviderClasses() { - @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); - return [renderImpl_ imageProviderClasses]; - } -} - void NativeRenderManager::SetVFSUriLoader(std::shared_ptr loader) { @autoreleasepool { - HPAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); renderImpl_.VFSUriLoader = loader; } } +void NativeRenderManager::SetHippyBridge(HippyBridge *bridge) { + HippyAssert(renderImpl_, @"renderImpl_ is null, did you forget to call Initialize()?"); + renderImpl_.bridge = bridge; +} + void NativeRenderManager::SetRootViewSizeChangedEvent(std::function cb) { [renderImpl_ setRootViewSizeChangedEvent:cb]; } -NativeRenderImpl *NativeRenderManager::GetNativeRenderImpl() { +HippyUIManager *NativeRenderManager::GetHippyUIManager() { return renderImpl_; } diff --git a/renderer/native/ios/renderer/NativeRenderObjectRootView.h b/renderer/native/ios/renderer/NativeRenderObjectRootView.h index 0d937759ec3..ac4b9df4930 100644 --- a/renderer/native/ios/renderer/NativeRenderObjectRootView.h +++ b/renderer/native/ios/renderer/NativeRenderObjectRootView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,9 +20,9 @@ * limitations under the License. */ -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" -@interface NativeRenderObjectRootView : NativeRenderObjectView +@interface NativeRenderObjectRootView : HippyShadowView /** * Calculate all views whose frame needs updating after layout has been calculated. diff --git a/renderer/native/ios/renderer/NativeRenderObjectRootView.mm b/renderer/native/ios/renderer/NativeRenderObjectRootView.mm index c63fe0b0b76..33b65c3a469 100644 --- a/renderer/native/ios/renderer/NativeRenderObjectRootView.mm +++ b/renderer/native/ios/renderer/NativeRenderObjectRootView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,8 +21,8 @@ */ #import "NativeRenderObjectRootView.h" -#import "HPToolUtils.h" -#import "HPI18nUtils.h" +#import "HippyUtils.h" +#import "HippyI18nUtils.h" @implementation NativeRenderObjectRootView @@ -30,7 +30,7 @@ - (void)applySizeConstraints { } - (void)amendLayoutBeforeMount:(NSMutableSet *)blocks { - for (NativeRenderObjectView *renderObject in self.subcomponents) { + for (HippyShadowView *renderObject in self.subcomponents) { [renderObject amendLayoutBeforeMount:blocks]; } } diff --git a/renderer/native/ios/renderer/NativeRenderRootView.h b/renderer/native/ios/renderer/NativeRenderRootView.h deleted file mode 100644 index 4d99fc259b3..00000000000 --- a/renderer/native/ios/renderer/NativeRenderRootView.h +++ /dev/null @@ -1,48 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * NativeRender available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import -#import "HPInvalidating.h" - -/** - * Native view used to host Hippy-managed views within the app. Can be used just - * like any ordinary UIView. You can have multiple HippyRootViews on screen at - * once, all controlled by the same JavaScript application. - */ -@interface NativeRenderRootView : UIView - -/** - * The backing view controller of the root view. - */ -@property (nonatomic, weak) UIViewController *nativeRenderViewController; - -- (void)contentDidAppear; - -/** - * Timings for hiding the loading view after the content has loaded. Both of - * these values default to 0.25 seconds. - */ -@property (nonatomic, assign) NSTimeInterval loadingViewFadeDelay; -@property (nonatomic, assign) NSTimeInterval loadingViewFadeDuration; -@property (nonatomic, assign) Class customTouchHandler; - -@end diff --git a/renderer/native/ios/renderer/NativeRenderRootView.m b/renderer/native/ios/renderer/NativeRenderRootView.m deleted file mode 100644 index 871ad22a64a..00000000000 --- a/renderer/native/ios/renderer/NativeRenderRootView.m +++ /dev/null @@ -1,81 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * Hippy available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import "NativeRenderRootView.h" -#import "HPAsserts.h" -#import "NativeRenderView.h" -#import "UIView+NativeRender.h" -#import "NativeRenderDefines.h" - -#include - -NSNumber *AllocRootViewTag(void) { - static NSString * const token = @"allocateRootTag"; - @synchronized (token) { - static NSUInteger rootTag = 0; - return @(rootTag += 10); - } -} - -@interface NativeRenderRootView () { - BOOL _contentHasAppeared; -} - -@property (readwrite, nonatomic, assign) CGSize intrinsicSize; - -@end - -@implementation NativeRenderRootView - -- (UIViewController *)nativeRenderViewController { - return _nativeRenderViewController?:[super nativeRenderViewController]; -} - -- (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { - [super insertNativeRenderSubview:subview atIndex:atIndex]; - if (!_contentHasAppeared) { - _contentHasAppeared = YES; - [self contentDidAppear]; - [[NSNotificationCenter defaultCenter] postNotificationName:kRootViewDidAddContent object:nil userInfo:@{ - kRootViewKey: self - }]; - } -} - -- (NSNumber *)componentTag { - HPAssertMainQueue(); - if (!super.componentTag) { - self.componentTag = AllocRootViewTag(); - } - return super.componentTag; -} - -- (void)contentDidAppear { -} - -- (void)dealloc -{ - [[NSNotificationCenter defaultCenter] removeObserver:self]; - HPLogInfo(@"[Hippy_OC_Log][Life_Circle],HippyRootView dealloc %p", self); -} - -@end diff --git a/renderer/native/ios/renderer/NativeRenderScrollProtocol.h b/renderer/native/ios/renderer/NativeRenderScrollProtocol.h index 1f5b99e9e99..07294c07581 100644 --- a/renderer/native/ios/renderer/NativeRenderScrollProtocol.h +++ b/renderer/native/ios/renderer/NativeRenderScrollProtocol.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/RenderVsyncManager.h b/renderer/native/ios/renderer/RenderVsyncManager.h index a39ac925eb3..bff09c928be 100644 --- a/renderer/native/ios/renderer/RenderVsyncManager.h +++ b/renderer/native/ios/renderer/RenderVsyncManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/RenderVsyncManager.m b/renderer/native/ios/renderer/RenderVsyncManager.m index 69a92c2906b..0d5fee16f1c 100644 --- a/renderer/native/ios/renderer/RenderVsyncManager.m +++ b/renderer/native/ios/renderer/RenderVsyncManager.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/UIView+Render.h b/renderer/native/ios/renderer/UIView+Render.h index a32859744dc..a2b77e9bfa3 100644 --- a/renderer/native/ios/renderer/UIView+Render.h +++ b/renderer/native/ios/renderer/UIView+Render.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -24,11 +24,11 @@ NS_ASSUME_NONNULL_BEGIN -@class NativeRenderImpl; +@class HippyUIManager; @interface UIView (Render) -- (NativeRenderImpl *)renderImpl; +- (HippyUIManager *)renderImpl; @end diff --git a/renderer/native/ios/renderer/UIView+Render.mm b/renderer/native/ios/renderer/UIView+Render.mm index e9549d58729..79c77f641e7 100644 --- a/renderer/native/ios/renderer/UIView+Render.mm +++ b/renderer/native/ios/renderer/UIView+Render.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,7 +21,7 @@ */ #import "UIView+Render.h" -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" #import "NSObject+Render.h" #import "NativeRenderManager.h" @@ -29,11 +29,11 @@ @implementation UIView (Render) -- (NativeRenderImpl *)renderImpl { +- (HippyUIManager *)renderImpl { auto renderManager = [self renderManager].lock(); if (renderManager) { auto nativeRenderManager = std::static_pointer_cast(renderManager); - return nativeRenderManager->GetNativeRenderImpl(); + return nativeRenderManager->GetHippyUIManager(); } return nil; } diff --git a/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefresh.h b/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefresh.h index c7c9a258fdb..2a330f66acc 100644 --- a/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefresh.h +++ b/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefresh.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,13 +20,13 @@ * limitations under the License. */ -#import "NativeRenderRefresh.h" -#import "NativeRenderComponentProtocol.h" +#import "HippyRefresh.h" +#import "HippyComponent.h" -@interface NativeRenderFooterRefresh : NativeRenderRefresh +@interface NativeRenderFooterRefresh : HippyRefresh @property (nonatomic, assign) BOOL refreshStick; -@property (nonatomic, copy) NativeRenderDirectEventBlock onFooterReleased; -@property (nonatomic, copy) NativeRenderDirectEventBlock onFooterPulling; +@property (nonatomic, copy) HippyDirectEventBlock onFooterReleased; +@property (nonatomic, copy) HippyDirectEventBlock onFooterPulling; @end diff --git a/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefresh.m b/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefresh.m index f3d3d19fb34..5a253991269 100644 --- a/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefresh.m +++ b/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefresh.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -47,7 +47,7 @@ - (void)observeValueForKeyPath:(NSString *)keyPath - (void)scrollViewDidScroll { if (_scrollView && _scrollView.contentSize.height > 0) { - if (self.onFooterPulling && NativeRenderRefreshStatusStartLoading != [self status] && NativeRenderRefreshStatusFinishLoading != [self status]) { + if (self.onFooterPulling && HippyRefreshStatusStartLoading != [self status] && HippyRefreshStatusFinishLoading != [self status]) { CGFloat offset = _scrollView.contentOffset.y; if (offset >= 0) { self.onFooterPulling(@{ @"contentOffset": @(offset) }); @@ -60,24 +60,24 @@ - (void)scrollViewDidEndDragging { if (_scrollView) { CGFloat offset = _scrollView.contentOffset.y; if (offset > _scrollView.contentSize.height - CGRectGetHeight(_scrollView.bounds) + CGRectGetHeight(self.bounds)) { - self.status = NativeRenderRefreshStatusStartLoading; + self.status = HippyRefreshStatusStartLoading; } } } -- (void)setStatus:(NativeRenderRefreshStatus)status { +- (void)setStatus:(HippyRefreshStatus)status { if (_status == status) { return; } switch (status) { - case NativeRenderRefreshStatusIdle: { + case HippyRefreshStatusIdle: { [UIView animateWithDuration:.2f animations:^{ UIEdgeInsets insets = self.scrollView.contentInset; self.scrollView.contentInset = UIEdgeInsetsMake(insets.top, insets.left, 0, insets.right); } completion:^(BOOL finished) { }]; } break; - case NativeRenderRefreshStatusStartLoading: { + case HippyRefreshStatusStartLoading: { CGFloat height = CGRectGetHeight(self.bounds); if (_refreshStick) { CGFloat currentOffset = _scrollView.contentOffset.y; @@ -94,7 +94,7 @@ - (void)setStatus:(NativeRenderRefreshStatus)status { } }]; } break; - case NativeRenderRefreshStatusFinishLoading: { + case HippyRefreshStatusFinishLoading: { } break; default: break; @@ -111,7 +111,7 @@ - (void)refresh { = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.contentInset.bottom); [self.scrollView setContentOffset:bottomOffset animated:YES]; } completion:^(BOOL finished) { - self.status = NativeRenderRefreshStatusStartLoading; + self.status = HippyRefreshStatusStartLoading; }]; } diff --git a/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefreshManager.h b/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefreshManager.h index 1f9c70131c6..482819adc04 100644 --- a/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefreshManager.h +++ b/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefreshManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderFooterRefreshManager : NativeRenderViewManager +@interface NativeRenderFooterRefreshManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefreshManager.mm b/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefreshManager.mm index 90bfe023604..c4a6d79b374 100644 --- a/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefreshManager.mm +++ b/renderer/native/ios/renderer/component/footerrefresh/NativeRenderFooterRefreshManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,33 +22,33 @@ #import "NativeRenderFooterRefreshManager.h" #import "NativeRenderFooterRefresh.h" -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" @implementation NativeRenderFooterRefreshManager -NATIVE_RENDER_EXPORT_VIEW(PullFooterView); +HIPPY_EXPORT_MODULE(PullFooterView); -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(refreshStick, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onFooterReleased, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onFooterPulling, NativeRenderDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(refreshStick, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(onFooterReleased, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onFooterPulling, HippyDirectEventBlock) -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(collapsePullFooter:(nonnull NSNumber *)reactTag) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderRefresh *refreshView = viewRegistry[reactTag]; +HIPPY_EXPORT_METHOD(collapsePullFooter:(nonnull NSNumber *)reactTag) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { + HippyRefresh *refreshView = viewRegistry[reactTag]; [refreshView refreshFinish]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(collapsePullFooterWithOptions:(nonnull NSNumber *)reactTag options:(NSDictionary *)options) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderRefresh *refreshView = viewRegistry[reactTag]; +HIPPY_EXPORT_METHOD(collapsePullFooterWithOptions:(nonnull NSNumber *)reactTag options:(NSDictionary *)options) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { + HippyRefresh *refreshView = viewRegistry[reactTag]; [refreshView refreshFinishWithOption:options]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(expandPullFooter:(nonnull NSNumber *)reactTag) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderRefresh *refreshView = viewRegistry[reactTag]; +HIPPY_EXPORT_METHOD(expandPullFooter:(nonnull NSNumber *)reactTag) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { + HippyRefresh *refreshView = viewRegistry[reactTag]; [refreshView refresh]; }]; } diff --git a/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefresh.h b/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefresh.h index a9ea692701a..d88aa6bcf9d 100644 --- a/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefresh.h +++ b/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefresh.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,12 +22,12 @@ #import -#import "NativeRenderRefresh.h" -#import "NativeRenderComponentProtocol.h" +#import "HippyRefresh.h" +#import "HippyComponent.h" -@interface NativeRenderHeaderRefresh : NativeRenderRefresh +@interface NativeRenderHeaderRefresh : HippyRefresh -@property (nonatomic, copy) NativeRenderDirectEventBlock onHeaderReleased; -@property (nonatomic, copy) NativeRenderDirectEventBlock onHeaderPulling; +@property (nonatomic, copy) HippyDirectEventBlock onHeaderReleased; +@property (nonatomic, copy) HippyDirectEventBlock onHeaderPulling; @end diff --git a/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefresh.m b/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefresh.m index 48fe3d0ccd1..71f356fcea7 100644 --- a/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefresh.m +++ b/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefresh.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -36,7 +36,7 @@ - (void)setFrame:(CGRect)frame { - (void)scrollViewDidScroll { if (_scrollView) { - if (self.onHeaderPulling && NativeRenderRefreshStatusStartLoading != [self status] && NativeRenderRefreshStatusFinishLoading != [self status]) { + if (self.onHeaderPulling && HippyRefreshStatusStartLoading != [self status] && HippyRefreshStatusFinishLoading != [self status]) { CGFloat offset = _scrollView.contentOffset.y; if (offset <= 0) { self.onHeaderPulling(@{ @"contentOffset": @(-offset) }); @@ -44,7 +44,7 @@ - (void)scrollViewDidScroll { } } // Section cell will stick in wrong position while header is still refresh. in this scenario,the scrollview inset need to be reset. - if ([self status] == NativeRenderRefreshStatusStartLoading || [self status] == NativeRenderRefreshStatusFinishLoading) { + if ([self status] == HippyRefreshStatusStartLoading || [self status] == HippyRefreshStatusFinishLoading) { [self resetInset]; } } @@ -63,23 +63,23 @@ - (void)resetInset - (void)scrollViewDidEndDragging { if (_scrollView && -_scrollView.contentOffset.y > CGRectGetHeight(self.bounds)) { - self.status = NativeRenderRefreshStatusStartLoading; + self.status = HippyRefreshStatusStartLoading; } } -- (void)setStatus:(NativeRenderRefreshStatus)status { +- (void)setStatus:(HippyRefreshStatus)status { if (_status == status) { return; } switch (status) { - case NativeRenderRefreshStatusIdle: { + case HippyRefreshStatusIdle: { [UIView animateWithDuration:.2f animations:^{ UIEdgeInsets insets = self.scrollView.contentInset; self.scrollView.contentInset = UIEdgeInsetsMake(0, insets.left, insets.bottom, insets.right); } completion:^(BOOL finished) { }]; } break; - case NativeRenderRefreshStatusStartLoading: { + case HippyRefreshStatusStartLoading: { CGFloat height = CGRectGetHeight(self.bounds); [UIView animateWithDuration:.2f animations:^{ UIEdgeInsets insets = self.scrollView.contentInset; diff --git a/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefreshManager.h b/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefreshManager.h index 5aa9b921b99..885bfa41f2c 100644 --- a/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefreshManager.h +++ b/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefreshManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderHeaderRefreshManager : NativeRenderViewManager +@interface NativeRenderHeaderRefreshManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefreshManager.mm b/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefreshManager.mm index 6a25ea60f5a..a468d9f43d5 100644 --- a/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefreshManager.mm +++ b/renderer/native/ios/renderer/component/headerrefresh/NativeRenderHeaderRefreshManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,32 +22,32 @@ #import "NativeRenderHeaderRefreshManager.h" #import "NativeRenderHeaderRefresh.h" -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" @implementation NativeRenderHeaderRefreshManager -NATIVE_RENDER_EXPORT_VIEW(PullHeaderView); +HIPPY_EXPORT_MODULE(PullHeaderView); -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onHeaderReleased, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onHeaderPulling, NativeRenderDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onHeaderReleased, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onHeaderPulling, HippyDirectEventBlock) -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(expandPullHeader:(nonnull NSNumber *)reactTag) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderRefresh *refreshView = viewRegistry[reactTag]; +HIPPY_EXPORT_METHOD(expandPullHeader:(nonnull NSNumber *)reactTag) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { + HippyRefresh *refreshView = viewRegistry[reactTag]; [refreshView refresh]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(collapsePullHeader:(nonnull NSNumber *)reactTag) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderRefresh *refreshView = viewRegistry[reactTag]; +HIPPY_EXPORT_METHOD(collapsePullHeader:(nonnull NSNumber *)reactTag) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { + HippyRefresh *refreshView = viewRegistry[reactTag]; [refreshView refreshFinish]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(collapsePullHeaderWithOptions:(nonnull NSNumber *)reactTag options:(NSDictionary *)options) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderRefresh *refreshView = viewRegistry[reactTag]; +HIPPY_EXPORT_METHOD(collapsePullHeaderWithOptions:(nonnull NSNumber *)reactTag options:(NSDictionary *)options) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { + HippyRefresh *refreshView = viewRegistry[reactTag]; [refreshView refreshFinishWithOption:options]; }]; } diff --git a/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImage.h b/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImage.h index b7ac6c4c542..b91625b0eae 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImage.h +++ b/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImage.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,7 +21,7 @@ */ #import -#import "HPImageProviderProtocol.h" +#import "HippyImageProviderProtocol.h" #import "NativeRenderAnimatedImageView.h" extern const NSTimeInterval kAnimatedImageDelayTimeIntervalMinimum; @@ -56,11 +56,11 @@ extern const NSTimeInterval kAnimatedImageDelayTimeIntervalMinimum; - (UIImage *)imageAtIndex:(NSUInteger)index; -- (instancetype)initWithAnimatedImageProvider:(id)imageProvider; -- (instancetype)initWithAnimatedImageProvider:(id)imageProvider +- (instancetype)initWithAnimatedImageProvider:(id)imageProvider; +- (instancetype)initWithAnimatedImageProvider:(id)imageProvider optimalFrameCacheSize:(NSUInteger)optimalFrameCacheSize predrawingEnabled:(BOOL)isPredrawingEnabled; -+ (instancetype)animatedImageWithAnimatedImageProvider:(id)imageProvider; ++ (instancetype)animatedImageWithAnimatedImageProvider:(id)imageProvider; // On success, the initializers return an `NativeRenderAnimatedImage` with all fields initialized, on failure they return `nil` and an error will be logged. - (instancetype)initWithAnimatedGIFData:(NSData *)data; @@ -71,7 +71,7 @@ extern const NSTimeInterval kAnimatedImageDelayTimeIntervalMinimum; + (instancetype)animatedImageWithGIFData:(NSData *)data; @property (nonatomic, strong, readonly) NSData *data; // The data the receiver was initialized with; read-only -@property (nonatomic, strong, readonly) id imageProvider; +@property (nonatomic, strong, readonly) id imageProvider; @end diff --git a/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImage.m b/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImage.m index 64de086e225..5eca5aa9c31 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImage.m +++ b/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImage.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -73,7 +73,7 @@ @interface NativeRenderAnimatedImage () // We are lying about the actual type here to gain static type checking and eliminate casts. // The actual type of the object is `NativeRenderWeakProxy`. @property (nonatomic, strong, readonly) NativeRenderAnimatedImage *weakProxy; -@property (nonatomic, strong) id imageProvider; +@property (nonatomic, strong) id imageProvider; @end @@ -165,11 +165,11 @@ - (instancetype)init { return animatedImage; } -- (instancetype)initWithAnimatedImageProvider:(id)imageProvider { +- (instancetype)initWithAnimatedImageProvider:(id)imageProvider { return [self initWithAnimatedImageProvider:imageProvider optimalFrameCacheSize:9 predrawingEnabled:NO]; } -- (instancetype)initWithAnimatedImageProvider:(id)imageProvider +- (instancetype)initWithAnimatedImageProvider:(id)imageProvider optimalFrameCacheSize:(NSUInteger)optimalFrameCacheSize predrawingEnabled:(BOOL)isPredrawingEnabled { if (nil == imageProvider) { @@ -302,7 +302,7 @@ - (instancetype)initWithAnimatedImageProvider:(id)image return self; } -+ (instancetype)animatedImageWithAnimatedImageProvider:(id)imageProvider { ++ (instancetype)animatedImageWithAnimatedImageProvider:(id)imageProvider { NativeRenderAnimatedImage *animatedImage = [[NativeRenderAnimatedImage alloc] initWithAnimatedImageProvider:imageProvider]; return animatedImage; } diff --git a/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImageView.h b/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImageView.h index e945cd5097a..ee736cd90fa 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImageView.h +++ b/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImageView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImageView.m b/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImageView.m index 885f54cb28b..7c860bf3fa2 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImageView.m +++ b/renderer/native/ios/renderer/component/image/NativeRenderAnimatedImageView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/image/NativeRenderImageCache.h b/renderer/native/ios/renderer/component/image/NativeRenderImageCache.h index 52cf3b18d72..5e4726efc4c 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderImageCache.h +++ b/renderer/native/ios/renderer/component/image/NativeRenderImageCache.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/image/NativeRenderImageCache.m b/renderer/native/ios/renderer/component/image/NativeRenderImageCache.m index 94fc99998f3..6d30adf5944 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderImageCache.m +++ b/renderer/native/ios/renderer/component/image/NativeRenderImageCache.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/image/NativeRenderImageView+NativeRenderTouchesImplementation.h b/renderer/native/ios/renderer/component/image/NativeRenderImageView+NativeRenderTouchesImplementation.h index c025e5b1e6a..ea89a85fcb3 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderImageView+NativeRenderTouchesImplementation.h +++ b/renderer/native/ios/renderer/component/image/NativeRenderImageView+NativeRenderTouchesImplementation.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/image/NativeRenderImageView+NativeRenderTouchesImplementation.mm b/renderer/native/ios/renderer/component/image/NativeRenderImageView+NativeRenderTouchesImplementation.mm index d3409ab34bb..590ccf41198 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderImageView+NativeRenderTouchesImplementation.mm +++ b/renderer/native/ios/renderer/component/image/NativeRenderImageView+NativeRenderTouchesImplementation.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,7 +22,7 @@ #import "NativeRenderImageView+NativeRenderTouchesImplementation.h" #import "UIView+DomEvent.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "UIEvent+TouchResponder.h" #import "objc/runtime.h" diff --git a/renderer/native/ios/renderer/component/image/NativeRenderImageView.h b/renderer/native/ios/renderer/component/image/NativeRenderImageView.h index f551a5e6b55..a1be1f2e6ef 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderImageView.h +++ b/renderer/native/ios/renderer/component/image/NativeRenderImageView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,10 +21,10 @@ */ #import -#import "NativeRenderComponentProtocol.h" -#import "HPConvert.h" +#import "HippyComponent.h" +#import "HippyConvert.h" #import "NativeRenderAnimatedImageView.h" -#import "HPImageProviderProtocol.h" +#import "HippyImageProviderProtocol.h" @class NativeRenderImageView; @@ -32,11 +32,11 @@ NSData *_animatedImageData; NSString *_url; __weak NativeRenderImageView *_imageView; - id _imageProvider; + id _imageProvider; } - (id)initWithAnimatedImageData:(NSData *)data imageView:(NativeRenderImageView *)imageView imageURL:(NSString *)url; -- (id)initWithAnimatedImageProvider:(id)imageProvider imageView:(NativeRenderImageView *)imageView imageURL:(NSString *)url; +- (id)initWithAnimatedImageProvider:(id)imageProvider imageView:(NativeRenderImageView *)imageView imageURL:(NSString *)url; @end @@ -69,24 +69,24 @@ typedef NS_ENUM(NSInteger, NativeRenderShapeMode) { @property (nonatomic, assign) CGFloat borderRadius; @property (nonatomic, assign) NativeRenderShapeMode shape; -@property (nonatomic, copy) NativeRenderDirectEventBlock onLoadStart; -@property (nonatomic, copy) NativeRenderDirectEventBlock onProgress; -@property (nonatomic, copy) NativeRenderDirectEventBlock onError; -@property (nonatomic, copy) NativeRenderDirectEventBlock onLoad; -@property (nonatomic, copy) NativeRenderDirectEventBlock onLoadEnd; +@property (nonatomic, copy) HippyDirectEventBlock onLoadStart; +@property (nonatomic, copy) HippyDirectEventBlock onProgress; +@property (nonatomic, copy) HippyDirectEventBlock onError; +@property (nonatomic, copy) HippyDirectEventBlock onLoad; +@property (nonatomic, copy) HippyDirectEventBlock onLoadEnd; - (void)reloadImage; - (void)updateImage:(UIImage *)image; -- (void)setImageProvider:(id)imageProvider; +- (void)setImageProvider:(id)imageProvider; - (void)clearImageIfDetached; - (BOOL)needsUpdateCornerRadiusManully; @end -@interface HPConvert (NativeRenderResizeMode) +@interface HippyConvert (NativeRenderResizeMode) + (NativeRenderResizeMode)NativeRenderResizeMode:(id)json; + (NativeRenderShapeMode)NativeRenderShapeMode:(id)json; diff --git a/renderer/native/ios/renderer/component/image/NativeRenderImageView.m b/renderer/native/ios/renderer/component/image/NativeRenderImageView.m index fc9e65ac832..c983bd9d716 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderImageView.m +++ b/renderer/native/ios/renderer/component/image/NativeRenderImageView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,8 +22,8 @@ #import -#import "HPAsserts.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" #import "NativeRenderImageView.h" #import "NativeRenderAnimatedImage.h" #import "UIView+MountEvent.h" @@ -202,7 +202,7 @@ @interface NativeRenderImageView () { BOOL _needsUpdateBorderRadiusManully; BOOL _needsReloadImage; BOOL _needsUpdateImage; - id _imageProvider; + id _imageProvider; } @property (nonatomic) NativeRenderAnimatedImageOperation *animatedImageOperation; @@ -341,7 +341,7 @@ - (void)setRenderingMode:(UIImageRenderingMode)renderingMode { } } -- (void)setImageProvider:(id)imageProvider { +- (void)setImageProvider:(id)imageProvider { if (_imageProvider != imageProvider) { _imageProvider = imageProvider; } @@ -448,15 +448,15 @@ - (void)loadImage:(UIImage *)image url:(NSString *)url error:(NSError *)error ne NSError *error = nil; UIImage *blurredImage = NativeRenderBlurredImageWithRadiusv(image, br, &error); if (error) { - NSError *finalError = HPErrorFromErrorAndModuleName(error, @"unknown"); - HPFatal(finalError, nil); + NSError *finalError = HippyErrorFromErrorAndModuleName(error, @"unknown"); + HippyFatal(finalError); } - HPExecuteOnMainQueue(^{ + HippyExecuteOnMainQueue(^{ setImageBlock(blurredImage); }); }); } else { - HPExecuteOnMainQueue(^{ + HippyExecuteOnMainQueue(^{ setImageBlock(image); }); } @@ -529,24 +529,24 @@ - (void)updateCornerRadius { } if ([self needsUpdateCornerRadiusManully] && ![self isAllCornerRadiussEqualToCornerRadius]) { CGRect contentRect = self.bounds; -#ifdef HPLog +#ifdef HippyLog CGFloat width = CGRectGetWidth(contentRect); CGFloat height = CGRectGetHeight(contentRect); BOOL flag1 = _borderTopLeftRadius <= MIN(width, height) / 2; if (!flag1) { - HPLog(@"[warning] _borderTopLeftRadius must be shorter than width / 2"); + HippyLog(@"[warning] _borderTopLeftRadius must be shorter than width / 2"); } BOOL flag2 = _borderTopRightRadius <= MIN(width, height) / 2; if (!flag2) { - HPLog(@"[warning] _borderTopRightRadius must be shorter than width / 2"); + HippyLog(@"[warning] _borderTopRightRadius must be shorter than width / 2"); } BOOL flag3 = _borderBottomLeftRadius <= MIN(width, height) / 2; if (!flag3) { - HPLog(@"[warning] _borderBottomLeftRadius must be shorter than width / 2"); + HippyLog(@"[warning] _borderBottomLeftRadius must be shorter than width / 2"); } BOOL flag4 = _borderBottomRightRadius <= MIN(width, height) / 2; if (!flag4) { - HPLog(@"[warning] _borderBottomRightRadius must be shorter than width / 2"); + HippyLog(@"[warning] _borderBottomRightRadius must be shorter than width / 2"); } #endif @@ -567,7 +567,7 @@ - (void)updateCornerRadius { } else { //radius must be smaller than MIN(self.frame.size.width, self.frame.size.height) / 2.0 CGFloat minOfRadius = MIN(self.frame.size.width, self.frame.size.height) / 2.0f; - double radius = HPZeroIfNaN(MIN(minOfRadius, _borderRadius)); + double radius = HippyZeroIfNaN(MIN(minOfRadius, _borderRadius)); self.layer.mask = nil; self.layer.cornerRadius = radius; } @@ -668,7 +668,7 @@ - (BorderRadiusStruct)properBorderRadius { @end -@implementation HPConvert (NativeRenderResizeMode) +@implementation HippyConvert (NativeRenderResizeMode) HP_ENUM_CONVERTER(NativeRenderResizeMode, (@{ @"cover": @(NativeRenderResizeModeCover), @@ -688,7 +688,7 @@ @implementation HPConvert (NativeRenderResizeMode) @implementation NativeRenderAnimatedImageOperation -- (id)initWithAnimatedImageProvider:(id)imageProvider imageView:(NativeRenderImageView *)imageView imageURL:(NSString *)url { +- (id)initWithAnimatedImageProvider:(id)imageProvider imageView:(NativeRenderImageView *)imageView imageURL:(NSString *)url { self = [super init]; if (self) { _imageProvider = imageProvider; diff --git a/renderer/native/ios/renderer/component/image/NativeRenderImageViewManager.h b/renderer/native/ios/renderer/component/image/NativeRenderImageViewManager.h index bb939db60aa..417a8a65226 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderImageViewManager.h +++ b/renderer/native/ios/renderer/component/image/NativeRenderImageViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderImageViewManager : NativeRenderViewManager +@interface NativeRenderImageViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/image/NativeRenderImageViewManager.mm b/renderer/native/ios/renderer/component/image/NativeRenderImageViewManager.mm index 94bc43e9052..603048f7b2f 100644 --- a/renderer/native/ios/renderer/component/image/NativeRenderImageViewManager.mm +++ b/renderer/native/ios/renderer/component/image/NativeRenderImageViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "HPAsserts.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" #import "NativeRenderImageViewManager.h" #import "NativeRenderImageView.h" -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" #import "TypeConverter.h" #include "VFSUriLoader.h" @@ -36,26 +36,26 @@ @interface NativeRenderImageViewManager () { @implementation NativeRenderImageViewManager -NATIVE_RENDER_EXPORT_VIEW(Image); +HIPPY_EXPORT_MODULE(Image); -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(blurRadius, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(capInsets, UIEdgeInsets) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(resizeMode, NativeRenderResizeMode) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onLoadStart, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onProgress, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onError, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onPartialLoad, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onLoad, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onLoadEnd, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(downSample, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(shape, NativeRenderShapeMode) -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(src, NSString, NativeRenderImageView) { - NSString *path = [HPConvert NSString:json]; +HIPPY_EXPORT_VIEW_PROPERTY(blurRadius, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(capInsets, UIEdgeInsets) +HIPPY_EXPORT_VIEW_PROPERTY(resizeMode, NativeRenderResizeMode) +HIPPY_EXPORT_VIEW_PROPERTY(onLoadStart, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onProgress, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onError, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onPartialLoad, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onLoad, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onLoadEnd, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(downSample, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(shape, NativeRenderShapeMode) +HIPPY_CUSTOM_VIEW_PROPERTY(src, NSString, NativeRenderImageView) { + NSString *path = [HippyConvert NSString:json]; [self loadImageSource:path forView:view]; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(source, NSArray, NativeRenderImageView) { - NSArray *pathSources = [HPConvert NSArray:json]; +HIPPY_CUSTOM_VIEW_PROPERTY(source, NSArray, NativeRenderImageView) { + NSArray *pathSources = [HippyConvert NSArray:json]; if ([pathSources isKindOfClass:[NSArray class]]) { NSDictionary *dicSource = [pathSources firstObject]; NSString *path = dicSource[@"uri"]; @@ -69,21 +69,23 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderImageView *)view { } NSString *standardizeAssetUrlString = path; __weak NativeRenderImageView *weakView = view; - auto loader = [[self renderImpl] VFSUriLoader].lock(); + auto loader = [self.bridge.uiManager VFSUriLoader].lock(); if (!loader) { return; } + __weak __typeof(self)weakSelf = self; loader->RequestUntrustedContent(path, nil, nil, ^(NSData *data, NSURLResponse *response, NSError *error) { - NativeRenderImpl *renderImpl = self.renderImpl; - id imageProvider = nil; + __strong __typeof(weakSelf)strongSelf = weakSelf; + HippyUIManager *renderImpl = strongSelf.bridge.uiManager; + id imageProvider = nil; if (renderImpl) { - for (Class cls in [renderImpl imageProviderClasses]) { + for (Class cls in [strongSelf.bridge imageProviderClasses]) { if ([cls canHandleData:data]) { imageProvider = [[(Class)cls alloc] init]; break; } } - HPAssert(imageProvider, @"Image Provider is required"); + HippyAssert(imageProvider, @"Image Provider is required"); imageProvider.imageDataPath = standardizeAssetUrlString; [imageProvider setImageData:data]; dispatch_async(dispatch_get_main_queue(), ^{ @@ -97,20 +99,20 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderImageView *)view { }); } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(tintColor, UIColor, NativeRenderImageView) { - view.tintColor = [HPConvert UIColor:json] ?: defaultView.tintColor; +HIPPY_CUSTOM_VIEW_PROPERTY(tintColor, UIColor, NativeRenderImageView) { + view.tintColor = [HippyConvert UIColor:json] ?: defaultView.tintColor; view.renderingMode = json ? UIImageRenderingModeAlwaysTemplate : defaultView.renderingMode; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(defaultSource, NSString, NativeRenderImageView) { - NSString *source = [HPConvert NSString:json]; +HIPPY_CUSTOM_VIEW_PROPERTY(defaultSource, NSString, NativeRenderImageView) { + NSString *source = [HippyConvert NSString:json]; [self loadImageSource:source forView:view]; } #define NATIVE_RENDER_VIEW_BORDER_RADIUS_PROPERTY(SIDE) \ - NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(border##SIDE##Radius, CGFloat, NativeRenderImageView) { \ + HIPPY_CUSTOM_VIEW_PROPERTY(border##SIDE##Radius, CGFloat, NativeRenderImageView) { \ if ([view respondsToSelector:@selector(setBorder##SIDE##Radius:)]) { \ - view.border##SIDE##Radius = json ? [HPConvert CGFloat:json] : defaultView.border##SIDE##Radius; \ + view.border##SIDE##Radius = json ? [HippyConvert CGFloat:json] : defaultView.border##SIDE##Radius; \ } \ } diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemView.h b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemView.h index 6904615c552..91a52da240f 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemView.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,9 +22,9 @@ #import #import "NativeRenderBaseListViewCell.h" -#import "NativeRenderView.h" +#import "HippyView.h" -@interface NativeRenderBaseListItemView : NativeRenderView +@interface NativeRenderBaseListItemView : HippyView @property (nonatomic, strong) id type; @property (nonatomic, assign) BOOL isSticky; diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemView.m b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemView.m index 21c3ce639b3..00c0d4ab335 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemView.m +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,13 +21,13 @@ */ #import "NativeRenderBaseListItemView.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "UIView+MountEvent.h" @implementation NativeRenderBaseListItemView -- (void)nativeRenderSetFrame:(CGRect)frame { - [super nativeRenderSetFrame:frame]; +- (void)hippySetFrame:(CGRect)frame { + [super hippySetFrame:frame]; self.frame = self.bounds; } diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemViewManager.h b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemViewManager.h index 94555767c28..91fef6833d2 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemViewManager.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderBaseListItemViewManager : NativeRenderViewManager +@interface NativeRenderBaseListItemViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemViewManager.mm b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemViewManager.mm index 697e8784370..381173ce438 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemViewManager.mm +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListItemViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -26,20 +26,20 @@ @implementation NativeRenderBaseListItemViewManager -NATIVE_RENDER_EXPORT_VIEW(ListViewItem) +HIPPY_EXPORT_MODULE(ListViewItem) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(type, id) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(isSticky, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onAppear, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onDisappear, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onWillAppear, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onWillDisappear, NativeRenderDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(type, id) +HIPPY_EXPORT_VIEW_PROPERTY(isSticky, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(onAppear, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onDisappear, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onWillAppear, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onWillDisappear, HippyDirectEventBlock) - (UIView *)view { return [[NativeRenderBaseListItemView alloc] init]; } -- (NativeRenderObjectView *)nativeRenderObjectView { +- (HippyShadowView *)hippyShadowView { return [[NativeRenderObjectBaseListItem alloc] init]; } diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListView.h b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListView.h index f4828a6dd95..bd1979d2669 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListView.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,7 +21,7 @@ */ #import -#import "NativeRenderScrollView.h" +#import "HippyScrollView.h" #import "NativeRenderListTableView.h" #import "NativeRenderTouchesView.h" #import "NativeRenderWaterfallView.h" @@ -31,15 +31,15 @@ @interface NativeRenderBaseListView : NativeRenderWaterfallView /** - * NativeRender events + * Hippy events */ -@property(nonatomic, copy) NativeRenderDirectEventBlock initialListReady; -@property(nonatomic, copy) NativeRenderDirectEventBlock onScrollBeginDrag; -@property(nonatomic, copy) NativeRenderDirectEventBlock onScrollEndDrag; -@property(nonatomic, copy) NativeRenderDirectEventBlock onMomentumScrollBegin; -@property(nonatomic, copy) NativeRenderDirectEventBlock onMomentumScrollEnd; -@property(nonatomic, copy) NativeRenderDirectEventBlock onRowWillDisplay; -@property(nonatomic, copy) NativeRenderDirectEventBlock onDelete; +@property(nonatomic, copy) HippyDirectEventBlock initialListReady; +@property(nonatomic, copy) HippyDirectEventBlock onScrollBeginDrag; +@property(nonatomic, copy) HippyDirectEventBlock onScrollEndDrag; +@property(nonatomic, copy) HippyDirectEventBlock onMomentumScrollBegin; +@property(nonatomic, copy) HippyDirectEventBlock onMomentumScrollEnd; +@property(nonatomic, copy) HippyDirectEventBlock onRowWillDisplay; +@property(nonatomic, copy) HippyDirectEventBlock onDelete; /** * Indication initial content offset when NativeRenderBaseListView finish loading data diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListView.mm b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListView.mm index 5e0793947d7..1a4305b1fcc 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListView.mm +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,17 +20,17 @@ * limitations under the License. */ -#import "HPAsserts.h" +#import "HippyAsserts.h" #import "NativeRenderBaseListView.h" #import "NativeRenderBaseListViewCell.h" #import "NativeRenderBaseListViewDataSource.h" #import "NativeRenderCollectionViewFlowLayout.h" #import "NativeRenderFooterRefresh.h" #import "NativeRenderHeaderRefresh.h" -#import "NativeRenderImpl.h" -#import "NativeRenderObjectView.h" +#import "HippyUIManager.h" +#import "HippyShadowView.h" #import "UIView+DirectionalLayout.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "UIView+Render.h" static NSString *const kCellIdentifier = @"cellIdentifier"; @@ -106,12 +106,12 @@ - (void)setFrame:(CGRect)frame { [super setFrame:frame]; } -- (void)nativeRenderSetFrame:(CGRect)frame { - [super nativeRenderSetFrame:frame]; +- (void)hippySetFrame:(CGRect)frame { + [super hippySetFrame:frame]; self.collectionView.frame = self.bounds; } -- (void)setInitialListReady:(NativeRenderDirectEventBlock)initialListReady { +- (void)setInitialListReady:(HippyDirectEventBlock)initialListReady { _initialListReady = initialListReady; _isInitialListReady = NO; } @@ -146,7 +146,7 @@ - (void)reloadData { } } -- (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { +- (void)insertHippySubview:(UIView *)subview atIndex:(NSInteger)atIndex { if ([subview isKindOfClass:[NativeRenderHeaderRefresh class]]) { if (_headerRefreshView) { [_headerRefreshView unsetFromScrollView]; @@ -154,7 +154,7 @@ - (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { _headerRefreshView = (NativeRenderHeaderRefresh *)subview; [_headerRefreshView setScrollView:self.collectionView]; _headerRefreshView.delegate = self; - [_weakItemMap setObject:subview forKey:[subview componentTag]]; + [_weakItemMap setObject:subview forKey:[subview hippyTag]]; } else if ([subview isKindOfClass:[NativeRenderFooterRefresh class]]) { if (_footerRefreshView) { [_footerRefreshView unsetFromScrollView]; @@ -162,15 +162,15 @@ - (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { _footerRefreshView = (NativeRenderFooterRefresh *)subview; [_footerRefreshView setScrollView:self.collectionView]; _footerRefreshView.delegate = self; - [_weakItemMap setObject:subview forKey:[subview componentTag]]; + [_weakItemMap setObject:subview forKey:[subview hippyTag]]; } } -- (void)didUpdateNativeRenderSubviews { +- (void)didUpdateHippySubviews { self.dirtyContent = YES; } -- (void)nativeRenderComponentDidFinishTransaction { +- (void)hippyBridgeDidFinishTransaction { if (self.dirtyContent) { [self reloadData]; self.dirtyContent = NO; @@ -178,7 +178,7 @@ - (void)nativeRenderComponentDidFinishTransaction { } - (void)refreshItemNodes { - NSArray *datasource = [self popDataSource]; + NSArray *datasource = [self popDataSource]; self->_dataSource = [[NativeRenderBaseListViewDataSource alloc] initWithDataSource:datasource itemViewName:[self compoentItemName] containBannerView:NO]; @@ -232,7 +232,7 @@ - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForHeaderInSection:(NSInteger)section { - NativeRenderObjectView *header = [self.dataSource headerForSection:section]; + HippyShadowView *header = [self.dataSource headerForSection:section]; if (header) { return CGRectGetHeight(header.frame); } else { @@ -243,8 +243,8 @@ - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectio - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section { - NativeRenderObjectView *headerObjectView = [self.dataSource headerForSection:section]; - if ([headerObjectView isKindOfClass:[NativeRenderObjectView class]]) { + HippyShadowView *headerObjectView = [self.dataSource headerForSection:section]; + if ([headerObjectView isKindOfClass:[HippyShadowView class]]) { return headerObjectView.frame.size; } return CGSizeZero; @@ -257,9 +257,9 @@ - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kSupplementaryIdentifier forIndexPath:indexPath]; - NativeRenderObjectView *headerRenderObject = [self.dataSource headerForSection:section]; - if (headerRenderObject && [headerRenderObject isKindOfClass:[NativeRenderObjectView class]]) { - UIView *headerView = [self.renderImpl viewFromRenderViewTag:headerRenderObject.componentTag onRootTag:headerRenderObject.rootTag]; + HippyShadowView *headerRenderObject = [self.dataSource headerForSection:section]; + if (headerRenderObject && [headerRenderObject isKindOfClass:[HippyShadowView class]]) { + UIView *headerView = [self.renderImpl viewFromRenderViewTag:headerRenderObject.hippyTag onRootTag:headerRenderObject.rootTag]; if (!headerView) { headerView = [self.renderImpl createViewRecursivelyFromRenderObject:headerRenderObject]; } @@ -278,7 +278,7 @@ - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSe - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath { - NativeRenderObjectView *cellRenderObjectView = [self.dataSource cellForIndexPath:indexPath]; + HippyShadowView *cellRenderObjectView = [self.dataSource cellForIndexPath:indexPath]; [cellRenderObjectView recusivelySetCreationTypeToInstant]; [self itemViewForCollectionViewCell:cell indexPath:indexPath]; NSInteger index = [self.dataSource flatIndexForIndexPath:indexPath]; @@ -310,7 +310,7 @@ - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:( if ([cell isKindOfClass:[NativeRenderBaseListViewCell class]]) { NativeRenderBaseListViewCell *hpCell = (NativeRenderBaseListViewCell *)cell; if (hpCell.cellView) { - [_cachedItems setObject:[hpCell.cellView componentTag] forKey:indexPath]; + [_cachedItems setObject:[hpCell.cellView hippyTag] forKey:indexPath]; hpCell.cellView = nil; } } @@ -321,21 +321,21 @@ - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cell } - (void)itemViewForCollectionViewCell:(UICollectionViewCell *)cell indexPath:(NSIndexPath *)indexPath { - HPAssert(self.renderImpl, @"no rendercontext detected"); + HippyAssert(self.renderImpl, @"no rendercontext detected"); if (!self.renderImpl) { return; } - NativeRenderObjectView *cellRenderObject = [self.dataSource cellForIndexPath:indexPath]; + HippyShadowView *cellRenderObject = [self.dataSource cellForIndexPath:indexPath]; NativeRenderBaseListViewCell *hpCell = (NativeRenderBaseListViewCell *)cell; UIView *cellView = [self.renderImpl createViewRecursivelyFromRenderObject:cellRenderObject]; if (cellView) { [_cachedItems removeObjectForKey:indexPath]; } - HPAssert([cellView conformsToProtocol:@protocol(ViewAppearStateProtocol)], + HippyAssert([cellView conformsToProtocol:@protocol(ViewAppearStateProtocol)], @"subviews of NativeRenderBaseListViewCell must conform to protocol ViewAppearStateProtocol"); hpCell.cellView = cellView; cellView.parentComponent = self; - [_weakItemMap setObject:cellView forKey:[cellView componentTag]]; + [_weakItemMap setObject:cellView forKey:[cellView hippyTag]]; } - (void)tableViewDidLayoutSubviews:(NativeRenderListTableView *)tableView { @@ -526,6 +526,6 @@ - (void)setHorizontal:(BOOL)horizontal { } #pragma mark NativeRenderRefresh Delegate -- (void)refreshView:(NativeRenderRefresh *)refreshView statusChanged:(NativeRenderRefreshStatus)status { +- (void)refreshView:(HippyRefresh *)refreshView statusChanged:(HippyRefreshStatus)status { } @end diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewCell.h b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewCell.h index 079a4b47cb3..0f41cb4083a 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewCell.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewCell.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewCell.m b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewCell.m index 4beb4b07fbd..8e3d5218445 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewCell.m +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewCell.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewDataSource.h b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewDataSource.h index 6eba8e353fb..bd328438d24 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewDataSource.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewDataSource.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewDataSource.mm b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewDataSource.mm index 584da180da2..fc2d095ae47 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewDataSource.mm +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewDataSource.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,7 +22,7 @@ #import #import "NativeRenderBaseListViewDataSource.h" -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" #import "NativeRenderObjectWaterfall.h" @interface NativeRenderBaseListViewDataSource () { @@ -33,12 +33,12 @@ @interface NativeRenderBaseListViewDataSource () { @implementation NativeRenderBaseListViewDataSource -- (void)setDataSource:(NSArray *)dataSource containBannerView:(BOOL)containBannerView { +- (void)setDataSource:(NSArray *)dataSource containBannerView:(BOOL)containBannerView { NSMutableArray *headerRenderObjects = [NSMutableArray array]; - NSMutableArray *> *cellRenderObjects = [NSMutableArray array]; - NSMutableArray *sectionCellRenderObject = nil; + NSMutableArray *> *cellRenderObjects = [NSMutableArray array]; + NSMutableArray *sectionCellRenderObject = nil; BOOL isFirstIndex = YES; - for (NativeRenderObjectView *renderObject in dataSource) { + for (HippyShadowView *renderObject in dataSource) { NSString *viewName = [renderObject viewName]; if ([self.itemViewName isEqualToString:viewName]) { NSNumber *sticky = renderObject.props[@"sticky"]; @@ -68,9 +68,9 @@ - (void)setDataSource:(NSArray *)dataSource containBan self.cellRenderObjectViews = [cellRenderObjects copy]; } -- (NativeRenderObjectView *)cellForIndexPath:(NSIndexPath *)indexPath { +- (HippyShadowView *)cellForIndexPath:(NSIndexPath *)indexPath { if (self.cellRenderObjectViews.count > indexPath.section) { - NSArray *sectionCellRenderObject = [self.cellRenderObjectViews objectAtIndex:indexPath.section]; + NSArray *sectionCellRenderObject = [self.cellRenderObjectViews objectAtIndex:indexPath.section]; if (sectionCellRenderObject.count > indexPath.row) { return [sectionCellRenderObject objectAtIndex:indexPath.row]; } @@ -78,13 +78,13 @@ - (NativeRenderObjectView *)cellForIndexPath:(NSIndexPath *)indexPath { return nil; } -- (NSIndexPath *)indexPathOfCell:(NativeRenderObjectView *)cell { +- (NSIndexPath *)indexPathOfCell:(HippyShadowView *)cell { NSInteger section = 0; NSInteger row = 0; for (NSInteger sec = 0; sec < [self.cellRenderObjectViews count]; sec++) { - NSArray *sectionCellRenderObjects = [self.cellRenderObjectViews objectAtIndex:sec]; + NSArray *sectionCellRenderObjects = [self.cellRenderObjectViews objectAtIndex:sec]; for (NSUInteger r = 0; r < [sectionCellRenderObjects count]; r++) { - NativeRenderObjectView *cellRenderObject = [sectionCellRenderObjects objectAtIndex:r]; + HippyShadowView *cellRenderObject = [sectionCellRenderObjects objectAtIndex:r]; if (cellRenderObject == cell) { section = sec; row = r; @@ -94,7 +94,7 @@ - (NSIndexPath *)indexPathOfCell:(NativeRenderObjectView *)cell { return [NSIndexPath indexPathForRow:row inSection:section]; } -- (NativeRenderObjectView *)headerForSection:(NSInteger)section { +- (HippyShadowView *)headerForSection:(NSInteger)section { if (_headerRenderObjects.count > section) { return [_headerRenderObjects objectAtIndex:section]; } @@ -118,7 +118,7 @@ - (NSIndexPath *)indexPathForFlatIndex:(NSInteger)index { NSInteger rowIndex = 0; NSInteger selfIncreaseIndex = 0; for (NSInteger sec = 0; sec < [self.cellRenderObjectViews count]; sec++) { - NSArray *sectionCellRenderObjects = [self.cellRenderObjectViews objectAtIndex:sec]; + NSArray *sectionCellRenderObjects = [self.cellRenderObjectViews objectAtIndex:sec]; for (NSUInteger r = 0; r < [sectionCellRenderObjects count]; r++) { if (index == selfIncreaseIndex) { sectionIndex = sec; @@ -140,7 +140,7 @@ - (NSInteger)flatIndexForIndexPath:(NSIndexPath *)indexPath { flatIndex += row; } else { - NSArray *sectionCellRenderObjects = [self.cellRenderObjectViews objectAtIndex:sec]; + NSArray *sectionCellRenderObjects = [self.cellRenderObjectViews objectAtIndex:sec]; flatIndex += [sectionCellRenderObjects count]; } } @@ -210,20 +210,19 @@ - (void)applyDiff:(NativeRenderBaseListViewDataSource *)another BOOL success = YES; if ([batchUpdate count]) { - [UIView setAnimationsEnabled:NO]; + [CATransaction begin]; + [CATransaction setDisableActions:YES]; @try { [view performBatchUpdates:^{ for (NSInvocation *invocation in batchUpdate) { [invocation invoke]; } - } completion:^(BOOL finished) { - [UIView setAnimationsEnabled:YES]; - }]; + } completion:nil]; } @catch (NSException *exception) { [view reloadData]; success = NO; - [UIView setAnimationsEnabled:YES]; } + [CATransaction commit]; } completion(success); } @@ -245,12 +244,12 @@ - (void)applyDiff:(NativeRenderBaseListViewDataSource *)another return invocation; } -static inline void EnumCellRenderObjects(NSArray *> *objects, - void (^ _Nonnull block)(__kindof NativeRenderObjectView * object, NSUInteger section, NSUInteger row)) { +static inline void EnumCellRenderObjects(NSArray *> *objects, + void (^ _Nonnull block)(__kindof HippyShadowView * object, NSUInteger section, NSUInteger row)) { for (NSUInteger section = 0; section < [objects count]; section ++) { - NSArray<__kindof NativeRenderObjectView *> *sectionObjects = [objects objectAtIndex:section]; + NSArray<__kindof HippyShadowView *> *sectionObjects = [objects objectAtIndex:section]; for (NSUInteger row = 0; row < [sectionObjects count]; row++) { - __kindof NativeRenderObjectView *object = [sectionObjects objectAtIndex:row]; + __kindof HippyShadowView *object = [sectionObjects objectAtIndex:row]; block(object, section, row); } } @@ -266,9 +265,9 @@ static inline void EnumCellRenderObjects(NSArray *invocations = [NSMutableArray arrayWithCapacity:8]; - NSHashTable<__kindof NativeRenderObjectView *> *insertedItems = [context addedItems]; - NSMutableSet<__kindof NativeRenderObjectView *> *deletedItems = [[context deletedItems] mutableCopy]; - NSHashTable<__kindof NativeRenderObjectView *> *frameChangedItems = [context frameChangedItems]; + NSHashTable<__kindof HippyShadowView *> *insertedItems = [context addedItems]; + NSMutableSet<__kindof HippyShadowView *> *deletedItems = [[context deletedItems] mutableCopy]; + NSHashTable<__kindof HippyShadowView *> *frameChangedItems = [context frameChangedItems]; //get section number change //section number increased or decreased NSUInteger selfSectionCount = [self.cellRenderObjectViews count]; @@ -277,7 +276,7 @@ static inline void EnumCellRenderObjects(NSArray *objects = [self.cellRenderObjectViews objectAtIndex:anotherSectionCount]; + NSArray<__kindof HippyShadowView *> *objects = [self.cellRenderObjectViews objectAtIndex:anotherSectionCount]; [objects enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { [insertedItems removeObject:obj]; }]; @@ -292,8 +291,8 @@ static inline void EnumCellRenderObjects(NSArray *objects = [another.cellRenderObjectViews objectAtIndex:anotherSectionCount]; - [objects enumerateObjectsUsingBlock:^(__kindof NativeRenderObjectView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { + NSArray<__kindof HippyShadowView *> *objects = [another.cellRenderObjectViews objectAtIndex:anotherSectionCount]; + [objects enumerateObjectsUsingBlock:^(__kindof HippyShadowView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { [deletedItems removeObject:obj]; }]; [indexSet addIndex:anotherSectionCount]; @@ -307,7 +306,7 @@ static inline void EnumCellRenderObjects(NSArray *insertedIndexPaths = [NSMutableArray arrayWithCapacity:16]; NSMutableArray *frameChangedIndexPaths = [NSMutableArray arrayWithCapacity:16]; - EnumCellRenderObjects(self.cellRenderObjectViews, ^(__kindof NativeRenderObjectView *object, NSUInteger section, NSUInteger row) { + EnumCellRenderObjects(self.cellRenderObjectViews, ^(__kindof HippyShadowView *object, NSUInteger section, NSUInteger row) { if ([insertedItems count] && [insertedItems containsObject:object]) { NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section]; [insertedIndexPaths addObject:indexPath]; @@ -331,7 +330,7 @@ static inline void EnumCellRenderObjects(NSArray *deletedIndexPaths = [NSMutableArray arrayWithCapacity:16]; - EnumCellRenderObjects(another.cellRenderObjectViews, ^(__kindof NativeRenderObjectView *object, NSUInteger section, NSUInteger row) { + EnumCellRenderObjects(another.cellRenderObjectViews, ^(__kindof HippyShadowView *object, NSUInteger section, NSUInteger row) { if ([deletedItems containsObject:object]) { NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section]; [deletedIndexPaths addObject:indexPath]; diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewManager.h b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewManager.h index aedd9b54fbb..9470a7e44da 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewManager.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderBaseListViewManager : NativeRenderViewManager +@interface NativeRenderBaseListViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewManager.mm b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewManager.mm index bba4ef918c8..179f0cc7be9 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewManager.mm +++ b/renderer/native/ios/renderer/component/listview/NativeRenderBaseListViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,63 +23,63 @@ #import "NativeRenderBaseListViewManager.h" #import "NativeRenderBaseListView.h" #import "NativeRenderObjectWaterfall.h" -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" @implementation NativeRenderBaseListViewManager -NATIVE_RENDER_EXPORT_VIEW(ListView) +HIPPY_EXPORT_MODULE(ListView) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollEventThrottle, double) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(initialListReady, NativeRenderDirectEventBlock); -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScrollBeginDrag, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScroll, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScrollEndDrag, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onMomentumScrollBegin, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onMomentumScrollEnd, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onRowWillDisplay, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onEndReached, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onDelete, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(preloadItemNumber, NSUInteger) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(bounces, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(initialContentOffset, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(editable, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(showScrollIndicator, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollEnabled, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(horizontal, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(scrollEventThrottle, double) +HIPPY_EXPORT_VIEW_PROPERTY(initialListReady, HippyDirectEventBlock); +HIPPY_EXPORT_VIEW_PROPERTY(onScrollBeginDrag, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onScroll, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onScrollEndDrag, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onMomentumScrollBegin, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onMomentumScrollEnd, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onRowWillDisplay, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onEndReached, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onDelete, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(preloadItemNumber, NSUInteger) +HIPPY_EXPORT_VIEW_PROPERTY(bounces, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(initialContentOffset, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(editable, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(showScrollIndicator, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(scrollEnabled, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(horizontal, BOOL) - (UIView *)view { return [[NativeRenderBaseListView alloc] init]; } -- (NativeRenderObjectView *)nativeRenderObjectView { +- (HippyShadowView *)hippyShadowView { return [[NativeRenderObjectWaterfall alloc] init]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(scrollToIndex:(nonnull NSNumber *)componentTag - xIndex:(__unused NSNumber *)xIndex - yIndex:(NSNumber *)yIndex - animation:(nonnull NSNumber *)animation) { - [self.renderImpl addUIBlock: - ^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ +HIPPY_EXPORT_METHOD(scrollToIndex:(nonnull NSNumber *)componentTag + xIndex:(__unused NSNumber *)xIndex + yIndex:(NSNumber *)yIndex + animation:(nonnull NSNumber *)animation) { + [self.bridge.uiManager addUIBlock: + ^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ NativeRenderBaseListView *view = (NativeRenderBaseListView *)viewRegistry[componentTag]; if (view == nil) return ; if (![view isKindOfClass:[NativeRenderBaseListView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderBaseListView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderBaseListView, got: %@", view); } [view scrollToIndex: yIndex.integerValue animated: [animation boolValue]]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(scrollToContentOffset:(nonnull NSNumber *)componentTag - x:(nonnull NSNumber *)x - y:(nonnull NSNumber *)y - animation:(nonnull NSNumber *)animation) { - [self.renderImpl addUIBlock: - ^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ +HIPPY_EXPORT_METHOD(scrollToContentOffset:(nonnull NSNumber *)componentTag + x:(nonnull NSNumber *)x + y:(nonnull NSNumber *)y + animation:(nonnull NSNumber *)animation) { + [self.bridge.uiManager addUIBlock: + ^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ NativeRenderBaseListView *view = (NativeRenderBaseListView *)viewRegistry[componentTag]; if (view == nil) return ; if (![view isKindOfClass:[NativeRenderBaseListView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderBaseListView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderBaseListView, got: %@", view); } [view scrollToContentOffset:CGPointMake([x floatValue], [y floatValue]) animated: [animation boolValue]]; }]; diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderCollectionViewFlowLayout.h b/renderer/native/ios/renderer/component/listview/NativeRenderCollectionViewFlowLayout.h index 1029e49f28d..0f746959f72 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderCollectionViewFlowLayout.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderCollectionViewFlowLayout.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderCollectionViewFlowLayout.m b/renderer/native/ios/renderer/component/listview/NativeRenderCollectionViewFlowLayout.m index f4e52c6b6f2..1020a05b24a 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderCollectionViewFlowLayout.m +++ b/renderer/native/ios/renderer/component/listview/NativeRenderCollectionViewFlowLayout.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderListTableView.h b/renderer/native/ios/renderer/component/listview/NativeRenderListTableView.h index 03a5f1b09bf..e652d11de76 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderListTableView.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderListTableView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderListTableView.m b/renderer/native/ios/renderer/component/listview/NativeRenderListTableView.m index bfad186cea5..48bcf896e19 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderListTableView.m +++ b/renderer/native/ios/renderer/component/listview/NativeRenderListTableView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderObjectBaseListItem.h b/renderer/native/ios/renderer/component/listview/NativeRenderObjectBaseListItem.h index f20c2f8012e..9b4434d1fa6 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderObjectBaseListItem.h +++ b/renderer/native/ios/renderer/component/listview/NativeRenderObjectBaseListItem.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" #import "NativeRenderObjectWaterfallItem.h" NS_ASSUME_NONNULL_BEGIN diff --git a/renderer/native/ios/renderer/component/listview/NativeRenderObjectBaseListItem.mm b/renderer/native/ios/renderer/component/listview/NativeRenderObjectBaseListItem.mm index 2aa5d9b0766..1da4d000561 100644 --- a/renderer/native/ios/renderer/component/listview/NativeRenderObjectBaseListItem.mm +++ b/renderer/native/ios/renderer/component/listview/NativeRenderObjectBaseListItem.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomAnimationTransition.h b/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomAnimationTransition.h index f8eb9265da0..2b25cb0b51a 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomAnimationTransition.h +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomAnimationTransition.h @@ -3,7 +3,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomAnimationTransition.m b/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomAnimationTransition.m index 3f596d16202..6542e2d6be7 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomAnimationTransition.m +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomAnimationTransition.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomPresentationController.h b/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomPresentationController.h index 513667756d7..3a9779b9d73 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomPresentationController.h +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomPresentationController.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomPresentationController.m b/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomPresentationController.m index fc102e0d20f..935052fdaae 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomPresentationController.m +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalCustomPresentationController.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostView.h b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostView.h index b21287fb182..dc0035eb065 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostView.h +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,7 +22,7 @@ #import -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" @class NativeRenderModalHostViewController; @@ -35,13 +35,13 @@ @property (nonatomic, assign, getter=isTransparent) BOOL transparent; @property (nonatomic, assign) BOOL darkStatusBarText; -@property (nonatomic, copy) NativeRenderDirectEventBlock onShow; -@property (nonatomic, copy) NativeRenderDirectEventBlock onRequestClose; +@property (nonatomic, copy) HippyDirectEventBlock onShow; +@property (nonatomic, copy) HippyDirectEventBlock onRequestClose; @property (nonatomic, weak) id delegate; @property (nonatomic, strong) NSArray *supportedOrientations; -@property (nonatomic, copy) NativeRenderDirectEventBlock onOrientationChange; +@property (nonatomic, copy) HippyDirectEventBlock onOrientationChange; @property (nonatomic, strong) NSNumber *hideStatusBar; @property (nonatomic, readonly) BOOL isPresented; @property (nonatomic, strong) NativeRenderModalHostViewController *modalViewController; diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostView.mm b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostView.mm index 44cd9aac6f7..913f034e2e1 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostView.mm +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,7 +22,7 @@ #import "NativeRenderModalHostView.h" #import "NativeRenderModalHostViewController.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "UIView+MountEvent.h" #import "NativeRenderModalHostViewInteractor.h" @@ -70,13 +70,13 @@ - (void)notifyForOrientationChange { _onOrientationChange(eventPayload); } -- (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { - [super insertNativeRenderSubview:subview atIndex:atIndex]; +- (void)insertHippySubview:(UIView *)subview atIndex:(NSInteger)atIndex { + [super insertHippySubview:subview atIndex:atIndex]; [_modalViewController.view insertSubview:subview atIndex:atIndex]; [subview sendAttachedToWindowEvent]; } -- (void)didUpdateNativeRenderSubviews { +- (void)didUpdateHippySubviews { // Do nothing, as subview (singular) is managed by `insertHippySubview:atIndex:` } @@ -92,7 +92,7 @@ - (void)didMoveToWindow { [super didMoveToWindow]; if (!_isPresented && self.window) { - NSAssert(self.nativeRenderViewController, @"Can't present modal view controller without a presenting view controller"); + NSAssert(self.hippyViewController, @"Can't present modal view controller without a presenting view controller"); _modalViewController.supportedInterfaceOrientations = [self supportedOrientationsMask]; if ([self.animationType isEqualToString:@"fade"]) { _modalViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewController.h b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewController.h index f4f16c8d640..4510abd457e 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewController.h +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewController.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewController.mm b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewController.mm index 6b201130f69..82bd2786a00 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewController.mm +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewController.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,7 +21,7 @@ */ #import "NativeRenderModalHostViewController.h" -#import "HPToolUtils.h" +#import "HippyUtils.h" @interface NativeRenderModalHostViewController () { CGRect _lastViewFrame; @@ -36,7 +36,7 @@ - (instancetype)init { self = [super init]; if (self) { if (@available(iOS 13.0, *)) { - _preferredStatusBarStyle = [[[HPKeyWindow() windowScene] statusBarManager] statusBarStyle]; + _preferredStatusBarStyle = [[[HippyKeyWindow() windowScene] statusBarManager] statusBarStyle]; } else { _preferredStatusBarStyle = [[UIApplication sharedApplication] statusBarStyle]; @@ -76,13 +76,13 @@ - (BOOL)prefersStatusBarHidden { if (_hideStatusBar) { return [_hideStatusBar boolValue]; } - BOOL hidden = [HPKeyWindow().rootViewController prefersStatusBarHidden]; + BOOL hidden = [HippyKeyWindow().rootViewController prefersStatusBarHidden]; return hidden; } -#if HP_DEBUG +#if HIPPY_DEBUG - (UIInterfaceOrientationMask)supportedInterfaceOrientations { - UIWindow *keyWindow = HPKeyWindow(); + UIWindow *keyWindow = HippyKeyWindow(); UIInterfaceOrientationMask appSupportedOrientationsMask = [[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:keyWindow]; if (!(_supportedInterfaceOrientations & appSupportedOrientationsMask)) { return UIInterfaceOrientationMaskAll; @@ -90,6 +90,6 @@ - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return _supportedInterfaceOrientations; } -#endif // HP_DEBUG +#endif // HIPPY_DEBUG @end diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewInteractor.h b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewInteractor.h index 8f8164ceef9..73746cc87a1 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewInteractor.h +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewInteractor.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewManager.h b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewManager.h index c1345808727..646b0a68466 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewManager.h +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" #import "NativeRenderModalHostView.h" @protocol NativeRenderModalHostViewInteractor; @@ -28,7 +28,7 @@ typedef void (^NativeRenderModalViewInteractionBlock)( UIViewController *reactViewController, UIViewController *viewController, BOOL animated, dispatch_block_t completionBlock); -@interface NativeRenderModalHostViewManager : NativeRenderViewManager +@interface NativeRenderModalHostViewManager : HippyViewManager @property (nonatomic, strong) NSHashTable *hostViews; @property (nonatomic, strong) id transitioningDelegate; diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewManager.mm b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewManager.mm index c1f019050e0..1edc7e129bc 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewManager.mm +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalHostViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,14 +20,14 @@ * limitations under the License. */ -#import "HPToolUtils.h" +#import "HippyUtils.h" #import "NativeRenderModalHostViewController.h" #import "NativeRenderModalHostViewManager.h" #import "NativeRenderModalTransitioningDelegate.h" -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" #import "NativeRenderUtils.h" -@interface NativeRenderObjectModalHost : NativeRenderObjectView +@interface NativeRenderObjectModalHost : HippyShadowView @end @@ -43,17 +43,17 @@ - (void)setDomManager:(std::weak_ptr)domManager { @implementation NativeRenderModalHostViewManager -NATIVE_RENDER_EXPORT_VIEW(Modal) +HIPPY_EXPORT_MODULE(Modal) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(animationType, NSString) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(transparent, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(darkStatusBarText, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onShow, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onRequestClose, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(supportedOrientations, NSArray) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onOrientationChange, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(primaryKey, NSString) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(hideStatusBar, NSNumber) +HIPPY_EXPORT_VIEW_PROPERTY(animationType, NSString) +HIPPY_EXPORT_VIEW_PROPERTY(transparent, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(darkStatusBarText, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(onShow, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onRequestClose, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(supportedOrientations, NSArray) +HIPPY_EXPORT_VIEW_PROPERTY(onOrientationChange, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(primaryKey, NSString) +HIPPY_EXPORT_VIEW_PROPERTY(hideStatusBar, NSNumber) - (UIView *)view { NativeRenderModalHostView *view = [[NativeRenderModalHostView alloc] init]; @@ -72,7 +72,7 @@ - (UIView *)view { return _transitioningDelegate; } -- (NativeRenderObjectView *)nativeRenderObjectView { +- (HippyShadowView *)hippyShadowView { return [NativeRenderObjectModalHost new]; } diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalTransitioningDelegate.h b/renderer/native/ios/renderer/component/modal/NativeRenderModalTransitioningDelegate.h index 11d37d683b1..81c78b0a10f 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalTransitioningDelegate.h +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalTransitioningDelegate.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/modal/NativeRenderModalTransitioningDelegate.m b/renderer/native/ios/renderer/component/modal/NativeRenderModalTransitioningDelegate.m index 434f4da6d7f..dae2a9dfaa0 100644 --- a/renderer/native/ios/renderer/component/modal/NativeRenderModalTransitioningDelegate.m +++ b/renderer/native/ios/renderer/component/modal/NativeRenderModalTransitioningDelegate.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,7 +23,7 @@ #import "NativeRenderModalTransitioningDelegate.h" #import "NativeRenderModalCustomPresentationController.h" #import "NativeRenderModalCustomAnimationTransition.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" @implementation NativeRenderModalTransitioningDelegate @@ -58,13 +58,13 @@ - (void)presentModalHostView:(NativeRenderModalHostView *)modalHostView } }; if (_presentationBlock) { - _presentationBlock([modalHostView nativeRenderViewController], viewController, animated, completionBlock); + _presentationBlock([modalHostView hippyViewController], viewController, animated, completionBlock); } else { if ([modalHostView.hideStatusBar boolValue]) { viewController.modalPresentationCapturesStatusBarAppearance = YES; viewController.hideStatusBar = [modalHostView hideStatusBar]; } - [[modalHostView nativeRenderViewController] presentViewController:viewController animated:animated completion:completionBlock]; + [[modalHostView hippyViewController] presentViewController:viewController animated:animated completion:completionBlock]; } } @@ -82,7 +82,7 @@ - (void)dismissModalHostView:(NativeRenderModalHostView *)modalHostView }; if (_dismissalBlock) { - _dismissalBlock([modalHostView nativeRenderViewController], viewController, animated, nil); + _dismissalBlock([modalHostView hippyViewController], viewController, animated, nil); } else { [viewController dismissViewControllerAnimated:animated completion:completionBlock]; } diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigationControllerAnimator.h b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigationControllerAnimator.h index 459b8b6b485..1bb80142883 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigationControllerAnimator.h +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigationControllerAnimator.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigationControllerAnimator.m b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigationControllerAnimator.m index 415fbb496ad..cd5c4f42689 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigationControllerAnimator.m +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigationControllerAnimator.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorHostView.h b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorHostView.h index 1d152847e94..3e8764b9bc9 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorHostView.h +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorHostView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorHostView.m b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorHostView.m index d49973dd03c..0f025ffd054 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorHostView.m +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorHostView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,7 +22,7 @@ #import "NativeRenderNavigatorHostView.h" #import "NativeRenderNavigationControllerAnimator.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "NativeRenderNavigatorItemViewController.h" #import "NativeRenderNavigatorRootViewController.h" #import "UIView+MountEvent.h" @@ -72,7 +72,7 @@ - (void)presentRootView { _isPresented = YES; UIView *rootView = [self createRootViewForModuleName:_appName initProperties:_initProps]; NativeRenderNavigatorItemViewController *itemViewController = [[NativeRenderNavigatorItemViewController alloc] initWithView:rootView]; - UIViewController *presentingViewController = [self nativeRenderViewController]; + UIViewController *presentingViewController = [self hippyViewController]; NSAssert(presentingViewController, @"no presenting view controller for navigator module"); _navigatorRootViewController = [[NativeRenderNavigatorRootViewController alloc] initWithRootViewController:itemViewController]; _navigatorRootViewController.navigationBar.hidden = YES; @@ -84,8 +84,8 @@ - (void)presentRootView { } } -- (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { - [super insertNativeRenderSubview:subview atIndex:0]; +- (void)insertHippySubview:(UIView *)subview atIndex:(NSInteger)atIndex { + [super insertHippySubview:subview atIndex:0]; } - (void)didMoveToSuperview { diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorItemViewController.h b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorItemViewController.h index b15945b3902..e568351d0c2 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorItemViewController.h +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorItemViewController.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorItemViewController.m b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorItemViewController.m index 8c7320e00a3..6b78fa2b101 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorItemViewController.m +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorItemViewController.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorRootViewController.h b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorRootViewController.h index 4aaee73af9a..a5805e11118 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorRootViewController.h +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorRootViewController.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorRootViewController.m b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorRootViewController.m index 7ddce0a6eb5..ec30df6ad2c 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorRootViewController.m +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorRootViewController.m @@ -3,7 +3,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorViewManager.h b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorViewManager.h index d17a29d4949..374c13657f4 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorViewManager.h +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,12 +20,12 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" #import "NativeRenderNavigatorHostView.h" NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderNavigatorViewManager : NativeRenderViewManager +@interface NativeRenderNavigatorViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorViewManager.mm b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorViewManager.mm index 0fd4dfd8bc4..d6ce1ab6999 100644 --- a/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorViewManager.mm +++ b/renderer/native/ios/renderer/component/navigator/NativeRenderNavigatorViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" #import "NativeRenderNavigatorViewManager.h" @interface NativeRenderNavigatorViewManager () @@ -29,7 +29,7 @@ @interface NativeRenderNavigatorViewManager () @implementation NativeRenderNavigatorViewManager -NATIVE_RENDER_EXPORT_VIEW(Navigator) +HIPPY_EXPORT_MODULE(Navigator) - (UIView *)view { NativeRenderNavigatorHostView *hostView = [[NativeRenderNavigatorHostView alloc] initWithProps:self.props]; @@ -37,15 +37,15 @@ - (UIView *)view { return hostView; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(push:(NSNumber *__nonnull)componentTag parms:(NSDictionary *__nonnull)params) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(push:(NSNumber *__nonnull)componentTag parms:(NSDictionary *__nonnull)params) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderNavigatorHostView *navigatorHostView = viewRegistry[componentTag]; [navigatorHostView push:params]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(pop:(NSNumber *__nonnull)componentTag parms:(NSDictionary *__nonnull)params) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(pop:(NSNumber *__nonnull)componentTag parms:(NSDictionary *__nonnull)params) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderNavigatorHostView *navigatorHostView = viewRegistry[componentTag]; [navigatorHostView pop:params]; }]; diff --git a/renderer/native/ios/renderer/component/refresh/NativeRenderRefresh.h b/renderer/native/ios/renderer/component/refresh/HippyRefresh.h similarity index 70% rename from renderer/native/ios/renderer/component/refresh/NativeRenderRefresh.h rename to renderer/native/ios/renderer/component/refresh/HippyRefresh.h index 72b02965916..d7e29900ea7 100644 --- a/renderer/native/ios/renderer/component/refresh/NativeRenderRefresh.h +++ b/renderer/native/ios/renderer/component/refresh/HippyRefresh.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,30 +23,30 @@ #import #import "NativeRenderTouchesView.h" -typedef NS_ENUM(NSUInteger, NativeRenderRefreshStatus) { - NativeRenderRefreshStatusIdle, - NativeRenderRefreshStatusPulling, - NativeRenderRefreshStatusStartLoading, - NativeRenderRefreshStatusFinishLoading, +typedef NS_ENUM(NSUInteger, HippyRefreshStatus) { + HippyRefreshStatusIdle, + HippyRefreshStatusPulling, + HippyRefreshStatusStartLoading, + HippyRefreshStatusFinishLoading, }; -@class NativeRenderRefresh; +@class HippyRefresh; @protocol NativeRenderRefreshDelegate @optional -- (void)refreshView:(NativeRenderRefresh *)refreshView statusChanged:(NativeRenderRefreshStatus)status; +- (void)refreshView:(HippyRefresh *)refreshView statusChanged:(HippyRefreshStatus)status; @end -@interface NativeRenderRefresh : NativeRenderTouchesView { +@interface HippyRefresh : NativeRenderTouchesView { @protected __weak UIScrollView *_scrollView; - NativeRenderRefreshStatus _status; + HippyRefreshStatus _status; __weak id _delegate; } @property (nonatomic, weak) UIScrollView *scrollView; -@property (nonatomic, readonly) NativeRenderRefreshStatus status; +@property (nonatomic, readonly) HippyRefreshStatus status; @property (nonatomic, weak) id delegate; - (void)unsetFromScrollView; diff --git a/renderer/native/ios/renderer/component/refresh/NativeRenderRefresh.m b/renderer/native/ios/renderer/component/refresh/HippyRefresh.m similarity index 83% rename from renderer/native/ios/renderer/component/refresh/NativeRenderRefresh.m rename to renderer/native/ios/renderer/component/refresh/HippyRefresh.m index 164aa1d6260..716268a7617 100644 --- a/renderer/native/ios/renderer/component/refresh/NativeRenderRefresh.m +++ b/renderer/native/ios/renderer/component/refresh/HippyRefresh.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,9 +20,9 @@ * limitations under the License. */ -#import "NativeRenderRefresh.h" +#import "HippyRefresh.h" -@implementation NativeRenderRefresh +@implementation HippyRefresh - (void)setScrollView:(UIScrollView *)scrollView { _scrollView = scrollView; @@ -40,7 +40,7 @@ - (void)scrollViewDidScroll { - (void)scrollViewDidEndDragging { } -- (void)setStatus:(NativeRenderRefreshStatus)status { +- (void)setStatus:(HippyRefreshStatus)status { if (_status == status) { return; } @@ -54,21 +54,21 @@ - (void)refresh { [UIView animateWithDuration:.2f animations:^{ self.scrollView.contentOffset = CGPointZero; } completion:^(BOOL finished) { - self.status = NativeRenderRefreshStatusStartLoading; + self.status = HippyRefreshStatusStartLoading; }]; } - (void)refreshFinish { - self.status = NativeRenderRefreshStatusFinishLoading; + self.status = HippyRefreshStatusFinishLoading; [self setRefreshStatusToIdle]; } - (void)setRefreshStatusToIdle { - self.status = NativeRenderRefreshStatusIdle; + self.status = HippyRefreshStatusIdle; } - (void)refreshFinishWithOption:(NSDictionary *)options { - self.status = NativeRenderRefreshStatusFinishLoading; + self.status = HippyRefreshStatusFinishLoading; CGFloat time = [options[@"time"] doubleValue] / 1000.f; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setRefreshStatusToIdle) object:nil]; [self performSelector:@selector(setRefreshStatusToIdle) withObject:nil afterDelay:time]; diff --git a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapper.h b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapper.h index 037d55b4171..bb7fc27745a 100644 --- a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapper.h +++ b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapper.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapper.m b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapper.m index 970dd606a86..ce5a67bb543 100644 --- a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapper.m +++ b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapper.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,15 +21,15 @@ */ #import "NativeRenderRefreshWrapper.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "NativeRenderRefreshWrapperItemView.h" -#import "NativeRenderScrollableProtocol.h" +#import "HippyScrollableProtocol.h" @interface NativeRenderRefreshWrapper () @property (nonatomic, weak) NativeRenderRefreshWrapperItemView *wrapperItemView; -@property (nonatomic, weak) id scrollableView; -@property (nonatomic, copy) NativeRenderDirectEventBlock onRefresh; +@property (nonatomic, weak) id scrollableView; +@property (nonatomic, copy) HippyDirectEventBlock onRefresh; @property (nonatomic, assign) CGFloat bounceTime; @end @@ -73,12 +73,12 @@ - (void)startRefresh { } } -- (void)insertNativeRenderSubview:(UIView *)view atIndex:(NSInteger)index { - [super insertNativeRenderSubview:view atIndex:index]; +- (void)insertHippySubview:(UIView *)view atIndex:(NSInteger)index { + [super insertHippySubview:view atIndex:index]; if ([view isKindOfClass:[NativeRenderRefreshWrapperItemView class]]) { _wrapperItemView = (NativeRenderRefreshWrapperItemView *)view; - } else if ([view conformsToProtocol:@protocol(NativeRenderScrollableProtocol)]) { - _scrollableView = (id)view; + } else if ([view conformsToProtocol:@protocol(HippyScrollableProtocol)]) { + _scrollableView = (id)view; [_scrollableView addScrollListener:self]; } } diff --git a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemView.h b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemView.h index 521f0136a79..522f66855f9 100644 --- a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemView.h +++ b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemView.m b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemView.m index 488c1966c95..4039f7bf998 100644 --- a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemView.m +++ b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ #import "NativeRenderRefreshWrapperItemView.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" @implementation NativeRenderRefreshWrapperItemView diff --git a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemViewManager.h b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemViewManager.h index f89adec573a..a316b903ca2 100644 --- a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemViewManager.h +++ b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderRefreshWrapperItemViewManager : NativeRenderViewManager +@interface NativeRenderRefreshWrapperItemViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemViewManager.mm b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemViewManager.mm index 80c411fecf5..28d6771c02f 100644 --- a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemViewManager.mm +++ b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperItemViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -25,7 +25,7 @@ @implementation NativeRenderRefreshWrapperItemViewManager -NATIVE_RENDER_EXPORT_VIEW(RefreshWrapperItemView) +HIPPY_EXPORT_MODULE(RefreshWrapperItemView) - (UIView *)view { return [NativeRenderRefreshWrapperItemView new]; diff --git a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperViewManager.h b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperViewManager.h index be2759ecc08..86c05a704c4 100644 --- a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperViewManager.h +++ b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderRefreshWrapperViewManager : NativeRenderViewManager +@interface NativeRenderRefreshWrapperViewManager : HippyViewManager @end NS_ASSUME_NONNULL_END diff --git a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperViewManager.mm b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperViewManager.mm index 9ae96888369..2312a4c95dd 100644 --- a/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperViewManager.mm +++ b/renderer/native/ios/renderer/component/refreshview/NativeRenderRefreshWrapperViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,28 +22,28 @@ #import "NativeRenderRefreshWrapperViewManager.h" #import "NativeRenderRefreshWrapper.h" -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" @implementation NativeRenderRefreshWrapperViewManager -NATIVE_RENDER_EXPORT_VIEW(RefreshWrapper) +HIPPY_EXPORT_MODULE(RefreshWrapper) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onRefresh, NativeRenderDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onRefresh, HippyDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(bounceTime, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(bounceTime, CGFloat) - (UIView *)view { return [NativeRenderRefreshWrapper new]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(refreshComplected:(NSNumber *__nonnull)componentTag) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(refreshComplected:(NSNumber *__nonnull)componentTag) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderRefreshWrapper *wrapperView = viewRegistry[componentTag]; [wrapperView refreshCompleted]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(startRefresh:(NSNumber *__nonnull)componentTag) { - [self.renderImpl addUIBlock:^(NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(startRefresh:(NSNumber *__nonnull)componentTag) { + [self.bridge.uiManager addUIBlock:^(HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderRefreshWrapper *wrapperView = viewRegistry[componentTag]; [wrapperView startRefresh]; }]; diff --git a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollView.h b/renderer/native/ios/renderer/component/scrollview/HippyScrollView.h similarity index 75% rename from renderer/native/ios/renderer/component/scrollview/NativeRenderScrollView.h rename to renderer/native/ios/renderer/component/scrollview/HippyScrollView.h index 00b517eb552..f438b0a8323 100644 --- a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollView.h +++ b/renderer/native/ios/renderer/component/scrollview/HippyScrollView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,24 +21,24 @@ */ #import -#import "NativeRenderScrollableProtocol.h" -#import "NativeRenderView.h" +#import "HippyScrollableProtocol.h" +#import "HippyView.h" @protocol UIScrollViewDelegate; -@interface NativeRenderCustomScrollView : UIScrollView +@interface HippyCustomScrollView : UIScrollView @property (nonatomic, assign) BOOL centerContent; @end -@interface NativeRenderScrollView : NativeRenderView +@interface HippyScrollView : HippyView /** * This is where subclasses should create their custom scroll view hierarchy if they dont want to use default scroll view. * Should never be called directly. */ -- (NativeRenderCustomScrollView *)loadScrollView; +- (HippyCustomScrollView *)loadScrollView; /** * The `NativeRenderScrollView` may have at most one single subview. This will ensure @@ -71,12 +71,12 @@ // NOTE: currently these event props are only declared so we can export the // event names to JS - we don't call the blocks directly because scroll events // need to be coalesced before sending, for performance reasons. -@property (nonatomic, copy) NativeRenderDirectEventBlock onScrollBeginDrag; -@property (nonatomic, copy) NativeRenderDirectEventBlock onScroll; -@property (nonatomic, copy) NativeRenderDirectEventBlock onScrollEndDrag; -@property (nonatomic, copy) NativeRenderDirectEventBlock onMomentumScrollBegin; -@property (nonatomic, copy) NativeRenderDirectEventBlock onMomentumScrollEnd; -@property (nonatomic, copy) NativeRenderDirectEventBlock onScrollAnimationEnd; +@property (nonatomic, copy) HippyDirectEventBlock onScrollBeginDrag; +@property (nonatomic, copy) HippyDirectEventBlock onScroll; +@property (nonatomic, copy) HippyDirectEventBlock onScrollEndDrag; +@property (nonatomic, copy) HippyDirectEventBlock onMomentumScrollBegin; +@property (nonatomic, copy) HippyDirectEventBlock onMomentumScrollEnd; +@property (nonatomic, copy) HippyDirectEventBlock onScrollAnimationEnd; @property (nonatomic, assign) CGPoint targetOffset; diff --git a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollView.mm b/renderer/native/ios/renderer/component/scrollview/HippyScrollView.mm similarity index 95% rename from renderer/native/ios/renderer/component/scrollview/NativeRenderScrollView.mm rename to renderer/native/ios/renderer/component/scrollview/HippyScrollView.mm index ceb5e0bb1f7..04f497bf65e 100644 --- a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollView.mm +++ b/renderer/native/ios/renderer/component/scrollview/HippyScrollView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,12 +21,12 @@ */ #import -#import "NativeRenderScrollView.h" -#import "UIView+NativeRender.h" +#import "HippyScrollView.h" +#import "UIView+Hippy.h" #import "UIView+MountEvent.h" #import "UIView+DirectionalLayout.h" -@implementation NativeRenderCustomScrollView +@implementation HippyCustomScrollView - (instancetype)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { @@ -45,7 +45,7 @@ - (void)setTransform:(CGAffineTransform)transform { } - (UIView *)contentView { - return ((NativeRenderScrollView *)self.superview).contentView; + return ((HippyScrollView *)self.superview).contentView; } /** @@ -91,7 +91,7 @@ - (void)scrollRectToVisible:(__unused CGRect)rect animated:(__unused BOOL)animat * * By default this returns NO for all views that are UIControls and YES for * everything else. What that does is allows scroll views to scroll even when a - * touch started inside of a `UIControl` (`UIButton` etc). For NativeRender scroll + * touch started inside of a `UIControl` (`UIButton` etc). For Hippy scroll * views, we want the default to be the same behavior as `UIControl`s so we * return `YES` by default. But there's one case where we want to block the * scrolling no matter what: When JS believes it has its own responder lock on @@ -159,8 +159,8 @@ - (void)setContentOffset:(CGPoint)contentOffset { @end -@interface NativeRenderScrollView () { - NativeRenderCustomScrollView *_scrollView; +@interface HippyScrollView () { + HippyCustomScrollView *_scrollView; UIView *_contentView; NSTimeInterval _lastScrollDispatchTime; BOOL _allowNextScrollNoMatterWhat; @@ -179,7 +179,7 @@ @interface NativeRenderScrollView () { @end -@implementation NativeRenderScrollView +@implementation HippyScrollView - (instancetype)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { @@ -199,8 +199,8 @@ - (instancetype)initWithFrame:(CGRect)frame { return self; } -- (NativeRenderCustomScrollView *)loadScrollView { - NativeRenderCustomScrollView *scrollview = [[NativeRenderCustomScrollView alloc] initWithFrame:CGRectZero]; +- (HippyCustomScrollView *)loadScrollView { + HippyCustomScrollView *scrollview = [[HippyCustomScrollView alloc] initWithFrame:CGRectZero]; scrollview.delegate = self; scrollview.delaysContentTouches = NO; return scrollview; @@ -214,13 +214,13 @@ - (void)invalidate { [_scrollListeners removeAllObjects]; } -- (void)insertNativeRenderSubview:(UIView *)view atIndex:(NSInteger)atIndex { +- (void)insertHippySubview:(UIView *)view atIndex:(NSInteger)atIndex { if (view == _contentView && 0 == atIndex) { return; } NSAssert(0 == atIndex, @"NativeRenderScrollView only contain one subview at index 0"); if (_contentView) { - [self removeNativeRenderSubview:_contentView]; + [self removeHippySubview:_contentView]; } _contentView = view; [_contentView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil]; @@ -235,7 +235,7 @@ - (void)insertNativeRenderSubview:(UIView *)view atIndex:(NSInteger)atIndex { /** * reset its contentOffset when subviews are ready */ - NSString *offsetString = [_contentOffsetCache objectForKey:self.componentTag]; + NSString *offsetString = [_contentOffsetCache objectForKey:self.hippyTag]; if (offsetString) { CGPoint point = CGPointFromString(offsetString); if (CGRectContainsPoint(_contentView.frame, point)) { @@ -257,22 +257,22 @@ - (void)observeValueForKeyPath:(NSString *)keyPath context:(__unused void *)context { if ([keyPath isEqualToString:@"frame"]) { if (object == _contentView) { - [self nativeRenderComponentDidFinishTransaction]; + [self hippyBridgeDidFinishTransaction]; } } } -- (void)removeNativeRenderSubview:(UIView *)subview { - [super removeNativeRenderSubview:subview]; +- (void)removeHippySubview:(UIView *)subview { + [super removeHippySubview:subview]; NSAssert(_contentView == subview, @"Attempted to remove non-existent subview"); [_contentView removeObserver:self forKeyPath:@"frame"]; _contentView.parentComponent = nil; _contentView = nil; } -- (void)didUpdateNativeRenderSubviews +- (void)didUpdateHippySubviews { - // Do nothing, as subviews are managed by `insertNativeRenderSubview:atIndex:` + // Do nothing, as subviews are managed by `insertHippySubview:atIndex:` } - (BOOL)centerContent { @@ -599,15 +599,15 @@ - (void)didMoveToSuperview { * we need to cache scroll view's contentOffset. * if scroll view is reused in list view cell, we can save its contentOffset in every cells, * and set right contentOffset for each cell. - * resetting componentTag meas scroll view is in reusing. + * resetting hippyTag meas scroll view is in reusing. */ -- (void)setComponentTag:(NSNumber *)componentTag { - if (![self.componentTag isEqualToNumber:componentTag]) { - if (self.componentTag) { +- (void)setHippyTag:(NSNumber *)componentTag { + if (![self.hippyTag isEqualToNumber:componentTag]) { + if (self.hippyTag) { NSString *offsetString = NSStringFromCGPoint(self.scrollView.contentOffset); - [_contentOffsetCache setObject:offsetString forKey:self.componentTag]; + [_contentOffsetCache setObject:offsetString forKey:self.hippyTag]; } - [super setComponentTag:componentTag]; + [super setHippyTag:componentTag]; } } @@ -639,7 +639,7 @@ - (CGSize)contentSize { } } -- (void)nativeRenderComponentDidFinishTransaction { +- (void)hippyBridgeDidFinishTransaction { CGSize contentSize = self.contentSize; if (!CGSizeEqualToSize(_scrollView.contentSize, contentSize)) { // When contentSize is set manually, ScrollView internals will reset diff --git a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollViewManager.h b/renderer/native/ios/renderer/component/scrollview/HippyScrollViewManager.h similarity index 81% rename from renderer/native/ios/renderer/component/scrollview/NativeRenderScrollViewManager.h rename to renderer/native/ios/renderer/component/scrollview/HippyScrollViewManager.h index 991d96941bd..05d23b90348 100644 --- a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollViewManager.h +++ b/renderer/native/ios/renderer/component/scrollview/HippyScrollViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,15 +20,15 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" -#import "HPConvert.h" +#import "HippyViewManager.h" +#import "HippyConvert.h" -@interface HPConvert (UIScrollView) +@interface HippyConvert (UIScrollView) + (UIScrollViewKeyboardDismissMode)UIScrollViewKeyboardDismissMode:(id)json; @end -@interface NativeRenderScrollViewManager : NativeRenderViewManager +@interface HippyScrollViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/scrollview/HippyScrollViewManager.mm b/renderer/native/ios/renderer/component/scrollview/HippyScrollViewManager.mm new file mode 100644 index 00000000000..c19a4d98989 --- /dev/null +++ b/renderer/native/ios/renderer/component/scrollview/HippyScrollViewManager.mm @@ -0,0 +1,154 @@ +/*! + * iOS SDK + * + * Tencent is pleased to support the open source community by making + * Hippy available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "HippyUIManager.h" +#import "HippyShadowView.h" +#import "HippyScrollViewManager.h" +#import "HippyScrollView.h" +#import "HippyBridgeModule.h" + +@implementation HippyConvert (UIScrollView) + +HP_ENUM_CONVERTER(UIScrollViewKeyboardDismissMode, (@{ + @"none": @(UIScrollViewKeyboardDismissModeNone), + @"on-drag": @(UIScrollViewKeyboardDismissModeOnDrag), + @"interactive": @(UIScrollViewKeyboardDismissModeInteractive), + // Backwards compatibility + @"onDrag": @(UIScrollViewKeyboardDismissModeOnDrag), +}), + UIScrollViewKeyboardDismissModeNone, integerValue) + +HP_ENUM_CONVERTER(UIScrollViewIndicatorStyle, (@{ + @"default": @(UIScrollViewIndicatorStyleDefault), + @"black": @(UIScrollViewIndicatorStyleBlack), + @"white": @(UIScrollViewIndicatorStyleWhite), +}), + UIScrollViewIndicatorStyleDefault, integerValue) + +@end + +@implementation HippyScrollViewManager + +HIPPY_EXPORT_MODULE(ScrollView) + +- (UIView *)view { + return [[HippyScrollView alloc] init]; +} + +HIPPY_EXPORT_VIEW_PROPERTY(alwaysBounceHorizontal, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(alwaysBounceVertical, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(horizontal, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(bounces, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(bouncesZoom, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(canCancelContentTouches, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(centerContent, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(decelerationRate, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(directionalLockEnabled, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(indicatorStyle, UIScrollViewIndicatorStyle) +HIPPY_EXPORT_VIEW_PROPERTY(keyboardDismissMode, UIScrollViewKeyboardDismissMode) +HIPPY_EXPORT_VIEW_PROPERTY(maximumZoomScale, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(minimumZoomScale, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(scrollEnabled, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(pagingEnabled, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(scrollsToTop, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(showsHorizontalScrollIndicator, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(showsVerticalScrollIndicator, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(stickyHeaderIndices, NSIndexSet) +HIPPY_EXPORT_VIEW_PROPERTY(scrollEventThrottle, NSTimeInterval) +HIPPY_EXPORT_VIEW_PROPERTY(zoomScale, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(scrollIndicatorInsets, UIEdgeInsets) +HIPPY_EXPORT_VIEW_PROPERTY(snapToInterval, int) +HIPPY_EXPORT_VIEW_PROPERTY(snapToAlignment, NSString) +HIPPY_REMAP_VIEW_PROPERTY(contentOffset, scrollView.contentOffset, CGPoint) +HIPPY_EXPORT_VIEW_PROPERTY(onScrollBeginDrag, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onScroll, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onScrollEndDrag, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onMomentumScrollBegin, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onMomentumScrollEnd, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onScrollAnimationEnd, HippyDirectEventBlock) + +HIPPY_REMAP_VIEW_PROPERTY(contentInset, _scrollView.contentInset, UIEdgeInsets) + +// overflow is used both in css-layout as well as by reac-native. In css-layout +// we always want to treat overflow as scroll but depending on what the overflow +// is set to from js we want to clip drawing or not. This piece of code ensures +// that css-layout is always treating the contents of a scroll container as +// overflow: 'scroll'. +//HIPPY_CUSTOM_SHADOW_PROPERTY(overflow, OverflowType, HippyShadowView) { +// (void)json; +// view.overflow = OverflowScroll; +//} + +HIPPY_EXPORT_METHOD(getContentSize:(nonnull NSNumber *)componentTag + callback:(HippyPromiseResolveBlock)callback) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { + HippyScrollView *view = viewRegistry[componentTag]; + CGSize size = view.scrollView.contentSize; + callback(@{@"width" : @(size.width),@"height" : @(size.height)}); + }]; +} + +HIPPY_EXPORT_METHOD(scrollTo:(nonnull NSNumber *)componentTag + offsetX:(NSNumber *)x + offsetY:(NSNumber *)y + animated:(NSNumber *)animated) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ + UIView *view = viewRegistry[componentTag]; + if (view == nil) return ; + if ([view conformsToProtocol:@protocol(HippyScrollableProtocol)]) { + [(id)view scrollToOffset:(CGPoint){[x floatValue], [y floatValue]} animated:[animated boolValue]]; + } else { + HippyLogError(@"tried to scrollTo: on non-NativeRenderScrollableProtocol view %@ " + "with tag #%@", view, componentTag); + } + }]; +} + +HIPPY_EXPORT_METHOD(scrollToWithOptions:(nonnull NSNumber *)componentTag + options:(NSDictionary *)options) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ + UIView *view = viewRegistry[componentTag]; + if (view == nil) return ; + if ([view conformsToProtocol:@protocol(HippyScrollableProtocol)]) { + CGFloat duration = 1.0; + CGFloat x = 0; + CGFloat y = 0; + if (options && [options[@"duration"] isKindOfClass:[NSNumber class]]) {//毫秒 + duration = ((NSNumber *)(options[@"duration"])).floatValue / 1000.0; + } + if (options && [options[@"x"] isKindOfClass:[NSNumber class]]) { + x = ((NSNumber *)(options[@"x"])).floatValue; + } + if (options && [options[@"y"] isKindOfClass:[NSNumber class]]) { + y = ((NSNumber *)(options[@"y"])).floatValue; + } + [UIView animateWithDuration:duration animations:^{ + [(id)view scrollToOffset:(CGPoint){x,y} animated:NO]; + }]; + } else { + HippyLogError(@"tried to scrollTo: on non-NativeRenderScrollableProtocol view %@ " + "with tag #%@", view, componentTag); + } + }]; +} + +@end diff --git a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollableProtocol.h b/renderer/native/ios/renderer/component/scrollview/HippyScrollableProtocol.h similarity index 95% rename from renderer/native/ios/renderer/component/scrollview/NativeRenderScrollableProtocol.h rename to renderer/native/ios/renderer/component/scrollview/HippyScrollableProtocol.h index c7ccf40e533..d05c1d04602 100644 --- a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollableProtocol.h +++ b/renderer/native/ios/renderer/component/scrollview/HippyScrollableProtocol.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -25,7 +25,7 @@ /** * Protocol for any scrollable components inherit from UIScrollView */ -@protocol NativeRenderScrollableProtocol +@protocol HippyScrollableProtocol /** * Content size for components diff --git a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollViewManager.mm b/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollViewManager.mm deleted file mode 100644 index 1b9bfb62141..00000000000 --- a/renderer/native/ios/renderer/component/scrollview/NativeRenderScrollViewManager.mm +++ /dev/null @@ -1,153 +0,0 @@ -/*! - * iOS SDK - * - * Tencent is pleased to support the open source community by making - * NativeRender available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import "NativeRenderImpl.h" -#import "NativeRenderObjectView.h" -#import "NativeRenderScrollViewManager.h" -#import "NativeRenderScrollView.h" - -@implementation HPConvert (UIScrollView) - -HP_ENUM_CONVERTER(UIScrollViewKeyboardDismissMode, (@{ - @"none": @(UIScrollViewKeyboardDismissModeNone), - @"on-drag": @(UIScrollViewKeyboardDismissModeOnDrag), - @"interactive": @(UIScrollViewKeyboardDismissModeInteractive), - // Backwards compatibility - @"onDrag": @(UIScrollViewKeyboardDismissModeOnDrag), -}), - UIScrollViewKeyboardDismissModeNone, integerValue) - -HP_ENUM_CONVERTER(UIScrollViewIndicatorStyle, (@{ - @"default": @(UIScrollViewIndicatorStyleDefault), - @"black": @(UIScrollViewIndicatorStyleBlack), - @"white": @(UIScrollViewIndicatorStyleWhite), -}), - UIScrollViewIndicatorStyleDefault, integerValue) - -@end - -@implementation NativeRenderScrollViewManager - -NATIVE_RENDER_EXPORT_VIEW(ScrollView) - -- (UIView *)view { - return [[NativeRenderScrollView alloc] init]; -} - -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(alwaysBounceHorizontal, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(alwaysBounceVertical, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(horizontal, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(bounces, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(bouncesZoom, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(canCancelContentTouches, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(centerContent, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(decelerationRate, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(directionalLockEnabled, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(indicatorStyle, UIScrollViewIndicatorStyle) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(keyboardDismissMode, UIScrollViewKeyboardDismissMode) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(maximumZoomScale, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(minimumZoomScale, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollEnabled, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(pagingEnabled, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollsToTop, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(showsHorizontalScrollIndicator, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(showsVerticalScrollIndicator, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(stickyHeaderIndices, NSIndexSet) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollEventThrottle, NSTimeInterval) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(zoomScale, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollIndicatorInsets, UIEdgeInsets) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(snapToInterval, int) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(snapToAlignment, NSString) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(contentOffset, scrollView.contentOffset, CGPoint) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScrollBeginDrag, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScroll, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScrollEndDrag, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onMomentumScrollBegin, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onMomentumScrollEnd, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScrollAnimationEnd, NativeRenderDirectEventBlock) - -NATIVE_RENDER_REMAP_VIEW_PROPERTY(contentInset, _scrollView.contentInset, UIEdgeInsets) - -// overflow is used both in css-layout as well as by reac-native. In css-layout -// we always want to treat overflow as scroll but depending on what the overflow -// is set to from js we want to clip drawing or not. This piece of code ensures -// that css-layout is always treating the contents of a scroll container as -// overflow: 'scroll'. -//NATIVE_RENDER_CUSTOM_RENDER_OBJECT_PROPERTY(overflow, OverflowType, NativeRenderObjectView) { -// (void)json; -// view.overflow = OverflowScroll; -//} - -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(getContentSize:(nonnull NSNumber *)componentTag - callback:(RenderUIResponseSenderBlock)callback) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { - NativeRenderScrollView *view = viewRegistry[componentTag]; - CGSize size = view.scrollView.contentSize; - callback(@{@"width" : @(size.width),@"height" : @(size.height)}); - }]; -} - -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(scrollTo:(nonnull NSNumber *)componentTag - offsetX:(NSNumber *)x - offsetY:(NSNumber *)y - animated:(NSNumber *)animated) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ - UIView *view = viewRegistry[componentTag]; - if (view == nil) return ; - if ([view conformsToProtocol:@protocol(NativeRenderScrollableProtocol)]) { - [(id)view scrollToOffset:(CGPoint){[x floatValue], [y floatValue]} animated:[animated boolValue]]; - } else { - HPLogError(@"tried to scrollTo: on non-NativeRenderScrollableProtocol view %@ " - "with tag #%@", view, componentTag); - } - }]; -} - -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(scrollToWithOptions:(nonnull NSNumber *)componentTag - options:(NSDictionary *)options) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ - UIView *view = viewRegistry[componentTag]; - if (view == nil) return ; - if ([view conformsToProtocol:@protocol(NativeRenderScrollableProtocol)]) { - CGFloat duration = 1.0; - CGFloat x = 0; - CGFloat y = 0; - if (options && [options[@"duration"] isKindOfClass:[NSNumber class]]) {//毫秒 - duration = ((NSNumber *)(options[@"duration"])).floatValue / 1000.0; - } - if (options && [options[@"x"] isKindOfClass:[NSNumber class]]) { - x = ((NSNumber *)(options[@"x"])).floatValue; - } - if (options && [options[@"y"] isKindOfClass:[NSNumber class]]) { - y = ((NSNumber *)(options[@"y"])).floatValue; - } - [UIView animateWithDuration:duration animations:^{ - [(id)view scrollToOffset:(CGPoint){x,y} animated:NO]; - }]; - } else { - HPLogError(@"tried to scrollTo: on non-NativeRenderScrollableProtocol view %@ " - "with tag #%@", view, componentTag); - } - }]; -} - -@end diff --git a/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerView.h b/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerView.h index c888e0dbdd9..08d7afc520c 100644 --- a/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerView.h +++ b/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,7 +21,7 @@ */ #import -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" #import "NativeRenderListTableView.h" #import "NativeRenderWaterfallView.h" @@ -32,13 +32,13 @@ NS_ASSUME_NONNULL_BEGIN @interface NativeRenderSmartViewPagerView : NativeRenderWaterfallView /** - * NativeRender events + * Hippy events */ -@property(nonatomic, copy) NativeRenderDirectEventBlock initialListReady; -@property(nonatomic, copy) NativeRenderDirectEventBlock onScrollBeginDrag; -@property(nonatomic, copy) NativeRenderDirectEventBlock onScrollEndDrag; -@property(nonatomic, strong) NativeRenderDirectEventBlock onPageSelected; -@property(nonatomic, strong) NativeRenderDirectEventBlock onPageScrollStateChanged; +@property(nonatomic, copy) HippyDirectEventBlock initialListReady; +@property(nonatomic, copy) HippyDirectEventBlock onScrollBeginDrag; +@property(nonatomic, copy) HippyDirectEventBlock onScrollEndDrag; +@property(nonatomic, strong) HippyDirectEventBlock onPageSelected; +@property(nonatomic, strong) HippyDirectEventBlock onPageScrollStateChanged; /** * Indicate view pager view scroll circule, default is NO diff --git a/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerView.mm b/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerView.mm index 5fa87c03e69..3df57183838 100644 --- a/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerView.mm +++ b/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -24,13 +24,13 @@ #import "NativeRenderBaseListViewDataSource.h" #import "NativeRenderFooterRefresh.h" #import "NativeRenderHeaderRefresh.h" -#import "NativeRenderImpl.h" -#import "NativeRenderObjectView.h" +#import "HippyUIManager.h" +#import "HippyShadowView.h" #import "NativeRenderSmartViewPagerView.h" #import "NativeRenderScrollProtocol.h" #import "UIView+MountEvent.h" #import "UIView+Render.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #include @@ -79,7 +79,7 @@ - (void)initialization { _circular = NO; _autoplay = NO; - _itemWidth = self.nativeRenderObjectView.frame.size.width; + _itemWidth = self.hippyShadowView.frame.size.width; _previousMargin = 0.0f; _nextMargin = 0.0f; _pageGap = 0; @@ -209,8 +209,8 @@ - (void)setPreviousMargin:(CGFloat)previousMargin nextMargin:(CGFloat)nextMargin _previousMargin = previousMargin; _nextMargin = nextMargin; _pageGap = pageGap; - _itemWidth = self.nativeRenderObjectView.frame.size.width - (previousMargin + nextMargin + pageGap * 2); - _viewPagerLayout.itemSize = CGSizeMake(_itemWidth, self.nativeRenderObjectView.frame.size.height); + _itemWidth = self.hippyShadowView.frame.size.width - (previousMargin + nextMargin + pageGap * 2); + _viewPagerLayout.itemSize = CGSizeMake(_itemWidth, self.hippyShadowView.frame.size.height); _viewPagerLayout.minimumLineSpacing = pageGap; _viewPagerLayout.minimumInteritemSpacing = pageGap; _currentPage = [self adjustInitialPage:_initialPage]; @@ -244,7 +244,7 @@ - (Class)listItemClass { - (__kindof UICollectionViewLayout *)collectionViewLayout { UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; layout.minimumLineSpacing = .0f; - layout.itemSize = CGSizeMake(self.nativeRenderObjectView.frame.size.width, self.nativeRenderObjectView.frame.size.height); + layout.itemSize = CGSizeMake(self.hippyShadowView.frame.size.width, self.hippyShadowView.frame.size.height); layout.scrollDirection = UICollectionViewScrollDirectionHorizontal; _viewPagerLayout = layout; return layout; @@ -266,12 +266,12 @@ - (void)setFrame:(CGRect)frame { [super setFrame:frame]; } -- (void)nativeRenderSetFrame:(CGRect)frame { - [super nativeRenderSetFrame:frame]; +- (void)hippySetFrame:(CGRect)frame { + [super hippySetFrame:frame]; self.collectionView.frame = self.bounds; } -- (void)setInitialListReady:(NativeRenderDirectEventBlock)initialListReady { +- (void)setInitialListReady:(HippyDirectEventBlock)initialListReady { _initialListReady = initialListReady; _isInitialListReady = NO; } @@ -287,7 +287,7 @@ - (void)reloadData { [self.collectionView reloadData]; } -- (void)didUpdateNativeRenderSubviews { +- (void)didUpdateHippySubviews { [self refreshItemNodes]; [self reloadData]; } @@ -312,8 +312,8 @@ - (NSArray *)refreshItemIndexArrayWithOldArrayLength:(NSInteger)length { } - (void)refreshItemNodes { - [self.dataSource setDataSource:self.nativeRenderObjectView.subcomponents containBannerView:NO]; - _itemIndexArray = [self refreshItemIndexArrayWithOldArrayLength:self.nativeRenderObjectView.subcomponents.count]; + [self.dataSource setDataSource:self.hippyShadowView.subcomponents containBannerView:NO]; + _itemIndexArray = [self refreshItemIndexArrayWithOldArrayLength:self.hippyShadowView.subcomponents.count]; [self setPreviousMargin:_previousMargin nextMargin:_nextMargin pageGap:_pageGap]; } @@ -345,7 +345,7 @@ - (CGSize)collectionView:(UICollectionView *)collectionView sizeForItemAtIndexPath:(NSIndexPath *)indexPath { NSInteger cellIndex = _itemIndexArray[indexPath.row].integerValue; NSIndexPath *adjustIndexPath = [NSIndexPath indexPathForRow:cellIndex inSection:indexPath.section]; - NativeRenderObjectView *renderObject = [_dataSource cellForIndexPath:adjustIndexPath]; + HippyShadowView *renderObject = [_dataSource cellForIndexPath:adjustIndexPath]; return renderObject.frame.size; } @@ -355,7 +355,7 @@ - (void)collectionView:(UICollectionView *)collectionView NSInteger cellIndex = _itemIndexArray[indexPath.row].integerValue; NSIndexPath *adjustIndexPath = [NSIndexPath indexPathForRow:cellIndex inSection:indexPath.section]; NativeRenderWaterfallViewCell *hpCell = (NativeRenderWaterfallViewCell *)cell; - NativeRenderObjectView *renderObject = [_dataSource cellForIndexPath:adjustIndexPath]; + HippyShadowView *renderObject = [_dataSource cellForIndexPath:adjustIndexPath]; [renderObject recusivelySetCreationTypeToInstant]; UIView *cellView = [self.renderImpl createViewRecursivelyFromRenderObject:renderObject]; hpCell.cellView = cellView; @@ -537,6 +537,6 @@ - (NSInteger)collectionView:(UICollectionView *)collectionView } #pragma mark NativeRenderRefresh Delegate -- (void)refreshView:(NativeRenderRefresh *)refreshView statusChanged:(NativeRenderRefreshStatus)status { +- (void)refreshView:(HippyRefresh *)refreshView statusChanged:(HippyRefreshStatus)status { } @end diff --git a/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerViewManager.h b/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerViewManager.h index 1d6f830f0b8..d218ec14d97 100644 --- a/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerViewManager.h +++ b/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderSmartViewPagerViewManager : NativeRenderViewManager +@interface NativeRenderSmartViewPagerViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerViewManager.mm b/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerViewManager.mm index 4464eb5b97a..facd86c4a93 100644 --- a/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerViewManager.mm +++ b/renderer/native/ios/renderer/component/smartViewPager/NativeRenderSmartViewPagerViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,40 +20,41 @@ * limitations under the License. */ -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" #import "NativeRenderSmartViewPagerViewManager.h" #import "NativeRenderSmartViewPagerView.h" +#import "HippyBridgeModule.h" @implementation NativeRenderSmartViewPagerViewManager -NATIVE_RENDER_EXPORT_VIEW(SmartViewPager) +HIPPY_EXPORT_MODULE(SmartViewPager) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollEventThrottle, NSTimeInterval) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(initialListReady, NativeRenderDirectEventBlock); -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScrollBeginDrag, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onPageSelected, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScroll, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onPageScrollStateChanged, NativeRenderDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(scrollEventThrottle, NSTimeInterval) +HIPPY_EXPORT_VIEW_PROPERTY(initialListReady, HippyDirectEventBlock); +HIPPY_EXPORT_VIEW_PROPERTY(onScrollBeginDrag, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onPageSelected, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onScroll, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onPageScrollStateChanged, HippyDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(pageGap, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(previousMargin, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(nextMargin, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(autoplayTimeInterval, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(initialPage, NSInteger) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(circular, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(autoplay, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(pageGap, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(previousMargin, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(nextMargin, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(autoplayTimeInterval, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(initialPage, NSInteger) +HIPPY_EXPORT_VIEW_PROPERTY(circular, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(autoplay, BOOL) - (UIView *)view { return [[NativeRenderSmartViewPagerView alloc] init]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(setPage:(nonnull NSNumber *)componentTag +HIPPY_EXPORT_METHOD(setPage:(nonnull NSNumber *)componentTag pageNumber:(NSNumber *)pageNumber) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ UIView *view = viewRegistry[componentTag]; if (view == nil || ![view isKindOfClass:[NativeRenderSmartViewPagerView class]]) { - HPLogError(@"tried to setPage: on an error viewPager %@ " + HippyLogError(@"tried to setPage: on an error viewPager %@ " "with tag #%@", view, componentTag); } NSInteger pageNumberInteger = pageNumber.integerValue; @@ -61,12 +62,12 @@ - (UIView *)view { }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(setPageWithoutAnimation:(nonnull NSNumber *)componentTag +HIPPY_EXPORT_METHOD(setPageWithoutAnimation:(nonnull NSNumber *)componentTag pageNumber:(NSNumber *)pageNumber) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ UIView *view = viewRegistry[componentTag]; if (view == nil || ![view isKindOfClass:[NativeRenderSmartViewPagerView class]]) { - HPLogError(@"tried to setPage: on an error viewPager %@ " + HippyLogError(@"tried to setPage: on an error viewPager %@ " "with tag #%@", view, componentTag); } NSInteger pageNumberInteger = pageNumber.integerValue; @@ -74,9 +75,9 @@ - (UIView *)view { }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(getPageIndex:(nonnull NSNumber *)componentTag - callback:(RenderUIResponseSenderBlock)callback) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(getPageIndex:(nonnull NSNumber *)componentTag + callback:(HippyPromiseResolveBlock)callback) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderSmartViewPagerView *view = viewRegistry[componentTag]; NSInteger currrentPage = [view getCurrentPage]; callback(@(currrentPage)); diff --git a/renderer/native/ios/renderer/component/text/NativeRenderObjectText.h b/renderer/native/ios/renderer/component/text/NativeRenderObjectText.h index f816498c3cb..7a8cde14441 100644 --- a/renderer/native/ios/renderer/component/text/NativeRenderObjectText.h +++ b/renderer/native/ios/renderer/component/text/NativeRenderObjectText.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "HPConvert+NativeRender.h" -#import "NativeRenderObjectView.h" +#import "HippyConvert+NativeRender.h" +#import "HippyShadowView.h" typedef NS_ENUM(NSInteger, NativeRenderSizeComparison) { NativeRenderSizeTooLarge, @@ -45,7 +45,7 @@ hippy::LayoutSize textMeasureFunc(float width, hippy::LayoutMeasureMode widthMea __unused hippy::LayoutMeasureMode heightMeasureMode, void *layoutContext); -@interface NativeRenderObjectText : NativeRenderObjectView { +@interface NativeRenderObjectText : HippyShadowView { @protected NSTextStorage *_cachedTextStorage; CGFloat _cachedTextStorageWidth; diff --git a/renderer/native/ios/renderer/component/text/NativeRenderObjectText.mm b/renderer/native/ios/renderer/component/text/NativeRenderObjectText.mm index adcab5bbc19..f62e5760264 100644 --- a/renderer/native/ios/renderer/component/text/NativeRenderObjectText.mm +++ b/renderer/native/ios/renderer/component/text/NativeRenderObjectText.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,10 +20,10 @@ * limitations under the License. */ -#import "HPConvert.h" -#import "HPI18nUtils.h" -#import "HPToolUtils.h" -#import "NativeRenderFont.h" +#import "HippyConvert.h" +#import "HippyI18nUtils.h" +#import "HippyUtils.h" +#import "HippyFont.h" #import "NativeRenderObjectText.h" #import "NativeRenderText.h" #import "NativeRenderTextView.h" @@ -163,7 +163,7 @@ - (instancetype)init { _fontSizeMultiplier = 1.0; _lineHeightMultiple = 1.0f; _textAlign = NSTextAlignmentLeft; - if (NSWritingDirectionRightToLeft == [[HPI18nUtils sharedInstance] writingDirectionForCurrentAppLanguage]) { + if (NSWritingDirectionRightToLeft == [[HippyI18nUtils sharedInstance] writingDirectionForCurrentAppLanguage]) { self.textAlign = NSTextAlignmentRight; } } @@ -198,13 +198,13 @@ - (void)contentSizeMultiplierDidChange:(__unused NSNotification *)note { UIEdgeInsets padding = self.paddingAsInsets; CGFloat width = self.frame.size.width - (padding.left + padding.right); - NSNumber *parentTag = [[self parentComponent] componentTag]; + NSNumber *parentTag = [[self parentComponent] hippyTag]; // MTTlayout NSTextStorage *textStorage = [self buildTextStorageForWidth:width widthMode:hippy::LayoutMeasureMode::Exactly]; CGRect textFrame = [self calculateTextFrame:textStorage]; UIColor *color = self.color ?: [UIColor blackColor]; [applierBlocks addObject:^(NSDictionary *viewRegistry) { - NativeRenderText *view = (NativeRenderText *)viewRegistry[self.componentTag]; + NativeRenderText *view = (NativeRenderText *)viewRegistry[self.hippyTag]; view.textFrame = textFrame; view.textStorage = textStorage; view.textColor = color; @@ -236,11 +236,11 @@ - (void)amendLayoutBeforeMount:(NSMutableSet *)blocks NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer]; NSRange characterRange = [layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL]; [textStorage enumerateAttribute:NativeRenderRenderObjectAttributeName inRange:characterRange options:0 usingBlock:^( - NativeRenderObjectView *child, NSRange range, __unused BOOL *_) { + HippyShadowView *child, NSRange range, __unused BOOL *_) { if (child) { float width = child.width, height = child.height; if (isnan(width) || isnan(height)) { - HPLogError(@"Views nested within a must have a width and height"); + HippyLogError(@"Views nested within a must have a width and height"); } // Use line fragment's rect instead of glyph rect for calculation, @@ -373,10 +373,10 @@ - (void)dirtyText:(BOOL)needToDoLayout { auto domManager = self.domManager.lock(); auto weakDomManager = self.domManager; if (domManager) { - __weak NativeRenderObjectView *weakSelf = self; + __weak HippyShadowView *weakSelf = self; auto domNodeAction = [needToDoLayout, weakSelf, weakDomManager](){ @autoreleasepool { - NativeRenderObjectView *strongSelf = weakSelf; + HippyShadowView *strongSelf = weakSelf; if (!strongSelf) { return; } @@ -384,7 +384,7 @@ - (void)dirtyText:(BOOL)needToDoLayout { if (!strongDomManager) { return; } - int32_t componentTag = [[strongSelf componentTag] intValue]; + int32_t componentTag = [[strongSelf hippyTag] intValue]; auto domNode = strongDomManager->GetNode(strongSelf.rootNode, componentTag); if (domNode) { domNode->GetLayoutNode()->MarkDirty(); @@ -469,7 +469,7 @@ - (NSAttributedString *)_attributedStringWithStyleInfo:(NativeRenderAttributedSt f = [UIFont fontWithName:styleInfo.fontFamily size:[styleInfo.fontSize floatValue]]; } - UIFont *font = [NativeRenderFont updateFont:f + UIFont *font = [HippyFont updateFont:f withFamily:styleInfo.fontFamily size:styleInfo.fontSize weight:styleInfo.fontWeight @@ -479,7 +479,7 @@ - (NSAttributedString *)_attributedStringWithStyleInfo:(NativeRenderAttributedSt CGFloat heightOfTallestSubview = 0.0; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.text ?: @""]; - for (NativeRenderObjectView *child in [self subcomponents]) { + for (HippyShadowView *child in [self subcomponents]) { if ([child isKindOfClass:[NativeRenderObjectText class]]) { NativeRenderObjectText *shadowText = (NativeRenderObjectText *)child; NativeRenderAttributedStringStyleInfo *childInfo = [NativeRenderAttributedStringStyleInfo new]; @@ -500,7 +500,7 @@ - (NSAttributedString *)_attributedStringWithStyleInfo:(NativeRenderAttributedSt float width = 0, height = 0; auto domManager = [child domManager].lock(); if (domManager) { - int32_t componentTag = [child.componentTag intValue]; + int32_t componentTag = [child.hippyTag intValue]; auto domNode = domManager->GetNode(child.rootNode, componentTag); if (domNode) { width = domNode->GetLayoutNode()->GetStyleWidth(); @@ -512,7 +512,7 @@ - (NSAttributedString *)_attributedStringWithStyleInfo:(NativeRenderAttributedSt } } if (isnan(width) || isnan(height)) { - HPLogError(@"Views nested within a must have a width and height"); + HippyLogError(@"Views nested within a must have a width and height"); } // take margin into account // FIXME: margin not working, may have bug in layout process @@ -569,7 +569,7 @@ - (NSAttributedString *)_attributedStringWithStyleInfo:(NativeRenderAttributedSt [self _addAttribute:NSFontAttributeName withValue:font toAttributedString:attributedString]; [self _addAttribute:NSKernAttributeName withValue:styleInfo.letterSpacing toAttributedString:attributedString]; - [self _addAttribute:NativeRenderComponentTagAttributeName withValue:self.componentTag toAttributedString:attributedString]; + [self _addAttribute:NativeRenderComponentTagAttributeName withValue:self.hippyTag toAttributedString:attributedString]; if (NativeRenderTextVerticalAlignUndefined != self.verticalAlignType) { [self _addAttribute:NativeRenderTextVerticalAlignAttributeName withValue:@(self.verticalAlignType) @@ -893,7 +893,7 @@ - (void)setDomManager:(std::weak_ptr)domManager { [super setDomManager:domManager]; auto shared_domNode = domManager.lock(); if (shared_domNode) { - int32_t componentTag = [self.componentTag intValue]; + int32_t componentTag = [self.hippyTag intValue]; auto node = shared_domNode->GetNode(self.rootNode, componentTag); if (node) { __weak NativeRenderObjectText *weakSelf = self; @@ -945,7 +945,7 @@ - (void)setAllowFontScaling:(BOOL)allowFontScaling { return; } _allowFontScaling = allowFontScaling; - for (NativeRenderObjectView *child in [self subcomponents]) { + for (HippyShadowView *child in [self subcomponents]) { if ([child isKindOfClass:[NativeRenderObjectText class]]) { ((NativeRenderObjectText *)child).allowFontScaling = allowFontScaling; } @@ -959,10 +959,10 @@ - (void)setFontSizeMultiplier:(CGFloat)fontSizeMultiplier { } _fontSizeMultiplier = fontSizeMultiplier; if (_fontSizeMultiplier == 0) { - HPLogError(@"fontSizeMultiplier value must be > zero."); + HippyLogError(@"fontSizeMultiplier value must be > zero."); _fontSizeMultiplier = 1.0; } - for (NativeRenderObjectView *child in [self subcomponents]) { + for (HippyShadowView *child in [self subcomponents]) { if ([child isKindOfClass:[NativeRenderObjectText class]]) { ((NativeRenderObjectText *)child).fontSizeMultiplier = fontSizeMultiplier; } @@ -980,11 +980,11 @@ - (void)setMinimumFontScale:(CGFloat)minimumFontScale { _needDirtyText = YES; } -- (void)didUpdateNativeRenderSubviews { - [super didUpdateNativeRenderSubviews]; +- (void)didUpdateHippySubviews { + [super didUpdateHippySubviews]; auto domManager = [self domManager].lock(); if (domManager) { - int32_t componentTag = [self.componentTag intValue]; + int32_t componentTag = [self.hippyTag intValue]; auto node = domManager->GetNode(self.rootNode, componentTag); if (node) { node->GetLayoutNode()->MarkDirty(); diff --git a/renderer/native/ios/renderer/component/text/NativeRenderText.h b/renderer/native/ios/renderer/component/text/NativeRenderText.h index 07b5a067d2f..f478de9f4ad 100644 --- a/renderer/native/ios/renderer/component/text/NativeRenderText.h +++ b/renderer/native/ios/renderer/component/text/NativeRenderText.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/text/NativeRenderText.mm b/renderer/native/ios/renderer/component/text/NativeRenderText.mm index 4ec810847b3..7b3ffdb0604 100644 --- a/renderer/native/ios/renderer/component/text/NativeRenderText.mm +++ b/renderer/native/ios/renderer/component/text/NativeRenderText.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,9 +22,9 @@ #import "NativeRenderText.h" #import "NativeRenderObjectText.h" -#import "HPToolUtils.h" -#import "UIView+NativeRender.h" -#import "HPLog.h" +#import "HippyUtils.h" +#import "UIView+Hippy.h" +#import "HippyLog.h" static void collectNonTextDescendants(NativeRenderText *view, NSMutableArray *nonTextDescendants) { for (UIView *child in view.subcomponents) { @@ -52,26 +52,26 @@ - (instancetype)initWithFrame:(CGRect)frame { - (NSString *)description { NSString *superDescription = super.description; NSRange semicolonRange = [superDescription rangeOfString:@";"]; - NSString *replacement = [NSString stringWithFormat:@"; componentTag: %@; text: %@", self.componentTag, self.textStorage.string]; + NSString *replacement = [NSString stringWithFormat:@"; componentTag: %@; text: %@", self.hippyTag, self.textStorage.string]; return [superDescription stringByReplacingCharactersInRange:semicolonRange withString:replacement]; } -- (void)nativeRenderSetFrame:(CGRect)frame { +- (void)hippySetFrame:(CGRect)frame { // Text looks super weird if its frame is animated. // This disables the frame animation, without affecting opacity, etc. [UIView performWithoutAnimation:^{ - [super nativeRenderSetFrame:frame]; + [super hippySetFrame:frame]; }]; } -- (void)removeNativeRenderSubview:(UIView *)subview { +- (void)removeHippySubview:(UIView *)subview { if ([[self subcomponents] containsObject:subview]) { - [super removeNativeRenderSubview:subview]; + [super removeHippySubview:subview]; } else { NSArray *hippySubviews = [self subcomponents]; for (UIView *hippySubview in hippySubviews) { - [hippySubview removeNativeRenderSubview:subview]; + [hippySubview removeHippySubview:subview]; } } } @@ -80,7 +80,7 @@ - (BOOL)canBeRetrievedFromViewCache { return NO; } -- (void)nativeRenderSetInheritedBackgroundColor:(__unused UIColor *)inheritedBackgroundColor { +- (void)hippySetInheritedBackgroundColor:(__unused UIColor *)inheritedBackgroundColor { // mttrn: // UIColor *backgroundColor = [self rightBackgroundColorOfTheme]; // @@ -90,7 +90,7 @@ - (void)nativeRenderSetInheritedBackgroundColor:(__unused UIColor *)inheritedBac // self.backgroundColor = inheritedBackgroundColor; } -- (void)didUpdateNativeRenderSubviews { +- (void)didUpdateHippySubviews { // Do nothing, as subviews are managed by `setTextStorage:` method } @@ -164,8 +164,8 @@ - (void)drawRect:(__unused CGRect)rect { } } -- (NSNumber *)componentTagAtPoint:(CGPoint)point { - NSNumber *componentTag = self.componentTag; +- (NSNumber *)hippyTagAtPoint:(CGPoint)point { + NSNumber *componentTag = self.hippyTag; CGFloat fraction; NSLayoutManager *layoutManager = _textStorage.layoutManagers.firstObject; @@ -222,7 +222,7 @@ - (NSString *)accessibilityLabel { } - (void)setBackgroundImageUrl:(NSString *)backgroundImageUrl { - HPLogWarn(@"Warning: backgroundImage is not available in NativeRenderText."); + HippyLogWarn(@"Warning: backgroundImage is not available in NativeRenderText."); } @end diff --git a/renderer/native/ios/renderer/component/text/NativeRenderTextManager.h b/renderer/native/ios/renderer/component/text/NativeRenderTextManager.h index 3aad33707b9..b99ae048c7b 100644 --- a/renderer/native/ios/renderer/component/text/NativeRenderTextManager.h +++ b/renderer/native/ios/renderer/component/text/NativeRenderTextManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderTextManager : NativeRenderViewManager +@interface NativeRenderTextManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/text/NativeRenderTextManager.mm b/renderer/native/ios/renderer/component/text/NativeRenderTextManager.mm index ddad034f82c..369de267217 100644 --- a/renderer/native/ios/renderer/component/text/NativeRenderTextManager.mm +++ b/renderer/native/ios/renderer/component/text/NativeRenderTextManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,14 +21,14 @@ */ #import "NativeRenderTextManager.h" -#import "HPConvert.h" +#import "HippyConvert.h" #import "NativeRenderObjectText.h" #import "NativeRenderText.h" #import "NativeRenderTextView.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" static void collectDirtyNonTextDescendants(NativeRenderObjectText *renderObject, NSMutableArray *nonTextDescendants) { - for (NativeRenderObjectView *child in renderObject.subcomponents) { + for (HippyShadowView *child in renderObject.subcomponents) { if ([child isKindOfClass:[NativeRenderObjectText class]]) { collectDirtyNonTextDescendants((NativeRenderObjectText *)child, nonTextDescendants); } else if ([child isTextDirty]) { @@ -44,48 +44,48 @@ - (NSTextStorage *)buildTextStorageForWidth:(CGFloat)width widthMode:(hippy::Lay @implementation NativeRenderTextManager -NATIVE_RENDER_EXPORT_VIEW(Text) +HIPPY_EXPORT_MODULE(Text) - (UIView *)view { return [NativeRenderText new]; } -- (NativeRenderObjectView *)nativeRenderObjectView { +- (HippyShadowView *)hippyShadowView { return [NativeRenderObjectText new]; } #pragma mark - Shadow properties -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(color, UIColor) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(fontFamily, NSString) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(fontSize, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(fontWeight, NSString) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(fontStyle, NSString) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(fontVariant, NSArray) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(isHighlighted, BOOL) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(letterSpacing, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(lineHeightMultiple, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(lineSpacingMultiplier, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(lineHeight, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(numberOfLines, NSUInteger) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(ellipsizeMode, NSLineBreakMode) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(textAlign, NSTextAlignment) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(textDecorationStyle, NSUnderlineStyle) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(textDecorationColor, UIColor) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(textDecorationLine, NativeRenderTextDecorationLineType) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(allowFontScaling, BOOL) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(opacity, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(textShadowOffset, CGSize) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(textShadowRadius, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(textShadowColor, UIColor) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(adjustsFontSizeToFit, BOOL) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(minimumFontScale, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(text, NSString) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(autoLetterSpacing, BOOL) - -- (NativeRenderRenderUIBlock)uiBlockToAmendWithRenderObjectRegistry:(NSDictionary *)renderObjectRegistry { - for (NativeRenderObjectView *rootView in renderObjectRegistry.allValues) { - if (![rootView isNativeRenderRootView]) { +HIPPY_EXPORT_SHADOW_PROPERTY(color, UIColor) +HIPPY_EXPORT_SHADOW_PROPERTY(fontFamily, NSString) +HIPPY_EXPORT_SHADOW_PROPERTY(fontSize, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(fontWeight, NSString) +HIPPY_EXPORT_SHADOW_PROPERTY(fontStyle, NSString) +HIPPY_EXPORT_SHADOW_PROPERTY(fontVariant, NSArray) +HIPPY_EXPORT_SHADOW_PROPERTY(isHighlighted, BOOL) +HIPPY_EXPORT_SHADOW_PROPERTY(letterSpacing, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(lineHeightMultiple, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(lineSpacingMultiplier, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(lineHeight, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(numberOfLines, NSUInteger) +HIPPY_EXPORT_SHADOW_PROPERTY(ellipsizeMode, NSLineBreakMode) +HIPPY_EXPORT_SHADOW_PROPERTY(textAlign, NSTextAlignment) +HIPPY_EXPORT_SHADOW_PROPERTY(textDecorationStyle, NSUnderlineStyle) +HIPPY_EXPORT_SHADOW_PROPERTY(textDecorationColor, UIColor) +HIPPY_EXPORT_SHADOW_PROPERTY(textDecorationLine, NativeRenderTextDecorationLineType) +HIPPY_EXPORT_SHADOW_PROPERTY(allowFontScaling, BOOL) +HIPPY_EXPORT_SHADOW_PROPERTY(opacity, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(textShadowOffset, CGSize) +HIPPY_EXPORT_SHADOW_PROPERTY(textShadowRadius, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(textShadowColor, UIColor) +HIPPY_EXPORT_SHADOW_PROPERTY(adjustsFontSizeToFit, BOOL) +HIPPY_EXPORT_SHADOW_PROPERTY(minimumFontScale, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(text, NSString) +HIPPY_EXPORT_SHADOW_PROPERTY(autoLetterSpacing, BOOL) + +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(NSDictionary *)renderObjectRegistry { + for (HippyShadowView *rootView in renderObjectRegistry.allValues) { + if (![rootView isHippyRootView]) { // This isn't a root view continue; } @@ -95,11 +95,11 @@ - (NativeRenderRenderUIBlock)uiBlockToAmendWithRenderObjectRegistry:(NSDictionar continue; } - NSMutableArray *queue = [NSMutableArray arrayWithObject:rootView]; + NSMutableArray *queue = [NSMutableArray arrayWithObject:rootView]; for (NSInteger i = 0; i < queue.count; i++) { - NativeRenderObjectView *renderObject = queue[i]; + HippyShadowView *renderObject = queue[i]; if (!renderObject) { - HPLogWarn(@"renderObject is nil, please remain xcode state and call rainywan"); + HippyLogWarn(@"renderObject is nil, please remain xcode state and call rainywan"); continue; } // NSAssert([renderObject isTextDirty], @"Don't process any nodes that don't have dirty text"); @@ -109,7 +109,7 @@ - (NativeRenderRenderUIBlock)uiBlockToAmendWithRenderObjectRegistry:(NSDictionar [(NativeRenderObjectText *)renderObject recomputeText]; collectDirtyNonTextDescendants((NativeRenderObjectText *)renderObject, queue); } else { - for (NativeRenderObjectView *child in [renderObject subcomponents]) { + for (HippyShadowView *child in [renderObject subcomponents]) { if ([child isTextDirty]) { [queue addObject:child]; } @@ -123,11 +123,11 @@ - (NativeRenderRenderUIBlock)uiBlockToAmendWithRenderObjectRegistry:(NSDictionar return nil; } -- (NativeRenderRenderUIBlock)uiBlockToAmendWithNativeRenderObjectView:(NativeRenderObjectText *)renderObjectText { - NSNumber *componentTag = renderObjectText.componentTag; +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowView:(NativeRenderObjectText *)renderObjectText { + NSNumber *componentTag = renderObjectText.hippyTag; UIEdgeInsets padding = renderObjectText.paddingAsInsets; - return ^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + return ^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderText *text = viewRegistry[componentTag]; text.contentInset = padding; }; diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderBaseTextInput.h b/renderer/native/ios/renderer/component/textinput/NativeRenderBaseTextInput.h index 7ec55a8634b..8c3d0a4c844 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderBaseTextInput.h +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderBaseTextInput.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,9 +20,9 @@ * limitations under the License. */ -#import "NativeRenderView.h" +#import "HippyView.h" -@interface NativeRenderBaseTextInput : NativeRenderView +@interface NativeRenderBaseTextInput : HippyView @property (nonatomic, strong) UIFont *font; @property (nonatomic, assign) UIEdgeInsets contentInset; diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderBaseTextInput.m b/renderer/native/ios/renderer/component/textinput/NativeRenderBaseTextInput.m index a0c076998c2..c69c7d432a2 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderBaseTextInput.m +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderBaseTextInput.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderObjectTextView.h b/renderer/native/ios/renderer/component/textinput/NativeRenderObjectTextView.h index 28528f0d35c..1b24867f000 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderObjectTextView.h +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderObjectTextView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,9 +20,9 @@ * limitations under the License. */ -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" -@interface NativeRenderObjectTextView : NativeRenderObjectView +@interface NativeRenderObjectTextView : HippyShadowView @property (nonatomic, copy) NSString *text; @property (nonatomic, copy) NSString *placeholder; diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderObjectTextView.mm b/renderer/native/ios/renderer/component/textinput/NativeRenderObjectTextView.mm index 3332536157f..6c798928ef0 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderObjectTextView.mm +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderObjectTextView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "HPToolUtils.h" +#import "HippyUtils.h" #import "NativeRenderObjectTextView.h" #include "dom/dom_manager.h" @@ -67,7 +67,7 @@ - (void)setDomManager:(std::weak_ptr)domManager { [super setDomManager:domManager]; auto shared_domNode = domManager.lock(); if (shared_domNode) { - int32_t componentTag = [self.componentTag intValue]; + int32_t componentTag = [self.hippyTag intValue]; auto node = shared_domNode->GetNode(self.rootNode, componentTag); if (node) { __weak NativeRenderObjectTextView *weakSelf = self; @@ -97,15 +97,15 @@ - (NSDictionary *)mergeProps:(NSDictionary *)props { return newProps; } -- (void)didUpdateNativeRenderSubviews { - [super didUpdateNativeRenderSubviews]; +- (void)didUpdateHippySubviews { + [super didUpdateHippySubviews]; auto domManager = [self domManager].lock(); if (domManager) { - int32_t componentTag = [self.componentTag intValue]; - __weak NativeRenderObjectView *weakSelf = self; + int32_t componentTag = [self.hippyTag intValue]; + __weak HippyShadowView *weakSelf = self; std::vector> ops_ = {[componentTag, weakSelf, domManager](){ @autoreleasepool { - NativeRenderObjectView *strongSelf = weakSelf; + HippyShadowView *strongSelf = weakSelf; if (strongSelf) { auto domNode = domManager->GetNode(strongSelf.rootNode, componentTag); if (domNode) { diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderTextField.h b/renderer/native/ios/renderer/component/textinput/NativeRenderTextField.h index 2cb300699e3..dee44d3737a 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderTextField.h +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderTextField.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,8 +21,8 @@ */ #import -#import "NativeRenderView.h" -#import "NativeRenderComponentProtocol.h" +#import "HippyView.h" +#import "HippyComponent.h" #import "NativeRenderBaseTextInput.h" @protocol NativeRenderUITextFieldResponseDelegate @@ -35,13 +35,13 @@ @property (nonatomic, assign) BOOL textWasPasted; @property (nonatomic, weak) id responderDelegate; -@property (nonatomic, copy) NativeRenderDirectEventBlock onBlur; -@property (nonatomic, copy) NativeRenderDirectEventBlock onFocus; +@property (nonatomic, copy) HippyDirectEventBlock onBlur; +@property (nonatomic, copy) HippyDirectEventBlock onFocus; @property (nonatomic, assign) BOOL editable; @end @interface NativeRenderTextField : NativeRenderBaseTextInput -@property (nonatomic, copy) NativeRenderDirectEventBlock onKeyPress; +@property (nonatomic, copy) HippyDirectEventBlock onKeyPress; @property (nonatomic, assign) BOOL autoCorrect; //@property (nonatomic, assign) UIEdgeInsets contentInset; @property (nonatomic, strong) UIColor *placeholderTextColor; @@ -49,17 +49,17 @@ @property (nonatomic, strong) NSNumber *maxLength; @property (nonatomic, assign) BOOL textWasPasted; -@property (nonatomic, copy) NativeRenderDirectEventBlock onSelectionChange; +@property (nonatomic, copy) HippyDirectEventBlock onSelectionChange; - (void)textFieldDidChange; -@property (nonatomic, copy) NativeRenderDirectEventBlock onChangeText; +@property (nonatomic, copy) HippyDirectEventBlock onChangeText; -@property (nonatomic, copy) NativeRenderDirectEventBlock onBlur; -@property (nonatomic, copy) NativeRenderDirectEventBlock onFocus; -@property (nonatomic, copy) NativeRenderDirectEventBlock onEndEditing; -@property (nonatomic, copy) NativeRenderDirectEventBlock onKeyboardWillShow; -@property (nonatomic, copy) NativeRenderDirectEventBlock onKeyboardWillHide; +@property (nonatomic, copy) HippyDirectEventBlock onBlur; +@property (nonatomic, copy) HippyDirectEventBlock onFocus; +@property (nonatomic, copy) HippyDirectEventBlock onEndEditing; +@property (nonatomic, copy) HippyDirectEventBlock onKeyboardWillShow; +@property (nonatomic, copy) HippyDirectEventBlock onKeyboardWillHide; @property (nonatomic, copy) NSString *value; @property (nonatomic, strong) NSNumber *fontSize; diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderTextField.m b/renderer/native/ios/renderer/component/textinput/NativeRenderTextField.m index fd908dbfc0f..f5a28eaf4fb 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderTextField.m +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderTextField.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,10 +22,10 @@ #import "NativeRenderTextField.h" -#import "HPConvert.h" -#import "HPToolUtils.h" +#import "HippyConvert.h" +#import "HippyUtils.h" #import "NativeRenderTextSelection.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" @implementation NativeRenderUITextField @@ -170,7 +170,7 @@ - (void)textFieldDidChange { // selectedTextRange observer isn't triggered when you type even though the // cursor position moves, so we send event again here. - if (!self.componentTag || !_onChangeText) { + if (!self.hippyTag || !_onChangeText) { return; } diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderTextSelection.h b/renderer/native/ios/renderer/component/textinput/NativeRenderTextSelection.h index cb0acac8559..c485791639b 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderTextSelection.h +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderTextSelection.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "HPConvert.h" +#import "HippyConvert.h" /** * Object containing information about a TextInput's selection. @@ -34,7 +34,7 @@ @end -@interface HPConvert (NativeRenderTextSelection) +@interface HippyConvert (NativeRenderTextSelection) + (NativeRenderTextSelection *)NativeRenderTextSelection:(id)json; diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderTextSelection.m b/renderer/native/ios/renderer/component/textinput/NativeRenderTextSelection.m index 594a428e46c..60cdb1ec47a 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderTextSelection.m +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderTextSelection.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -34,7 +34,7 @@ - (instancetype)initWithStart:(NSInteger)start end:(NSInteger)end { @end -@implementation HPConvert (NativeRenderTextSelection) +@implementation HippyConvert (NativeRenderTextSelection) + (NativeRenderTextSelection *)NativeRenderTextSelection:(id)json { if ([json isKindOfClass:[NSDictionary class]]) { diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderTextView.h b/renderer/native/ios/renderer/component/textinput/NativeRenderTextView.h index 6a298d6ceef..2e741e76e93 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderTextView.h +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderTextView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,9 +22,9 @@ #import -#import "NativeRenderView.h" +#import "HippyView.h" #import "NativeRenderBaseTextInput.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" @protocol NativeRenderUITextViewResponseDelegate @required @@ -51,11 +51,11 @@ @property (nonatomic, strong) UIFont *font; @property (nonatomic, assign) NSInteger mostRecentEventCount; @property (nonatomic, strong) NSNumber *maxLength; -@property (nonatomic, copy) NativeRenderDirectEventBlock onKeyPress; -@property (nonatomic, copy) NativeRenderDirectEventBlock onContentSizeChange; -@property (nonatomic, copy) NativeRenderDirectEventBlock onSelectionChange; -@property (nonatomic, copy) NativeRenderDirectEventBlock onTextInput; -@property (nonatomic, copy) NativeRenderDirectEventBlock onEndEditing; +@property (nonatomic, copy) HippyDirectEventBlock onKeyPress; +@property (nonatomic, copy) HippyDirectEventBlock onContentSizeChange; +@property (nonatomic, copy) HippyDirectEventBlock onSelectionChange; +@property (nonatomic, copy) HippyDirectEventBlock onTextInput; +@property (nonatomic, copy) HippyDirectEventBlock onEndEditing; - (void)performTextUpdate; @@ -63,11 +63,11 @@ @property (nonatomic, strong) NSNumber *fontSize; @property (nonatomic, strong) NSString *defaultValue; @property (nonatomic, strong) UIColor *textColor; -@property (nonatomic, copy) NativeRenderDirectEventBlock onChangeText; -@property (nonatomic, copy) NativeRenderDirectEventBlock onBlur; -@property (nonatomic, copy) NativeRenderDirectEventBlock onFocus; -@property (nonatomic, copy) NativeRenderDirectEventBlock onKeyboardWillShow; -@property (nonatomic, copy) NativeRenderDirectEventBlock onKeyboardWillHide; +@property (nonatomic, copy) HippyDirectEventBlock onChangeText; +@property (nonatomic, copy) HippyDirectEventBlock onBlur; +@property (nonatomic, copy) HippyDirectEventBlock onFocus; +@property (nonatomic, copy) HippyDirectEventBlock onKeyboardWillShow; +@property (nonatomic, copy) HippyDirectEventBlock onKeyboardWillHide; - (void)updateFrames; @end diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderTextView.mm b/renderer/native/ios/renderer/component/textinput/NativeRenderTextView.mm index 9f86f5a4a9b..1d0e9a321e6 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderTextView.mm +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderTextView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,12 +22,12 @@ #import "NativeRenderTextView.h" -#import "HPConvert.h" +#import "HippyConvert.h" #import "NativeRenderObjectText.h" #import "NativeRenderText.h" -#import "HPToolUtils.h" +#import "HippyUtils.h" #import "NativeRenderTextSelection.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" @implementation NativeRenderUITextView @@ -126,11 +126,11 @@ - (instancetype)initWithFrame:(CGRect)frame { return self; } -- (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)index { - [super insertNativeRenderSubview:subview atIndex:index]; +- (void)insertHippySubview:(UIView *)subview atIndex:(NSInteger)index { + [super insertHippySubview:subview atIndex:index]; if ([subview isKindOfClass:[NativeRenderText class]]) { if (_richTextView) { - HPLogError(@"Tried to insert a second into - there can only be one."); + HippyLogError(@"Tried to insert a second into - there can only be one."); } _richTextView = (NativeRenderText *)subview; @@ -144,22 +144,22 @@ - (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)index { } } -- (void)removeNativeRenderSubview:(UIView *)subview { - [super removeNativeRenderSubview:subview]; +- (void)removeHippySubview:(UIView *)subview { + [super removeHippySubview:subview]; if (_richTextView == subview) { _richTextView = nil; [self performTextUpdate]; } } -- (void)didUpdateNativeRenderSubviews { +- (void)didUpdateHippySubviews { // Do nothing, as we don't allow non-text subviews } - (void)setMostRecentEventCount:(NSInteger)mostRecentEventCount { _mostRecentEventCount = mostRecentEventCount; - // Props are set after uiBlockToAmendWithRenderObjectRegistry, which means that + // Props are set after uiBlockToAmendWithShadowViewRegistry, which means that // at the time performTextUpdate is called, _mostRecentEventCount will be // behind _eventCount, with the result that performPendingTextUpdate will do // nothing. For that reason we call it again here after mostRecentEventCount @@ -270,7 +270,7 @@ - (void)updateContentSize { @"height": @(size.height), @"width": @(size.width), }, - @"target": self.componentTag, + @"target": self.hippyTag, }); } } @@ -600,7 +600,7 @@ - (void)textViewDidChange:(UITextView *)textView { _nativeUpdatesInFlight = NO; // _nativeEventCount++; - if (!self.componentTag || !_onChangeText) { + if (!self.hippyTag || !_onChangeText) { return; } @@ -624,7 +624,7 @@ - (void)textViewDidChange:(UITextView *)textView { _onChangeText(@{ @"text": self.text, @"contentSize": @ { @"height": @(contentHeight), @"width": @(textView.contentSize.width) }, - @"target": self.componentTag, + @"target": self.hippyTag, @"eventCount": @(_nativeEventCount), }); } diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderTextViewManager.h b/renderer/native/ios/renderer/component/textinput/NativeRenderTextViewManager.h index 3c0e3cb7086..93a51ad916c 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderTextViewManager.h +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderTextViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderTextViewManager : NativeRenderViewManager +@interface NativeRenderTextViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/textinput/NativeRenderTextViewManager.mm b/renderer/native/ios/renderer/component/textinput/NativeRenderTextViewManager.mm index 5534d9cecdb..69ea4705707 100644 --- a/renderer/native/ios/renderer/component/textinput/NativeRenderTextViewManager.mm +++ b/renderer/native/ios/renderer/component/textinput/NativeRenderTextViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,17 +21,18 @@ */ #import "NativeRenderBaseTextInput.h" -#import "NativeRenderFont.h" -#import "NativeRenderImpl.h" +#import "HippyFont.h" +#import "HippyUIManager.h" #import "NativeRenderObjectTextView.h" -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" #import "NativeRenderTextField.h" #import "NativeRenderTextView.h" #import "NativeRenderTextViewManager.h" +#import "HippyBridgeModule.h" @implementation NativeRenderTextViewManager -NATIVE_RENDER_EXPORT_VIEW(TextInput) +HIPPY_EXPORT_MODULE(TextInput) - (UIView *)view { NSNumber *multiline = self.props[@"multiline"]; @@ -60,79 +61,79 @@ - (UIView *)view { return theView; } -- (NativeRenderObjectView *)nativeRenderObjectView { +- (HippyShadowView *)hippyShadowView { return [NativeRenderObjectTextView new]; } -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(value, NSString) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onChangeText, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onKeyPress, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onBlur, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onFocus, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onKeyboardWillShow, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(defaultValue, NSString) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(isNightMode, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(value, NSString) +HIPPY_EXPORT_VIEW_PROPERTY(onChangeText, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onKeyPress, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onBlur, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onFocus, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onKeyboardWillShow, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(defaultValue, NSString) +HIPPY_EXPORT_VIEW_PROPERTY(isNightMode, BOOL) -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(focusTextInput:(nonnull NSNumber *)componentTag) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ +HIPPY_EXPORT_METHOD(focusTextInput:(nonnull NSNumber *)componentTag) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ NativeRenderBaseTextInput *view = (NativeRenderBaseTextInput *)viewRegistry[componentTag]; if (view == nil) return ; if (![view isKindOfClass:[NativeRenderBaseTextInput class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); } [view focus]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(isFocused:(nonnull NSNumber *)componentTag callback:(RenderUIResponseSenderBlock)callback) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(isFocused:(nonnull NSNumber *)componentTag callback:(HippyPromiseResolveBlock)callback) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderBaseTextInput *view = (NativeRenderBaseTextInput *)viewRegistry[componentTag]; if (view == nil) return ; if (![view isKindOfClass:[NativeRenderBaseTextInput class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); } BOOL isFocused = [view isFirstResponder]; callback([NSDictionary dictionaryWithObject:[NSNumber numberWithBool:isFocused] forKey:@"value"]); }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(blurTextInput:(nonnull NSNumber *)componentTag) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry){ +HIPPY_EXPORT_METHOD(blurTextInput:(nonnull NSNumber *)componentTag) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ NativeRenderBaseTextInput *view = (NativeRenderBaseTextInput *)viewRegistry[componentTag]; if (view == nil) return ; if (![view isKindOfClass:[NativeRenderBaseTextInput class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); } [view blur]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(clear:(nonnull NSNumber *)componentTag) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(clear:(nonnull NSNumber *)componentTag) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderBaseTextInput *view = (NativeRenderBaseTextInput *)viewRegistry[componentTag]; if (view == nil) return ; if (![view isKindOfClass:[NativeRenderBaseTextInput class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); } [view clearText]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(setValue:(nonnull NSNumber *)componentTag +HIPPY_EXPORT_METHOD(setValue:(nonnull NSNumber *)componentTag text:(NSString *)text ) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderBaseTextInput *view = (NativeRenderBaseTextInput *)viewRegistry[componentTag]; if (view == nil) return ; if (![view isKindOfClass:[NativeRenderBaseTextInput class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderBaseTextInput, got: %@", view); } [view setValue: text]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(getValue:(nonnull NSNumber *)componentTag - callback:(RenderUIResponseSenderBlock)callback ) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(getValue:(nonnull NSNumber *)componentTag + callback:(HippyPromiseResolveBlock)callback ) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderBaseTextInput *view = (NativeRenderBaseTextInput *)viewRegistry[componentTag]; NSString *stringValue = [view value]; if (nil == stringValue) { @@ -142,69 +143,69 @@ - (NativeRenderObjectView *)nativeRenderObjectView { }]; } -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(text, NSString) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(placeholder, NSString) +HIPPY_EXPORT_SHADOW_PROPERTY(text, NSString) +HIPPY_EXPORT_SHADOW_PROPERTY(placeholder, NSString) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(autoCapitalize, textView.autocapitalizationType, UITextAutocapitalizationType) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(autoCorrect, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(blurOnSubmit, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(clearTextOnFocus, BOOL) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(color, textView.textColor, UIColor) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(textAlign, textView.textAlignment, NSTextAlignment) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(editable, textView.editable, BOOL) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(enablesReturnKeyAutomatically, textView.enablesReturnKeyAutomatically, BOOL) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(keyboardType, textView.keyboardType, UIKeyboardType) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(keyboardAppearance, textView.keyboardAppearance, UIKeyboardAppearance) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(maxLength, NSNumber) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onContentSizeChange, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onSelectionChange, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onTextInput, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onEndEditing, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(placeholder, NSString) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(placeholderTextColor, UIColor) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(returnKeyType, textView.returnKeyType, UIReturnKeyType) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(secureTextEntry, textView.secureTextEntry, BOOL) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(selectionColor, tintColor, UIColor) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(selectTextOnFocus, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(selection, NativeRenderTextSelection) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(text, NSString) +HIPPY_REMAP_VIEW_PROPERTY(autoCapitalize, textView.autocapitalizationType, UITextAutocapitalizationType) +HIPPY_EXPORT_VIEW_PROPERTY(autoCorrect, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(blurOnSubmit, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(clearTextOnFocus, BOOL) +HIPPY_REMAP_VIEW_PROPERTY(color, textView.textColor, UIColor) +HIPPY_REMAP_VIEW_PROPERTY(textAlign, textView.textAlignment, NSTextAlignment) +HIPPY_REMAP_VIEW_PROPERTY(editable, textView.editable, BOOL) +HIPPY_REMAP_VIEW_PROPERTY(enablesReturnKeyAutomatically, textView.enablesReturnKeyAutomatically, BOOL) +HIPPY_REMAP_VIEW_PROPERTY(keyboardType, textView.keyboardType, UIKeyboardType) +HIPPY_REMAP_VIEW_PROPERTY(keyboardAppearance, textView.keyboardAppearance, UIKeyboardAppearance) +HIPPY_EXPORT_VIEW_PROPERTY(maxLength, NSNumber) +HIPPY_EXPORT_VIEW_PROPERTY(onContentSizeChange, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onSelectionChange, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onTextInput, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onEndEditing, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(placeholder, NSString) +HIPPY_EXPORT_VIEW_PROPERTY(placeholderTextColor, UIColor) +HIPPY_REMAP_VIEW_PROPERTY(returnKeyType, textView.returnKeyType, UIReturnKeyType) +HIPPY_REMAP_VIEW_PROPERTY(secureTextEntry, textView.secureTextEntry, BOOL) +HIPPY_REMAP_VIEW_PROPERTY(selectionColor, tintColor, UIColor) +HIPPY_EXPORT_VIEW_PROPERTY(selectTextOnFocus, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(selection, NativeRenderTextSelection) +HIPPY_EXPORT_VIEW_PROPERTY(text, NSString) -NATIVE_RENDER_CUSTOM_RENDER_OBJECT_PROPERTY(fontSize, NSNumber, NativeRenderObjectTextView) { - view.font = [NativeRenderFont updateFont:view.font withSize:json]; +HIPPY_CUSTOM_SHADOW_PROPERTY(fontSize, NSNumber, NativeRenderObjectTextView) { + view.font = [HippyFont updateFont:view.font withSize:json]; } -NATIVE_RENDER_CUSTOM_RENDER_OBJECT_PROPERTY(fontWeight, NSString, NativeRenderObjectTextView) { - view.font = [NativeRenderFont updateFont:view.font withWeight:json]; +HIPPY_CUSTOM_SHADOW_PROPERTY(fontWeight, NSString, NativeRenderObjectTextView) { + view.font = [HippyFont updateFont:view.font withWeight:json]; } -NATIVE_RENDER_CUSTOM_RENDER_OBJECT_PROPERTY(fontStyle, NSString, NativeRenderObjectTextView) { - view.font = [NativeRenderFont updateFont:view.font withStyle:json]; // defaults to normal +HIPPY_CUSTOM_SHADOW_PROPERTY(fontStyle, NSString, NativeRenderObjectTextView) { + view.font = [HippyFont updateFont:view.font withStyle:json]; // defaults to normal } -NATIVE_RENDER_CUSTOM_RENDER_OBJECT_PROPERTY(fontFamily, NSString, NativeRenderObjectTextView) { - view.font = [NativeRenderFont updateFont:view.font withFamily:json]; +HIPPY_CUSTOM_SHADOW_PROPERTY(fontFamily, NSString, NativeRenderObjectTextView) { + view.font = [HippyFont updateFont:view.font withFamily:json]; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(fontSize, NSNumber, NativeRenderBaseTextInput) { - UIFont *theFont = [NativeRenderFont updateFont:view.font withSize:json ?: @(defaultView.font.pointSize)]; +HIPPY_CUSTOM_VIEW_PROPERTY(fontSize, NSNumber, NativeRenderBaseTextInput) { + UIFont *theFont = [HippyFont updateFont:view.font withSize:json ?: @(defaultView.font.pointSize)]; view.font = theFont; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(fontWeight, NSString, __unused NativeRenderBaseTextInput) { - UIFont *theFont = [NativeRenderFont updateFont:view.font withWeight:json]; // defaults to normal +HIPPY_CUSTOM_VIEW_PROPERTY(fontWeight, NSString, __unused NativeRenderBaseTextInput) { + UIFont *theFont = [HippyFont updateFont:view.font withWeight:json]; // defaults to normal view.font = theFont; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(fontStyle, NSString, __unused NativeRenderBaseTextInput) { - UIFont *theFont = [NativeRenderFont updateFont:view.font withStyle:json]; +HIPPY_CUSTOM_VIEW_PROPERTY(fontStyle, NSString, __unused NativeRenderBaseTextInput) { + UIFont *theFont = [HippyFont updateFont:view.font withStyle:json]; view.font = theFont; // defaults to normal } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(fontFamily, NSString, NativeRenderBaseTextInput) { - view.font = [NativeRenderFont updateFont:view.font withFamily:json ?: defaultView.font.familyName]; +HIPPY_CUSTOM_VIEW_PROPERTY(fontFamily, NSString, NativeRenderBaseTextInput) { + view.font = [HippyFont updateFont:view.font withFamily:json ?: defaultView.font.familyName]; } -- (NativeRenderRenderUIBlock)uiBlockToAmendWithNativeRenderObjectView:(NativeRenderObjectView *)nativeRenderObjectView { - NSNumber *componentTag = nativeRenderObjectView.componentTag; - UIEdgeInsets padding = nativeRenderObjectView.paddingAsInsets; - return ^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowView:(HippyShadowView *)hippyShadowView { + NSNumber *componentTag = hippyShadowView.hippyTag; + UIEdgeInsets padding = hippyShadowView.paddingAsInsets; + return ^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { viewRegistry[componentTag].contentInset = padding; }; } diff --git a/renderer/native/ios/renderer/component/view/NativeRenderBorderDrawing.h b/renderer/native/ios/renderer/component/view/HippyBorderDrawing.h similarity index 67% rename from renderer/native/ios/renderer/component/view/NativeRenderBorderDrawing.h rename to renderer/native/ios/renderer/component/view/HippyBorderDrawing.h index dbc6b30b80e..b5f88551ecd 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderBorderDrawing.h +++ b/renderer/native/ios/renderer/component/view/HippyBorderDrawing.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,8 +22,8 @@ #import -#import "HPConvert+NativeRender.h" -#import "MacroDefines.h" +#import "HippyConvert+NativeRender.h" +#import "HippyDefines.h" typedef struct { CGFloat topLeft; @@ -49,21 +49,21 @@ typedef struct { /** * Determine if the border widths, colors and radii are all equal. */ -HP_EXTERN BOOL NativeRenderBorderInsetsAreEqual(UIEdgeInsets borderInsets); -HP_EXTERN BOOL NativeRenderCornerRadiiAreEqual(NativeRenderCornerRadii cornerRadii); -HP_EXTERN BOOL NativeRenderBorderColorsAreEqual(NativeRenderBorderColors borderColors); +HIPPY_EXTERN BOOL NativeRenderBorderInsetsAreEqual(UIEdgeInsets borderInsets); +HIPPY_EXTERN BOOL NativeRenderCornerRadiiAreEqual(NativeRenderCornerRadii cornerRadii); +HIPPY_EXTERN BOOL NativeRenderBorderColorsAreEqual(NativeRenderBorderColors borderColors); /** * Convert NativeRenderCornerRadii to NativeRenderCornerInsets by applying border insets. * Effectively, returns radius - inset, with a lower bound of 0.0. */ -HP_EXTERN NativeRenderCornerInsets NativeRenderGetCornerInsets(NativeRenderCornerRadii cornerRadii, UIEdgeInsets borderInsets); +HIPPY_EXTERN NativeRenderCornerInsets NativeRenderGetCornerInsets(NativeRenderCornerRadii cornerRadii, UIEdgeInsets borderInsets); /** * Create a CGPath representing a rounded rectangle with the specified bounds * and corner insets. Note that the CGPathRef must be released by the caller. */ -HP_EXTERN CGPathRef NativeRenderPathCreateWithRoundedRect(CGRect bounds, NativeRenderCornerInsets cornerInsets, const CGAffineTransform *transform); +HIPPY_EXTERN CGPathRef NativeRenderPathCreateWithRoundedRect(CGRect bounds, NativeRenderCornerInsets cornerInsets, const CGAffineTransform *transform); /** * Draw a CSS-compliant border as an image. You can determine if it's scalable @@ -71,7 +71,7 @@ HP_EXTERN CGPathRef NativeRenderPathCreateWithRoundedRect(CGRect bounds, NativeR * * `borderInsets` defines the border widths for each edge. */ -HP_EXTERN UIImage *NativeRenderGetBorderImage(NativeRenderBorderStyle borderStyle, CGSize viewSize, NativeRenderCornerRadii cornerRadii, UIEdgeInsets borderInsets, +HIPPY_EXTERN UIImage *NativeRenderGetBorderImage(NativeRenderBorderStyle borderStyle, CGSize viewSize, NativeRenderCornerRadii cornerRadii, UIEdgeInsets borderInsets, NativeRenderBorderColors borderColors, CGColorRef backgroundColor, BOOL drawToEdge, BOOL drawBackgroundColor); -HP_EXTERN CGPathRef NativeRenderPathCreateOuterOutline(BOOL drawToEdge, CGRect rect, NativeRenderCornerRadii cornerRadii); +HIPPY_EXTERN CGPathRef NativeRenderPathCreateOuterOutline(BOOL drawToEdge, CGRect rect, NativeRenderCornerRadii cornerRadii); diff --git a/renderer/native/ios/renderer/component/view/NativeRenderBorderDrawing.m b/renderer/native/ios/renderer/component/view/HippyBorderDrawing.m similarity index 99% rename from renderer/native/ios/renderer/component/view/NativeRenderBorderDrawing.m rename to renderer/native/ios/renderer/component/view/HippyBorderDrawing.m index 3c2cb51256d..2b7e78ad8d6 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderBorderDrawing.m +++ b/renderer/native/ios/renderer/component/view/HippyBorderDrawing.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,8 +20,8 @@ * limitations under the License. */ -#import "NativeRenderBorderDrawing.h" -#import "HPLog.h" +#import "HippyBorderDrawing.h" +#import "HippyLog.h" static const CGFloat NativeRenderViewBorderThreshold = 0.001; @@ -403,7 +403,7 @@ static CGContextRef NativeRenderUIGraphicsBeginImageContext(CGSize size, CGColor NSCParameterAssert(borderStyle == NativeRenderBorderStyleDashed || borderStyle == NativeRenderBorderStyleDotted); if (!NativeRenderBorderColorsAreEqual(borderColors) || !NativeRenderBorderInsetsAreEqual(borderInsets)) { - HPLogWarn(@"Unsupported dashed / dotted border style"); + HippyLogWarn(@"Unsupported dashed / dotted border style"); return nil; } diff --git a/renderer/native/ios/renderer/component/view/NativeRenderObjectView.h b/renderer/native/ios/renderer/component/view/HippyShadowView.h similarity index 90% rename from renderer/native/ios/renderer/component/view/NativeRenderObjectView.h rename to renderer/native/ios/renderer/component/view/HippyShadowView.h index 2ee2f0e0109..33c0372da0d 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderObjectView.h +++ b/renderer/native/ios/renderer/component/view/HippyShadowView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,9 +21,8 @@ */ #import - -#import "NativeRenderComponentProtocol.h" -#import "HPConvert+NativeRender.h" +#import "HippyComponent.h" +#import "HippyConvert+NativeRender.h" #include @@ -51,11 +50,11 @@ typedef NS_ENUM(NSUInteger, NativeRenderCreationType) { NativeRenderCreationTypeLazily, }; -@class NativeRenderObjectView; +@class HippyShadowView; typedef void (^NativeRenderApplierBlock)(NSDictionary *viewRegistry); -typedef UIView *(^NativeRenderViewCreationBlock)(NativeRenderObjectView *renderObject); +typedef UIView *(^NativeRenderViewCreationBlock)(HippyShadowView *renderObject); typedef void (^NativeRenderViewInsertionBlock)(UIView *container, NSArray *children); //TODO remove unused string @@ -65,14 +64,14 @@ extern NSString *const NativeRenderShadowViewDiffUpdate; extern NSString *const NativeRenderShadowViewDiffTag; /** - * RenderObject tree mirrors NativeRender view tree. Every node is highly stateful. + * ShadowView tree mirrors Hippy view tree. Every node is highly stateful. * 1. A node is in one of three lifecycles: uninitialized, computed, dirtied. * 2. At the end of each Bridge transaction, we call collectUpdatedFrames:widthConstraint:heightConstraint * at the root node to recursively layout the entire hierarchy. * 3. If a node is "computed" and the constraint passed from above is identical to the constraint used to * perform the last computation, we skip laying out the subtree entirely. */ -@interface NativeRenderObjectView : NSObject { +@interface HippyShadowView : NSObject { @protected NativeRenderUpdateLifecycle _propagationLifecycle; } @@ -84,12 +83,12 @@ extern NSString *const NativeRenderShadowViewDiffTag; /** * Get all native render object */ -- (NSArray *)subcomponents; +- (NSArray *)subcomponents; /** * Get super render object */ -- (NativeRenderObjectView *)parentComponent; +- (HippyShadowView *)parentComponent; /** * Insert native render object at index. @@ -98,19 +97,19 @@ extern NSString *const NativeRenderShadowViewDiffTag; * @param atIndex position for hippy subview to insert * @discussion atIndex must not exceed range of current index */ -- (void)insertNativeRenderSubview:(NativeRenderObjectView *)subview atIndex:(NSInteger)atIndex; +- (void)insertHippySubview:(HippyShadowView *)subview atIndex:(NSInteger)atIndex; /** * Remove render object * * @param subview A render object to delete */ -- (void)removeNativeRenderSubview:(NativeRenderObjectView *)subview; +- (void)removeHippySubview:(HippyShadowView *)subview; -@property(nonatomic, weak, readonly) NativeRenderObjectView *superview; +@property(nonatomic, weak, readonly) HippyShadowView *superview; @property(nonatomic, copy) NSString *viewName; @property(nonatomic, strong) UIColor *backgroundColor; // Used to propagate to children -@property(nonatomic, copy) NativeRenderDirectEventBlock onLayout; +@property(nonatomic, copy) HippyDirectEventBlock onLayout; @property(nonatomic, readonly) BOOL confirmedLayoutDirectionDidUpdated; /** @@ -230,7 +229,7 @@ extern NSString *const NativeRenderShadowViewDiffTag; /** * As described in NativeRenderComponent protocol. */ -- (void)didUpdateNativeRenderSubviews NS_REQUIRES_SUPER; +- (void)didUpdateHippySubviews NS_REQUIRES_SUPER; - (void)didSetProps:(NSArray *)changedProps NS_REQUIRES_SUPER; - (NSDictionary *)mergeProps:(NSDictionary *)props; diff --git a/renderer/native/ios/renderer/component/view/NativeRenderObjectView.mm b/renderer/native/ios/renderer/component/view/HippyShadowView.mm similarity index 82% rename from renderer/native/ios/renderer/component/view/NativeRenderObjectView.mm rename to renderer/native/ios/renderer/component/view/HippyShadowView.mm index 347b4334ea1..42e59869d60 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderObjectView.mm +++ b/renderer/native/ios/renderer/component/view/HippyShadowView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,12 +20,12 @@ * limitations under the License. */ -#import "HPConvert.h" -#import "HPDomUtils.h" -#import "HPI18nUtils.h" -#import "NativeRenderObjectView.h" +#import "HippyConvert.h" +#import "HippyDomUtils.h" +#import "HippyI18nUtils.h" +#import "HippyShadowView.h" #import "UIView+DirectionalLayout.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #include "dom/layout_node.h" #include "dom/render_manager.h" @@ -38,8 +38,8 @@ NSString *const NativeRenderShadowViewDiffTag = @"NativeRenderShadowViewDiffTag"; -@interface NativeRenderObjectView () { - NSMutableArray *_objectSubviews; +@interface HippyShadowView () { + NSMutableArray *_objectSubviews; BOOL _recomputePadding; BOOL _recomputeMargin; BOOL _recomputeBorder; @@ -51,9 +51,9 @@ @interface NativeRenderObjectView () { @end -@implementation NativeRenderObjectView +@implementation HippyShadowView -@synthesize componentTag = _componentTag; +@synthesize hippyTag = _hippyTag; @synthesize props = _props; @synthesize rootTag = _rootTag; @synthesize tagName =_tagName; @@ -63,7 +63,7 @@ - (void)amendLayoutBeforeMount:(NSMutableSet *)blocks return; } _propagationLifecycle = NativeRenderUpdateLifecycleComputed; - for (NativeRenderObjectView *renderObjectView in self.subcomponents) { + for (HippyShadowView *renderObjectView in self.subcomponents) { [renderObjectView amendLayoutBeforeMount:blocks]; } } @@ -72,17 +72,17 @@ - (void)amendLayoutBeforeMount:(NSMutableSet *)blocks parentProperties:(NSDictionary *)parentProperties { if (_didUpdateSubviews) { _didUpdateSubviews = NO; - [self didUpdateNativeRenderSubviews]; + [self didUpdateHippySubviews]; [applierBlocks addObject:^(NSDictionary *viewRegistry) { - UIView *view = viewRegistry[self->_componentTag]; + UIView *view = viewRegistry[self->_hippyTag]; [view clearSortedSubviews]; - [view didUpdateNativeRenderSubviews]; + [view didUpdateHippySubviews]; }]; } if (_confirmedLayoutDirectionDidUpdated) { hippy::Direction direction = [self confirmedLayoutDirection]; [applierBlocks addObject:^(NSDictionary *viewRegistry) { - UIView *view = viewRegistry[self->_componentTag]; + UIView *view = viewRegistry[self->_hippyTag]; [view applyLayoutDirectionFromParent:direction]; }]; _confirmedLayoutDirectionDidUpdated = NO; @@ -91,8 +91,8 @@ - (void)amendLayoutBeforeMount:(NSMutableSet *)blocks UIColor *parentBackgroundColor = parentProperties[NativeRenderBackgroundColorProp]; if (parentBackgroundColor) { [applierBlocks addObject:^(NSDictionary *viewRegistry) { - UIView *view = viewRegistry[self->_componentTag]; - [view nativeRenderSetInheritedBackgroundColor:parentBackgroundColor]; + UIView *view = viewRegistry[self->_hippyTag]; + [view hippySetInheritedBackgroundColor:parentBackgroundColor]; }]; } } else { @@ -125,8 +125,8 @@ - (instancetype)init { return self; } -- (BOOL)isNativeRenderRootView { - return NativeRenderIsRootView(self.componentTag); +- (BOOL)isHippyRootView { + return HippyIsHippyRootView(self.hippyTag); } - (BOOL)isCSSLeafNode { @@ -165,8 +165,8 @@ - (BOOL)isTextDirty { - (NativeRenderCreationType)creationType { if (NativeRenderCreationTypeUndetermined == _creationType) { - NativeRenderObjectView *superRenderObject = [self parentComponent]; - if (superRenderObject && ![superRenderObject isNativeRenderRootView]) { + HippyShadowView *superRenderObject = [self parentComponent]; + if (superRenderObject && ![superRenderObject isHippyRootView]) { _creationType = [superRenderObject creationType]; } else { @@ -183,13 +183,13 @@ - (void)setTextComputed { - (void)recusivelySetCreationTypeToInstant { auto domManager = self.domManager.lock(); if (domManager) { - __weak NativeRenderObjectView *weakSelf = self; + __weak HippyShadowView *weakSelf = self; std::vector> ops = {[weakSelf](){ if (weakSelf) { - NativeRenderObjectView *strongSelf = weakSelf; + HippyShadowView *strongSelf = weakSelf; strongSelf.creationType = NativeRenderCreationTypeInstantly; - for (NativeRenderObjectView *subRenderObject in strongSelf.subcomponents) { + for (HippyShadowView *subRenderObject in strongSelf.subcomponents) { [subRenderObject synchronousRecusivelySetCreationTypeToInstant]; } } @@ -200,7 +200,7 @@ - (void)recusivelySetCreationTypeToInstant { - (void)synchronousRecusivelySetCreationTypeToInstant { self.creationType = NativeRenderCreationTypeInstantly; - for (NativeRenderObjectView *subShadowView in self.subcomponents) { + for (HippyShadowView *subShadowView in self.subcomponents) { [subShadowView synchronousRecusivelySetCreationTypeToInstant]; } } @@ -208,7 +208,7 @@ - (void)synchronousRecusivelySetCreationTypeToInstant { - (UIView *)createView:(NativeRenderViewCreationBlock)creationBlock insertChildren:(NativeRenderViewInsertionBlock)insertionBlock { UIView *container = creationBlock(self); NSMutableArray *children = [NSMutableArray arrayWithCapacity:[self.subcomponents count]]; - for (NativeRenderObjectView *subviews in self.subcomponents) { + for (HippyShadowView *subviews in self.subcomponents) { UIView *subview = [subviews createView:creationBlock insertChildren:insertionBlock]; if (subview) { [children addObject:subview]; @@ -218,7 +218,7 @@ - (UIView *)createView:(NativeRenderViewCreationBlock)creationBlock insertChildr return container; } -- (void)insertNativeRenderSubview:(NativeRenderObjectView *)subview atIndex:(NSInteger)atIndex { +- (void)insertHippySubview:(HippyShadowView *)subview atIndex:(NSInteger)atIndex { if (atIndex <= [_objectSubviews count]) { [_objectSubviews insertObject:subview atIndex:atIndex]; } @@ -231,14 +231,14 @@ - (void)insertNativeRenderSubview:(NativeRenderObjectView *)subview atIndex:(NSI [self dirtyPropagation:NativeRenderUpdateLifecycleLayoutDirtied]; } -- (void)moveNativeRenderSubview:(id)subview toIndex:(NSInteger)atIndex { +- (void)moveHippySubview:(id)subview toIndex:(NSInteger)atIndex { if ([_objectSubviews containsObject:subview]) { [_objectSubviews removeObject:subview]; } - [self insertNativeRenderSubview:subview atIndex:atIndex]; + [self insertHippySubview:subview atIndex:atIndex]; } -- (void)removeNativeRenderSubview:(NativeRenderObjectView *)subview { +- (void)removeHippySubview:(HippyShadowView *)subview { [subview dirtyText:NO]; [subview dirtyPropagation:NativeRenderUpdateLifecycleLayoutDirtied]; _didUpdateSubviews = YES; @@ -246,40 +246,40 @@ - (void)removeNativeRenderSubview:(NativeRenderObjectView *)subview { [_objectSubviews removeObject:subview]; } -- (void)removeFromNativeRenderSuperview { +- (void)removeFromHippySuperview { id superview = [self parentComponent]; - [superview removeNativeRenderSubview:self]; + [superview removeHippySubview:self]; } -- (NSArray *)subcomponents { +- (NSArray *)subcomponents { return _objectSubviews; } -- (NativeRenderObjectView *)parentComponent { +- (HippyShadowView *)parentComponent { return _superview; } -- (void)setParentComponent:(__kindof id)parentComponent { +- (void)setParentComponent:(__kindof id)parentComponent { _superview = parentComponent; } -- (NSNumber *)componentTagAtPoint:(CGPoint)point { - for (NativeRenderObjectView *renderObject in _objectSubviews) { +- (NSNumber *)hippyTagAtPoint:(CGPoint)point { + for (HippyShadowView *renderObject in _objectSubviews) { if (CGRectContainsPoint(renderObject.frame, point)) { CGPoint relativePoint = point; CGPoint origin = renderObject.frame.origin; relativePoint.x -= origin.x; relativePoint.y -= origin.y; - return [renderObject componentTagAtPoint:relativePoint]; + return [renderObject hippyTagAtPoint:relativePoint]; } } - return self.componentTag; + return self.hippyTag; } - (NSString *)description { NSString *description = super.description; description = [[description substringToIndex:description.length - 1] - stringByAppendingFormat:@"; viewName: %@; componentTag: %@; frame: %@>", self.viewName, self.componentTag, NSStringFromCGRect(self.frame)]; + stringByAppendingFormat:@"; viewName: %@; componentTag: %@; frame: %@>", self.viewName, self.hippyTag, NSStringFromCGRect(self.frame)]; return description; } @@ -291,7 +291,7 @@ - (void)addRecursiveDescriptionToString:(NSMutableString *)string atLevel:(NSUIn [string appendString:self.description]; [string appendString:@"\n"]; - for (NativeRenderObjectView *subview in _objectSubviews) { + for (HippyShadowView *subview in _objectSubviews) { [subview addRecursiveDescriptionToString:string atLevel:level + 1]; } } @@ -326,14 +326,14 @@ - (void)setLayoutFrame:(CGRect)frame dirtyPropagation:(BOOL)dirtyPropagation { [self setFrame:frame]; auto domManager = self.domManager.lock(); if (domManager) { - __weak NativeRenderObjectView *weakSelf = self; + __weak HippyShadowView *weakSelf = self; std::vector> ops = {[weakSelf, domManager, frame, dirtyPropagation](){ @autoreleasepool { if (!weakSelf) { return; } - NativeRenderObjectView *strongSelf = weakSelf; - int32_t componentTag = [[strongSelf componentTag] intValue]; + HippyShadowView *strongSelf = weakSelf; + int32_t componentTag = [[strongSelf hippyTag] intValue]; auto node = domManager->GetNode(strongSelf.rootNode, componentTag); auto renderManager = domManager->GetRenderManager().lock(); if (!node || !renderManager) { @@ -361,14 +361,14 @@ - (void)setBackgroundColor:(UIColor *)color { [self dirtyPropagation:NativeRenderUpdateLifecyclePropsDirtied]; } -- (void)didUpdateNativeRenderSubviews { +- (void)didUpdateHippySubviews { // Does nothing by default } - (void)didSetProps:(__unused NSArray *)changedProps { } -- (void)nativeRenderSetFrame:(__unused CGRect)frame { +- (void)hippySetFrame:(__unused CGRect)frame { } - (NSDictionary *)mergeProps:(NSDictionary *)props { @@ -449,7 +449,7 @@ - (void)setConfirmedLayoutDirection:(hippy::Direction)confirmedLayoutDirection { - (void)applyConfirmedLayoutDirectionToSubviews:(hippy::Direction)confirmedLayoutDirection { _confirmedLayoutDirection = confirmedLayoutDirection; - for (NativeRenderObjectView *subviews in self.subcomponents) { + for (HippyShadowView *subviews in self.subcomponents) { [subviews applyConfirmedLayoutDirectionToSubviews:confirmedLayoutDirection]; } } @@ -459,14 +459,14 @@ - (BOOL)isLayoutSubviewsRTL { return layoutRTL; } -- (void)checkLayoutDirection:(NSMutableSet *)viewsSet direction:(hippy::Direction *)direction{ +- (void)checkLayoutDirection:(NSMutableSet *)viewsSet direction:(hippy::Direction *)direction{ if (hippy::Direction::Inherit == self.confirmedLayoutDirection) { [viewsSet addObject:self]; - NativeRenderObjectView *shadowSuperview = [self parentComponent]; + HippyShadowView *shadowSuperview = [self parentComponent]; if (!shadowSuperview) { if (direction) { NSWritingDirection writingDirection = - [[HPI18nUtils sharedInstance] writingDirectionForCurrentAppLanguage]; + [[HippyI18nUtils sharedInstance] writingDirectionForCurrentAppLanguage]; *direction = NSWritingDirectionRightToLeft == writingDirection ? hippy::Direction::RTL : hippy::Direction::LTR; } } @@ -482,7 +482,7 @@ - (void)checkLayoutDirection:(NSMutableSet *)viewsSet - (void)superviewLayoutDirectionChangedTo:(hippy::Direction)direction { if (hippy::Direction::Inherit == self.layoutDirection) { self.confirmedLayoutDirection = [self superview].confirmedLayoutDirection; - for (NativeRenderObjectView *subview in self.subcomponents) { + for (HippyShadowView *subview in self.subcomponents) { [subview superviewLayoutDirectionChangedTo:self.confirmedLayoutDirection]; } } diff --git a/renderer/native/ios/renderer/component/view/NativeRenderView.h b/renderer/native/ios/renderer/component/view/HippyView.h similarity index 91% rename from renderer/native/ios/renderer/component/view/NativeRenderView.h rename to renderer/native/ios/renderer/component/view/HippyView.h index 3881fb29b2f..495f0860582 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderView.h +++ b/renderer/native/ios/renderer/component/view/HippyView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,19 +22,19 @@ #import -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" #import "NativeRenderTouchesView.h" @class NativeRenderGradientObject; -@interface NativeRenderView : NativeRenderTouchesView +@interface HippyView : NativeRenderTouchesView /** * z-index, used to override sibling order in didUpdateHippySubviews. This is - * inherited from UIView+NativeRender, but we override it here to reduce the boxing + * inherited from UIView+Hippy, but we override it here to reduce the boxing * and associated object overheads. */ -@property (nonatomic, assign) NSInteger nativeRenderZIndex; +@property (nonatomic, assign) NSInteger hippyZIndex; @property (nonatomic, assign) CGFloat shadowSpread; diff --git a/renderer/native/ios/renderer/component/view/NativeRenderView.m b/renderer/native/ios/renderer/component/view/HippyView.m similarity index 94% rename from renderer/native/ios/renderer/component/view/NativeRenderView.m rename to renderer/native/ios/renderer/component/view/HippyView.m index 898eefcf1ed..039080abc7b 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderView.m +++ b/renderer/native/ios/renderer/component/view/HippyView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,14 +20,14 @@ * limitations under the License. */ -#import "HPConvert.h" -#import "HPToolUtils.h" -#import "NativeRenderBorderDrawing.h" +#import "HippyConvert.h" +#import "HippyUtils.h" +#import "HippyBorderDrawing.h" #import "NativeRenderGradientObject.h" -#import "NativeRenderView.h" +#import "HippyView.h" #import "UIEvent+TouchResponder.h" #import "UIView+DomEvent.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" static CGSize makeSizeConstrainWithType(CGSize originSize, CGSize constrainSize, NSString *resizeMode) { // width / height @@ -68,11 +68,11 @@ static CGSize makeSizeConstrainWithType(CGSize originSize, CGSize constrainSize, return str; } -@implementation NativeRenderView { +@implementation HippyView { UIColor *_backgroundColor; } -@synthesize nativeRenderZIndex = _nativeRenderZIndex; +@synthesize hippyZIndex = _hippyZIndex; - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; @@ -103,7 +103,7 @@ - (NSString *)accessibilityLabel { - (NSString *)description { NSString *superDescription = super.description; NSRange semicolonRange = [superDescription rangeOfString:@";"]; - NSString *replacement = [NSString stringWithFormat:@"; componentTag: %@;", self.componentTag]; + NSString *replacement = [NSString stringWithFormat:@"; componentTag: %@;", self.hippyTag]; return [superDescription stringByReplacingCharactersInRange:semicolonRange withString:replacement]; } @@ -148,10 +148,10 @@ - (NativeRenderCornerRadii)cornerRadii { // Get scale factors required to prevent radii from overlapping const CGSize size = self.bounds.size; - const CGFloat topScaleFactor = HPZeroIfNaN(MIN(1, size.width / (topLeftRadius + topRightRadius))); - const CGFloat bottomScaleFactor = HPZeroIfNaN(MIN(1, size.width / (bottomLeftRadius + bottomRightRadius))); - const CGFloat rightScaleFactor = HPZeroIfNaN(MIN(1, size.height / (topRightRadius + bottomRightRadius))); - const CGFloat leftScaleFactor = HPZeroIfNaN(MIN(1, size.height / (topLeftRadius + bottomLeftRadius))); + const CGFloat topScaleFactor = HippyZeroIfNaN(MIN(1, size.width / (topLeftRadius + topRightRadius))); + const CGFloat bottomScaleFactor = HippyZeroIfNaN(MIN(1, size.width / (bottomLeftRadius + bottomRightRadius))); + const CGFloat rightScaleFactor = HippyZeroIfNaN(MIN(1, size.height / (topRightRadius + bottomRightRadius))); + const CGFloat leftScaleFactor = HippyZeroIfNaN(MIN(1, size.height / (topLeftRadius + bottomLeftRadius))); // Return scaled radii return (NativeRenderCornerRadii) { @@ -162,12 +162,12 @@ - (NativeRenderCornerRadii)cornerRadii { }; } -- (void)nativeRenderSetFrame:(CGRect)frame { +- (void)hippySetFrame:(CGRect)frame { // If frame is zero, or below the threshold where the border radii can // be rendered as a stretchable image, we'll need to re-render. // TODO: detect up-front if re-rendering is necessary CGSize oldSize = self.bounds.size; - [super nativeRenderSetFrame:frame]; + [super hippySetFrame:frame]; if (!CGSizeEqualToSize(self.bounds.size, oldSize)) { [self.layer setNeedsDisplay]; } @@ -245,7 +245,7 @@ - (void)displayLayer:(CALayer *)layer { const NativeRenderBorderColors borderColors = [self borderColors]; UIColor *backgroundColor = self.backgroundColor; - BOOL isRunningInTest = HPRunningInTestEnvironment(); + BOOL isRunningInTest = HippyRunningInTestEnvironment(); BOOL isCornerEqual = NativeRenderCornerRadiiAreEqual(cornerRadii); BOOL isBorderInsetsEqual = NativeRenderBorderInsetsAreEqual(borderInsets); BOOL isBorderColorsEqual = NativeRenderBorderColorsAreEqual(borderColors); @@ -382,7 +382,7 @@ static BOOL NativeRenderLayerHasShadow(CALayer *layer) { return layer.shadowOpacity * CGColorGetAlpha(layer.shadowColor) > 0; } -- (void)nativeRenderSetInheritedBackgroundColor:(UIColor *)inheritedBackgroundColor { +- (void)hippySetInheritedBackgroundColor:(UIColor *)inheritedBackgroundColor { // Inherit background color if a shadow has been set, as an optimization if (NativeRenderLayerHasShadow(self.layer)) { self.backgroundColor = inheritedBackgroundColor; diff --git a/renderer/native/ios/renderer/component/view/NativeRenderViewManager.h b/renderer/native/ios/renderer/component/view/HippyViewManager.h similarity index 54% rename from renderer/native/ios/renderer/component/view/NativeRenderViewManager.h rename to renderer/native/ios/renderer/component/view/HippyViewManager.h index 621e853b8a4..d0f90528ad0 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderViewManager.h +++ b/renderer/native/ios/renderer/component/view/HippyViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,15 +21,21 @@ */ #import -#import "HPConvert.h" +#import "HippyConvert.h" #import "NativeRenderDefines.h" +#import "HippyBridgeModule.h" -@class NativeRenderObjectView; -@class NativeRenderImpl; +@class HippyBridge; +@class HippyShadowView; -@interface NativeRenderViewManager : NSObject +@interface HippyViewManager : NSObject -@property(nonatomic, weak)NativeRenderImpl *renderImpl; +/** + * The bridge can be used to access both the HippyUIIManager and the HippyEventDispatcher, + * allowing the manager (or the views that it manages) to manipulate the view + * hierarchy and send events back to the JS context. + */ +@property (nonatomic, weak) HippyBridge *bridge; /** * This method instantiates a native view to be managed by the module. Override @@ -42,17 +48,17 @@ /** * This method instantiates a shadow view to be managed by the module. If omitted, - * an ordinary NativeRenderObjectView instance will be created, which is typically fine for + * an ordinary HippyShadowView instance will be created, which is typically fine for * most view types. As with the -view method, the -renderObject method should return * a fresh instance each time it is called. */ -- (NativeRenderObjectView *)nativeRenderObjectView; +- (HippyShadowView *)hippyShadowView; /** * Called to notify manager that layout has finished, in case any calculated * properties need to be copied over from shadow view to view. */ -- (NativeRenderRenderUIBlock)uiBlockToAmendWithNativeRenderObjectView:(NativeRenderObjectView *)renderObject; +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowView:(HippyShadowView *)shadowView; /** * Called after view hierarchy manipulation has finished, and all shadow props @@ -60,22 +66,22 @@ * custom layout logic or tasks that involve walking the view hierarchy. * To be deprecated, hopefully. */ -- (NativeRenderRenderUIBlock)uiBlockToAmendWithRenderObjectRegistry:(NSDictionary *)renderObjectRegistry; +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(NSDictionary *)shadowViewRegistry; /** * This handles the simple case, where JS and native property names match. */ -#define NATIVE_RENDER_EXPORT_VIEW_PROPERTY(name, type) \ - +(NSArray *)propConfig_##name { \ - return @[@ #type]; \ +#define HIPPY_EXPORT_VIEW_PROPERTY(name, type) \ + +(NSArray *)propConfig_##name { \ + return @[@ #type]; \ } /** * This macro maps a named property to an arbitrary key path in the view. */ -#define NATIVE_RENDER_REMAP_VIEW_PROPERTY(name, keyPath, type) \ - +(NSArray *)propConfig_##name { \ - return @[@ #type, @ #keyPath]; \ +#define HIPPY_REMAP_VIEW_PROPERTY(name, keyPath, type) \ + +(NSArray *)propConfig_##name { \ + return @[@ #type, @ #keyPath]; \ } /** @@ -83,24 +89,24 @@ * view properties. The macro should be followed by a method body, which can * refer to "json", "view" and "defaultView" to implement the required logic. */ -#define NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(name, type, viewClass) \ - NATIVE_RENDER_REMAP_VIEW_PROPERTY(name, __custom__, type) \ +#define HIPPY_CUSTOM_VIEW_PROPERTY(name, type, viewClass) \ + HIPPY_REMAP_VIEW_PROPERTY(name, __custom__, type) \ -(void)set_##name : (id)json forView : (viewClass *)view withDefaultView : (viewClass *)defaultView /** * This macro is used to map properties to the shadow view, instead of the view. */ -#define NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(name, type) \ - +(NSArray *)propConfigRenderObject_##name { \ - return @[@ #type]; \ +#define HIPPY_EXPORT_SHADOW_PROPERTY(name, type) \ + +(NSArray *)propConfigShadow_##name { \ + return @[@ #type]; \ } /** * This macro maps a named property to an arbitrary key path in the shadow view. */ -#define NATIVE_RENDER_REMAP_RENDER_OBJECT_PROPERTY(name, keyPath, type) \ - +(NSArray *)propConfigRenderObject_##name { \ - return @[@ #type, @ #keyPath]; \ +#define HIPPY_REMAP_SHADOW_PROPERTY(name, keyPath, type) \ + +(NSArray *)propConfigShadow_##name { \ + return @[@ #type, @ #keyPath]; \ } /** @@ -108,23 +114,14 @@ * shadow view properties. The macro should be followed by a method body, which can * refer to "json" and "view". */ -#define NATIVE_RENDER_CUSTOM_RENDER_OBJECT_PROPERTY(name, type, viewClass) \ - NATIVE_RENDER_REMAP_RENDER_OBJECT_PROPERTY(name, __custom__, type) \ - -(void)set_##name : (id)json forRenderObject : (viewClass *)view - -#define NATIVE_RENDER_COMPONENT_EXPORT_METHOD(method_name) NATIVE_RENDER_COMPONENT_REMAP_METHOD(, method_name) +#define HIPPY_CUSTOM_SHADOW_PROPERTY(name, type, viewClass) \ + HIPPY_REMAP_SHADOW_PROPERTY(name, __custom__, type) \ + -(void)set_##name : (id)json forShadowView : (viewClass *)view -#define NATIVE_RENDER_COMPONENT_REMAP_METHOD(js_name, method_name) \ - +(NSArray *)HP_CONCAT(__render_export__, \ - HP_CONCAT(js_name, HP_CONCAT(__LINE__, __COUNTER__))) { \ - return @[@#js_name, @#method_name]; \ - } \ - -(void)method_name - -typedef void (^RenderUIResponseSenderBlock)(id response); @end -@interface NativeRenderViewManager (InitProps) +@interface HippyViewManager (InitProps) @property (nonatomic, strong) NSDictionary *props; @end + diff --git a/renderer/native/ios/renderer/component/view/NativeRenderViewManager.mm b/renderer/native/ios/renderer/component/view/HippyViewManager.mm similarity index 52% rename from renderer/native/ios/renderer/component/view/NativeRenderViewManager.mm rename to renderer/native/ios/renderer/component/view/HippyViewManager.mm index 43e83a4f683..f9c73dda39a 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderViewManager.mm +++ b/renderer/native/ios/renderer/component/view/HippyViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,83 +20,79 @@ * limitations under the License. */ -#import "HPAsserts.h" -#import "HPConvert.h" -#import "HPConvert+NativeRender.h" -#import "HPImageProviderProtocol.h" -#import "HPToolUtils.h" +#import "HippyAsserts.h" +#import "HippyConvert.h" +#import "HippyConvert+NativeRender.h" +#import "HippyImageProviderProtocol.h" +#import "HippyUtils.h" #import "NativeRenderGradientObject.h" -#import "NativeRenderImpl.h" -#import "NativeRenderObjectView.h" -#import "NativeRenderViewManager.h" -#import "NativeRenderView.h" +#import "HippyUIManager.h" +#import "HippyShadowView.h" +#import "HippyViewManager.h" +#import "HippyView.h" #import "UIView+DirectionalLayout.h" -#import "UIView+NativeRender.h" - -#include - -#include "VFSUriLoader.h" -#include "dom/layout_node.h" +#import "UIView+Hippy.h" +#import "HippyBridgeModule.h" +#import +#import "VFSUriLoader.h" +#import "dom/layout_node.h" -@interface NativeRenderViewManager () { +@interface HippyViewManager () { NSUInteger _sequence; - __weak NativeRenderImpl *_renderImpl; } @end -@implementation NativeRenderViewManager +@implementation HippyViewManager -NATIVE_RENDER_EXPORT_VIEW(View); +@synthesize bridge = _bridge; + +HIPPY_EXPORT_MODULE(View); - (UIView *)view { - return [[NativeRenderView alloc] init]; + return [[HippyView alloc] init]; } -- (NativeRenderObjectView *)nativeRenderObjectView { - return [[NativeRenderObjectView alloc] init]; +- (HippyShadowView *)hippyShadowView { + return [[HippyShadowView alloc] init]; } -- (NativeRenderRenderUIBlock)uiBlockToAmendWithNativeRenderObjectView:(__unused NativeRenderObjectView *)renderObject { +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowView:(__unused HippyShadowView *)shadowView { return nil; } -- (NativeRenderRenderUIBlock)uiBlockToAmendWithRenderObjectRegistry:(__unused NSDictionary *)renderObjectRegistry { +- (HippyViewManagerUIBlock)uiBlockToAmendWithShadowViewRegistry:(__unused NSDictionary *)shadowViewRegistry { return nil; } -- (NativeRenderImpl *)renderImpl { - return _renderImpl; -} - -static NSString * const NativeRenderViewManagerGetBoundingRelToContainerKey = @"relToContainer"; -static NSString * const NativeRenderViewManagerGetBoundingErrMsgrKey = @"errMsg"; -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(getBoundingClientRect:(nonnull NSNumber *)hippyTag - options:(nullable NSDictionary *)options - callback:(RenderUIResponseSenderBlock)callback ) { - if (options && [[options objectForKey:NativeRenderViewManagerGetBoundingRelToContainerKey] boolValue]) { +static NSString * const HippyViewManagerGetBoundingRelToContainerKey = @"relToContainer"; +static NSString * const HippyViewManagerGetBoundingErrMsgrKey = @"errMsg"; +HIPPY_EXPORT_METHOD(getBoundingClientRect:(nonnull NSNumber *)hippyTag + options:(nullable NSDictionary *)options + callback:(HippyPromiseResolveBlock)callback ) { + if (options && [[options objectForKey:HippyViewManagerGetBoundingRelToContainerKey] boolValue]) { [self measureInWindow:hippyTag withErrMsg:YES callback:callback]; } else { [self measureInAppWindow:hippyTag withErrMsg:YES callback:callback]; } } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(measureInWindow:(NSNumber *)componentTag - callback:(RenderUIResponseSenderBlock)callback) { +HIPPY_EXPORT_METHOD(measureInWindow:(NSNumber *)componentTag + callback:(HippyPromiseResolveBlock)callback) { [self measureInWindow:componentTag withErrMsg:NO callback:callback]; } - (void)measureInWindow:(NSNumber *)componentTag withErrMsg:(BOOL)withErrMsg - callback:(RenderUIResponseSenderBlock)callback { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, + callback:(HippyPromiseResolveBlock)callback { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[componentTag]; if (!view) { if (withErrMsg) { NSString *formatStr = @"measure cannot find view with tag #%@"; NSString *errMsg = [NSString stringWithFormat:formatStr, componentTag]; - callback(@{NativeRenderViewManagerGetBoundingErrMsgrKey : errMsg}); + callback(@{HippyViewManagerGetBoundingErrMsgrKey : errMsg}); } else { callback(@{}); } @@ -107,7 +103,7 @@ - (void)measureInWindow:(NSNumber *)componentTag if (withErrMsg) { NSString *formatStr = @"measure cannot find view's root view with tag #%@"; NSString *errMsg = [NSString stringWithFormat:formatStr, componentTag]; - callback(@{NativeRenderViewManagerGetBoundingErrMsgrKey : errMsg}); + callback(@{HippyViewManagerGetBoundingErrMsgrKey : errMsg}); } else { callback(@{}); } @@ -121,15 +117,15 @@ - (void)measureInWindow:(NSNumber *)componentTag }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(measureInAppWindow:(NSNumber *)componentTag - callback:(RenderUIResponseSenderBlock)callback) { +HIPPY_EXPORT_METHOD(measureInAppWindow:(NSNumber *)componentTag + callback:(HippyPromiseResolveBlock)callback) { [self measureInAppWindow:componentTag withErrMsg:NO callback:callback]; } - (void)measureInAppWindow:(NSNumber *)componentTag withErrMsg:(BOOL)withErrMsg - callback:(RenderUIResponseSenderBlock)callback { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, + callback:(HippyPromiseResolveBlock)callback { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[componentTag]; if (!view) { @@ -144,10 +140,10 @@ - (void)measureInAppWindow:(NSNumber *)componentTag }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(getScreenShot:(nonnull NSNumber *)componentTag +HIPPY_EXPORT_METHOD(getScreenShot:(nonnull NSNumber *)componentTag params:(NSDictionary *__nonnull)params - callback:(RenderUIResponseSenderBlock)callback) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + callback:(HippyPromiseResolveBlock)callback) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[componentTag]; if (view == nil) { callback(@[]); @@ -184,10 +180,10 @@ - (void)measureInAppWindow:(NSNumber *)componentTag }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(getLocationOnScreen:(nonnull NSNumber *)componentTag +HIPPY_EXPORT_METHOD(getLocationOnScreen:(nonnull NSNumber *)componentTag params:(NSDictionary *__nonnull)params - callback:(RenderUIResponseSenderBlock)callback) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + callback:(HippyPromiseResolveBlock)callback) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { UIView *view = viewRegistry[componentTag]; if (view == nil) { callback(@[]); @@ -206,22 +202,22 @@ - (void)measureInAppWindow:(NSNumber *)componentTag #pragma mark - View properties -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(accessibilityLabel, NSString) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(backgroundColor, UIColor) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(shadowSpread, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(accessibilityLabel, NSString) +HIPPY_EXPORT_VIEW_PROPERTY(backgroundColor, UIColor) +HIPPY_EXPORT_VIEW_PROPERTY(shadowSpread, CGFloat) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(accessible, isAccessibilityElement, BOOL) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(opacity, alpha, CGFloat) +HIPPY_REMAP_VIEW_PROPERTY(accessible, isAccessibilityElement, BOOL) +HIPPY_REMAP_VIEW_PROPERTY(opacity, alpha, CGFloat) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(shadowOpacity, layer.shadowOpacity, float) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(shadowRadius, layer.shadowRadius, CGFloat) +HIPPY_REMAP_VIEW_PROPERTY(shadowOpacity, layer.shadowOpacity, float) +HIPPY_REMAP_VIEW_PROPERTY(shadowRadius, layer.shadowRadius, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(backgroundPositionX, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(backgroundPositionY, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onInterceptTouchEvent, BOOL) -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(visibility, NSString, NativeRenderView) { +HIPPY_EXPORT_VIEW_PROPERTY(backgroundPositionX, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(backgroundPositionY, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(onInterceptTouchEvent, BOOL) +HIPPY_CUSTOM_VIEW_PROPERTY(visibility, NSString, HippyView) { if (json) { - NSString *status = [HPConvert NSString:json]; + NSString *status = [HippyConvert NSString:json]; view.hidden = [status isEqualToString:@"hidden"]; } else { @@ -229,9 +225,9 @@ - (void)measureInAppWindow:(NSNumber *)componentTag } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(backgroundImage, NSString, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(backgroundImage, NSString, HippyView) { if (json) { - NSString *imagePath = [HPConvert NSString:json]; + NSString *imagePath = [HippyConvert NSString:json]; [self loadImageSource:imagePath forView:view]; } else { @@ -239,21 +235,23 @@ - (void)measureInAppWindow:(NSNumber *)componentTag } } -- (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { +- (void)loadImageSource:(NSString *)path forView:(HippyView *)view { if (!path || !view) { return; } NSString *standardizeAssetUrlString = path; - __weak NativeRenderView *weakView = view; - auto loader = [[self renderImpl] VFSUriLoader].lock(); + __weak HippyView *weakView = view; + auto loader = [self.bridge.uiManager VFSUriLoader].lock(); if (!loader) { return; } + __weak __typeof(self)weakSelf = self; loader->RequestUntrustedContent(path, nil, nil, ^(NSData *data, NSURLResponse *response, NSError *error) { - NativeRenderImpl *renderImpl = self.renderImpl; - id imageProvider = nil; + __strong __typeof(weakSelf)strongSelf = weakSelf; + HippyUIManager *renderImpl = strongSelf.bridge.uiManager; + id imageProvider = nil; if (renderImpl) { - for (Class cls in [renderImpl imageProviderClasses]) { + for (Class cls in [strongSelf.bridge imageProviderClasses]) { if ([cls canHandleData:data]) { imageProvider = [[(Class)cls alloc] init]; break; @@ -263,7 +261,7 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { [imageProvider setImageData:data]; UIImage *backgroundImage = [imageProvider image]; dispatch_async(dispatch_get_main_queue(), ^{ - NativeRenderView *strongView = weakView; + HippyView *strongView = weakView; if (strongView) { strongView.backgroundImage = backgroundImage; } @@ -272,9 +270,9 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { }); } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(linearGradient, NSDictionary, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(linearGradient, NSDictionary, HippyView) { if (json) { - NSDictionary *linearGradientObject = [HPConvert NSDictionary:json]; + NSDictionary *linearGradientObject = [HippyConvert NSDictionary:json]; view.gradientObject = [[NativeRenderGradientObject alloc] initWithGradientObject:linearGradientObject]; [view.layer setNeedsDisplay]; } @@ -284,27 +282,27 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(backgroundSize, NSString, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(backgroundSize, NSString, HippyView) { NSString *bgSize = @"auto"; if (json) { - bgSize = [HPConvert NSString:json]; + bgSize = [HippyConvert NSString:json]; } view.backgroundSize = bgSize; [view.layer setNeedsDisplay]; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(shadowColor, UIColor, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(shadowColor, UIColor, HippyView) { if (json) { - view.layer.shadowColor = [HPConvert UIColor:json].CGColor; + view.layer.shadowColor = [HippyConvert UIColor:json].CGColor; } else { view.layer.shadowColor = defaultView.layer.shadowColor; } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(shadowOffsetX, CGFloat, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(shadowOffsetX, CGFloat, HippyView) { CGSize shadowOffset = view.layer.shadowOffset; if (json) { - shadowOffset.width = [HPConvert CGFloat:json]; + shadowOffset.width = [HippyConvert CGFloat:json]; } else { shadowOffset.width = defaultView.layer.shadowOffset.width; @@ -312,10 +310,10 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { view.layer.shadowOffset = shadowOffset; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(shadowOffsetY, CGFloat, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(shadowOffsetY, CGFloat, HippyView) { CGSize shadowOffset = view.layer.shadowOffset; if (json) { - shadowOffset.height = [HPConvert CGFloat:json]; + shadowOffset.height = [HippyConvert CGFloat:json]; } else { shadowOffset.height = defaultView.layer.shadowOffset.height; @@ -323,9 +321,9 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { view.layer.shadowOffset = shadowOffset; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(shadowOffset, NSDictionary, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(shadowOffset, NSDictionary, HippyView) { if (json) { - NSDictionary *offset = [HPConvert NSDictionary:json]; + NSDictionary *offset = [HippyConvert NSDictionary:json]; NSNumber *width = offset[@"width"]; if (nil == width) { width = offset[@"x"]; @@ -341,25 +339,25 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(overflow, NSString, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(overflow, NSString, HippyView) { if (json) { view.clipsToBounds = ![json isEqualToString:@"visible"]; } else { view.clipsToBounds = defaultView.clipsToBounds; } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(shouldRasterizeIOS, BOOL, NativeRenderView) { - view.layer.shouldRasterize = json ? [HPConvert BOOL:json] : defaultView.layer.shouldRasterize; +HIPPY_CUSTOM_VIEW_PROPERTY(shouldRasterizeIOS, BOOL, HippyView) { + view.layer.shouldRasterize = json ? [HippyConvert BOOL:json] : defaultView.layer.shouldRasterize; view.layer.rasterizationScale = view.layer.shouldRasterize ? [UIScreen mainScreen].scale : defaultView.layer.rasterizationScale; } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(transform, CATransform3D, NativeRenderView) { - view.layer.transform = json ? [HPConvert CATransform3D:json] : defaultView.layer.transform; +HIPPY_CUSTOM_VIEW_PROPERTY(transform, CATransform3D, HippyView) { + view.layer.transform = json ? [HippyConvert CATransform3D:json] : defaultView.layer.transform; view.layer.allowsEdgeAntialiasing = !CATransform3DIsIdentity(view.layer.transform); } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(pointerEvents, NativeRenderPointerEvents, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(pointerEvents, NativeRenderPointerEvents, HippyView) { if ([view respondsToSelector:@selector(setPointerEvents:)]) { - view.pointerEvents = json ? [HPConvert NativeRenderPointerEvents:json] : defaultView.pointerEvents; + view.pointerEvents = json ? [HippyConvert NativeRenderPointerEvents:json] : defaultView.pointerEvents; return; } @@ -368,11 +366,11 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { return; } - switch ([HPConvert NativeRenderPointerEvents:json]) { + switch ([HippyConvert NativeRenderPointerEvents:json]) { case NativeRenderPointerEventsUnspecified: // Pointer events "unspecified" acts as if a stylesheet had not specified, // which is different than "auto" in CSS (which cannot and will not be - // supported in `NativeRender`. "auto" may override a parent's "none". + // supported in `Hippy`. "auto" may override a parent's "none". // Unspecified values do not. // This wouldn't override a container view's `userInteractionEnabled = NO` view.userInteractionEnabled = YES; @@ -381,48 +379,48 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { view.userInteractionEnabled = NO; break; default: - HPLogError(@"UIView base class does not support pointerEvent value: %@", json); + HippyLogError(@"UIView base class does not support pointerEvent value: %@", json); break; } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(borderRadius, CGFloat, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(borderRadius, CGFloat, HippyView) { if ([view respondsToSelector:@selector(setBorderRadius:)]) { - view.borderRadius = json ? [HPConvert CGFloat:json] : defaultView.borderRadius; + view.borderRadius = json ? [HippyConvert CGFloat:json] : defaultView.borderRadius; } else { - view.layer.cornerRadius = json ? [HPConvert CGFloat:json] : defaultView.layer.cornerRadius; + view.layer.cornerRadius = json ? [HippyConvert CGFloat:json] : defaultView.layer.cornerRadius; } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(borderColor, CGColor, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(borderColor, CGColor, HippyView) { if ([view respondsToSelector:@selector(setBorderColor:)]) { - view.borderColor = json ? [HPConvert CGColor:json] : defaultView.borderColor; + view.borderColor = json ? [HippyConvert CGColor:json] : defaultView.borderColor; } else { - view.layer.borderColor = json ? [HPConvert CGColor:json] : defaultView.layer.borderColor; + view.layer.borderColor = json ? [HippyConvert CGColor:json] : defaultView.layer.borderColor; } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(borderWidth, CGFloat, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(borderWidth, CGFloat, HippyView) { if ([view respondsToSelector:@selector(setBorderWidth:)]) { - view.borderWidth = json ? [HPConvert CGFloat:json] : defaultView.borderWidth; + view.borderWidth = json ? [HippyConvert CGFloat:json] : defaultView.borderWidth; } else { - view.layer.borderWidth = json ? [HPConvert CGFloat:json] : defaultView.layer.borderWidth; + view.layer.borderWidth = json ? [HippyConvert CGFloat:json] : defaultView.layer.borderWidth; } } -NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(borderStyle, NativeRenderBorderStyle, NativeRenderView) { +HIPPY_CUSTOM_VIEW_PROPERTY(borderStyle, NativeRenderBorderStyle, HippyView) { if ([view respondsToSelector:@selector(setBorderStyle:)]) { - view.borderStyle = json ? [HPConvert NativeRenderBorderStyle:json] : defaultView.borderStyle; + view.borderStyle = json ? [HippyConvert NativeRenderBorderStyle:json] : defaultView.borderStyle; } } #define NATIVE_RENDER_VIEW_BORDER_PROPERTY(SIDE) \ - NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(border##SIDE##Width, CGFloat, NativeRenderView) { \ + HIPPY_CUSTOM_VIEW_PROPERTY(border##SIDE##Width, CGFloat, HippyView) { \ if ([view respondsToSelector:@selector(setBorder##SIDE##Width:)]) { \ - view.border##SIDE##Width = json ? [HPConvert CGFloat:json] : defaultView.border##SIDE##Width; \ + view.border##SIDE##Width = json ? [HippyConvert CGFloat:json] : defaultView.border##SIDE##Width; \ } \ } \ - NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(border##SIDE##Color, UIColor, NativeRenderView) { \ + HIPPY_CUSTOM_VIEW_PROPERTY(border##SIDE##Color, UIColor, HippyView) { \ if ([view respondsToSelector:@selector(setBorder##SIDE##Color:)]) { \ - view.border##SIDE##Color = json ? [HPConvert CGColor:json] : defaultView.border##SIDE##Color; \ + view.border##SIDE##Color = json ? [HippyConvert CGColor:json] : defaultView.border##SIDE##Color; \ } \ } @@ -432,9 +430,9 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { NATIVE_RENDER_VIEW_BORDER_PROPERTY(Left) #define NATIVE_RENDER_VIEW_BORDER_RADIUS_PROPERTY(SIDE) \ - NATIVE_RENDER_CUSTOM_VIEW_PROPERTY(border##SIDE##Radius, CGFloat, NativeRenderView) { \ + HIPPY_CUSTOM_VIEW_PROPERTY(border##SIDE##Radius, CGFloat, HippyView) { \ if ([view respondsToSelector:@selector(setBorder##SIDE##Radius:)]) { \ - view.border##SIDE##Radius = json ? [HPConvert CGFloat:json] : defaultView.border##SIDE##Radius; \ + view.border##SIDE##Radius = json ? [HippyConvert CGFloat:json] : defaultView.border##SIDE##Radius; \ } \ } @@ -443,63 +441,63 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { NATIVE_RENDER_VIEW_BORDER_RADIUS_PROPERTY(BottomLeft) NATIVE_RENDER_VIEW_BORDER_RADIUS_PROPERTY(BottomRight) -NATIVE_RENDER_REMAP_VIEW_PROPERTY(zIndex, nativeRenderZIndex, NSInteger) +HIPPY_REMAP_VIEW_PROPERTY(zIndex, hippyZIndex, NSInteger) #pragma mark - native render object properties -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(backgroundColor, UIColor) +HIPPY_EXPORT_SHADOW_PROPERTY(backgroundColor, UIColor) //TODO remove layout codes -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(top, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(right, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(bottom, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(left, CGFloat); - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(width, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(height, CGFloat) - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(minWidth, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(maxWidth, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(minHeight, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(maxHeight, CGFloat) - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(borderTopWidth, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(borderRightWidth, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(borderBottomWidth, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(borderLeftWidth, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(borderWidth, CGFloat) - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(marginTop, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(marginRight, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(marginBottom, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(marginLeft, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(marginVertical, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(marginHorizontal, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(margin, CGFloat) - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(paddingTop, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(paddingRight, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(paddingBottom, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(paddingLeft, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(paddingVertical, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(paddingHorizontal, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(padding, CGFloat) - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(flex, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(flexGrow, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(flexShrink, CGFloat) -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(flexBasis, CGFloat) - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(overflow, NSString) - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(onLayout, NativeRenderDirectEventBlock) - -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onDidMount, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onDidUnmount, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onAttachedToWindow, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onDetachedFromWindow, NativeRenderDirectEventBlock) - -NATIVE_RENDER_EXPORT_RENDER_OBJECT_PROPERTY(zIndex, NSInteger) +HIPPY_EXPORT_SHADOW_PROPERTY(top, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(right, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(bottom, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(left, CGFloat); + +HIPPY_EXPORT_SHADOW_PROPERTY(width, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(height, CGFloat) + +HIPPY_EXPORT_SHADOW_PROPERTY(minWidth, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(maxWidth, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(minHeight, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(maxHeight, CGFloat) + +HIPPY_EXPORT_SHADOW_PROPERTY(borderTopWidth, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(borderRightWidth, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(borderBottomWidth, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(borderLeftWidth, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(borderWidth, CGFloat) + +HIPPY_EXPORT_SHADOW_PROPERTY(marginTop, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(marginRight, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(marginBottom, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(marginLeft, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(marginVertical, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(marginHorizontal, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(margin, CGFloat) + +HIPPY_EXPORT_SHADOW_PROPERTY(paddingTop, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(paddingRight, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(paddingBottom, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(paddingLeft, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(paddingVertical, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(paddingHorizontal, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(padding, CGFloat) + +HIPPY_EXPORT_SHADOW_PROPERTY(flex, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(flexGrow, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(flexShrink, CGFloat) +HIPPY_EXPORT_SHADOW_PROPERTY(flexBasis, CGFloat) + +HIPPY_EXPORT_SHADOW_PROPERTY(overflow, NSString) + +HIPPY_EXPORT_SHADOW_PROPERTY(onLayout, HippyDirectEventBlock) + +HIPPY_EXPORT_VIEW_PROPERTY(onDidMount, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onDidUnmount, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onAttachedToWindow, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onDetachedFromWindow, HippyDirectEventBlock) + +HIPPY_EXPORT_SHADOW_PROPERTY(zIndex, NSInteger) static inline hippy::Direction ConvertDirection(id direction) { if (!direction) { @@ -522,18 +520,18 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { return hippy::Direction::Inherit; } -NATIVE_RENDER_CUSTOM_RENDER_OBJECT_PROPERTY(direction, id, NativeRenderObjectView) { +HIPPY_CUSTOM_SHADOW_PROPERTY(direction, id, HippyShadowView) { view.layoutDirection = ConvertDirection(json); } -NATIVE_RENDER_CUSTOM_RENDER_OBJECT_PROPERTY(verticalAlign, HippyTextAttachmentVerticalAlign, NativeRenderObjectView) { +HIPPY_CUSTOM_SHADOW_PROPERTY(verticalAlign, HippyTextAttachmentVerticalAlign, HippyShadowView) { if (json && [json isKindOfClass:NSString.class]) { - view.verticalAlignType = [HPConvert NativeRenderTextVerticalAlignType:json]; + view.verticalAlignType = [HippyConvert NativeRenderTextVerticalAlignType:json]; } else if ([json isKindOfClass:NSNumber.class]) { view.verticalAlignType = NativeRenderTextVerticalAlignMiddle; - view.verticalAlignOffset = [HPConvert CGFloat:json]; + view.verticalAlignOffset = [HippyConvert CGFloat:json]; } else { - HPLogError(@"Unsupported value for verticalAlign of Text: %@, type: %@", json, [json classForCoder]); + HippyLogError(@"Unsupported value for verticalAlign of Text: %@, type: %@", json, [json classForCoder]); } } @@ -544,7 +542,7 @@ - (void)loadImageSource:(NSString *)path forView:(NativeRenderView *)view { static const char *init_props_identifier = "init_props_identifier"; -@implementation NativeRenderViewManager (InitProps) +@implementation HippyViewManager (InitProps) - (NSDictionary *)props { return objc_getAssociatedObject(self, init_props_identifier); diff --git a/renderer/native/ios/renderer/component/view/NativeRenderTouchesProtocol.h b/renderer/native/ios/renderer/component/view/NativeRenderTouchesProtocol.h index 31a61481f97..1fb3887149d 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderTouchesProtocol.h +++ b/renderer/native/ios/renderer/component/view/NativeRenderTouchesProtocol.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/view/NativeRenderTouchesView.h b/renderer/native/ios/renderer/component/view/NativeRenderTouchesView.h index 32b7da82354..e4789546b2e 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderTouchesView.h +++ b/renderer/native/ios/renderer/component/view/NativeRenderTouchesView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,7 +23,7 @@ #import #import "NativeRenderTouchesProtocol.h" -#import "HPConvert+NativeRender.h" +#import "HippyConvert+NativeRender.h" NS_ASSUME_NONNULL_BEGIN diff --git a/renderer/native/ios/renderer/component/view/NativeRenderTouchesView.m b/renderer/native/ios/renderer/component/view/NativeRenderTouchesView.m index 18b0e306903..049074aa0c3 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderTouchesView.m +++ b/renderer/native/ios/renderer/component/view/NativeRenderTouchesView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -24,7 +24,7 @@ #import "UIEvent+TouchResponder.h" #import "UIView+DomEvent.h" #import "UIView+MountEvent.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "objc/runtime.h" @interface NativeRenderTouchesView () { @@ -186,7 +186,7 @@ - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { case NativeRenderPointerEventsBoxNone: return hitSubview; default: - HPLogError(@"Invalid pointer-events specified %ld on %@", (long)_pointerEvents, self); + HippyLogError(@"Invalid pointer-events specified %ld on %@", (long)_pointerEvents, self); return hitSubview ?: hitView; } } diff --git a/renderer/native/ios/renderer/component/view/NativeRenderViewEventType.h b/renderer/native/ios/renderer/component/view/NativeRenderViewEventType.h index bfe12d55ccf..fc4b7bfa74a 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderViewEventType.h +++ b/renderer/native/ios/renderer/component/view/NativeRenderViewEventType.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "MacroDefines.h" +#import "HippyDefines.h" typedef NS_ENUM(NSInteger, NativeRenderViewEventType) { //touche event @@ -45,6 +45,6 @@ typedef NS_ENUM(NSInteger, NativeRenderViewEventType) { NativeRenderViewEventTypeUnknown = -1, }; -HP_EXTERN NativeRenderViewEventType viewEventTypeFromName(const char * _Nullable name); +HIPPY_EXTERN NativeRenderViewEventType viewEventTypeFromName(const char * _Nullable name); -HP_EXTERN const char *_Nullable viewEventNameFromType(NativeRenderViewEventType eventType); +HIPPY_EXTERN const char *_Nullable viewEventNameFromType(NativeRenderViewEventType eventType); diff --git a/renderer/native/ios/renderer/component/view/NativeRenderViewEventType.mm b/renderer/native/ios/renderer/component/view/NativeRenderViewEventType.mm index cd23870d428..6484ff8bfdf 100644 --- a/renderer/native/ios/renderer/component/view/NativeRenderViewEventType.mm +++ b/renderer/native/ios/renderer/component/view/NativeRenderViewEventType.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/view/UIEvent+TouchResponder.h b/renderer/native/ios/renderer/component/view/UIEvent+TouchResponder.h index e694296f01a..c869b7780ae 100644 --- a/renderer/native/ios/renderer/component/view/UIEvent+TouchResponder.h +++ b/renderer/native/ios/renderer/component/view/UIEvent+TouchResponder.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/view/UIEvent+TouchResponder.m b/renderer/native/ios/renderer/component/view/UIEvent+TouchResponder.m index d7883f0b69f..af1a68533ab 100644 --- a/renderer/native/ios/renderer/component/view/UIEvent+TouchResponder.m +++ b/renderer/native/ios/renderer/component/view/UIEvent+TouchResponder.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/view/UIView+DirectionalLayout.h b/renderer/native/ios/renderer/component/view/UIView+DirectionalLayout.h index dd7662ffe5b..a9af37d1c7a 100644 --- a/renderer/native/ios/renderer/component/view/UIView+DirectionalLayout.h +++ b/renderer/native/ios/renderer/component/view/UIView+DirectionalLayout.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/view/UIView+DirectionalLayout.mm b/renderer/native/ios/renderer/component/view/UIView+DirectionalLayout.mm index d7417fc7772..642a5b23574 100644 --- a/renderer/native/ios/renderer/component/view/UIView+DirectionalLayout.mm +++ b/renderer/native/ios/renderer/component/view/UIView+DirectionalLayout.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,8 +21,8 @@ */ #import "UIView+DirectionalLayout.h" -#import "UIView+NativeRender.h" -#import "HPI18nUtils.h" +#import "UIView+Hippy.h" +#import "HippyI18nUtils.h" #include diff --git a/renderer/native/ios/renderer/component/view/UIView+DomEvent.h b/renderer/native/ios/renderer/component/view/UIView+DomEvent.h index 882de0c6b3b..08a638bf7a1 100644 --- a/renderer/native/ios/renderer/component/view/UIView+DomEvent.h +++ b/renderer/native/ios/renderer/component/view/UIView+DomEvent.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,7 +23,7 @@ #import #import "NativeRenderTouchesProtocol.h" -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" NS_ASSUME_NONNULL_BEGIN @@ -45,7 +45,7 @@ NS_ASSUME_NONNULL_BEGIN * @param name event name * @param callback event call back for event */ -- (void)addPropertyEvent:(const char *)name eventCallback:(NativeRenderDirectEventBlock)callback; +- (void)addPropertyEvent:(const char *)name eventCallback:(HippyDirectEventBlock)callback; /** * Remove status change event for view @@ -60,7 +60,7 @@ NS_ASSUME_NONNULL_BEGIN * * @discussion The default implementation of this method is to trigger onDidMount event if it is onDidMount event */ -- (void)didAddPropertyEvent:(const char *)name eventCallback:(NativeRenderDirectEventBlock)callback; +- (void)didAddPropertyEvent:(const char *)name eventCallback:(HippyDirectEventBlock)callback; /** * Notify view event has been removed from view diff --git a/renderer/native/ios/renderer/component/view/UIView+DomEvent.mm b/renderer/native/ios/renderer/component/view/UIView+DomEvent.mm index 7521c4e181f..a82d9fd54a6 100644 --- a/renderer/native/ios/renderer/component/view/UIView+DomEvent.mm +++ b/renderer/native/ios/renderer/component/view/UIView+DomEvent.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,7 +23,7 @@ #import "UIView+DomEvent.h" #import #import "UIView+MountEvent.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "UIEvent+TouchResponder.h" #include "dom/dom_listener.h" @@ -82,7 +82,7 @@ static SEL SelectorFromCName(const char *name) { return selector; } -- (void)addPropertyEvent:(const char *)name eventCallback:(NativeRenderDirectEventBlock)callback { +- (void)addPropertyEvent:(const char *)name eventCallback:(HippyDirectEventBlock)callback { @try { SEL selector = SelectorFromCName(name); if ([self respondsToSelector:selector]) { @@ -100,7 +100,7 @@ - (void)addPropertyEvent:(const char *)name eventCallback:(NativeRenderDirectEve } } -- (void)didAddPropertyEvent:(const char *)name eventCallback:(NativeRenderDirectEventBlock)callback { +- (void)didAddPropertyEvent:(const char *)name eventCallback:(HippyDirectEventBlock)callback { if (!name) { return; } @@ -123,7 +123,7 @@ - (void)removePropertyEvent:(const char *)name { SEL selector = SelectorFromCName(name); @try { if ([self respondsToSelector:selector]) { - NativeRenderDirectEventBlock cb = NULL; + HippyDirectEventBlock cb = NULL; NSMethodSignature *methodSign = [self methodSignatureForSelector:selector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSign]; [invocation setTarget:self]; diff --git a/renderer/native/ios/renderer/component/view/UIView+NativeRender.h b/renderer/native/ios/renderer/component/view/UIView+Hippy.h similarity index 63% rename from renderer/native/ios/renderer/component/view/UIView+NativeRender.h rename to renderer/native/ios/renderer/component/view/UIView+Hippy.h index 3928aeade2c..18d19d9a9f9 100644 --- a/renderer/native/ios/renderer/component/view/UIView+NativeRender.h +++ b/renderer/native/ios/renderer/component/view/UIView+Hippy.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,26 +21,31 @@ */ #import +#import "HippyComponent.h" -#import "NativeRenderComponentProtocol.h" +@class HippyShadowView; -@class NativeRenderObjectView; +@interface UIView (Hippy) -@interface UIView (NativeRender) +/** + * reset all hippy subviews + */ +- (void)resetHippySubviews; /** - * NativeRenderComponent interface. + * reset all hippy subviews */ -- (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex; -- (void)moveNativeRenderSubview:(UIView *)subview toIndex:(NSInteger)atIndex; -- (void)removeNativeRenderSubview:(UIView *)subview; -- (void)resetNativeRenderSubviews; - (void)clearSortedSubviews; + +/** + * TODO: remove + */ - (UIView *)NativeRenderRootView; + /** * z-index, used to override sibling order in didUpdateHippySubviews. */ -@property (nonatomic, assign) NSInteger nativeRenderZIndex; +@property (nonatomic, assign) NSInteger hippyZIndex; /** * set true when hippy subviews changed, but subviews does not. @@ -58,24 +63,25 @@ * Updates the subviews array based on the hippySubviews. Default behavior is * to insert the sortedHippySubviews into the UIView. */ -- (void)didUpdateNativeRenderSubviews; +- (void)didUpdateHippySubviews; /** * Used by the UIIManager to set the view frame. * May be overriden to disable animation, etc. */ -- (void)nativeRenderSetFrame:(CGRect)frame; +- (void)hippySetFrame:(CGRect)frame; /** * Used to improve performance when compositing views with translucent content. */ -- (void)nativeRenderSetInheritedBackgroundColor:(UIColor *)inheritedBackgroundColor; +- (void)hippySetInheritedBackgroundColor:(UIColor *)inheritedBackgroundColor; /** * This method finds and returns the containing view controller for the view. */ -- (UIViewController *)nativeRenderViewController; +- (UIViewController *)hippyViewController; +// FIXME: remove this method /** * CellView is reusable. * but sometimes it misdisplays. @@ -84,14 +90,6 @@ */ - (BOOL)canBeRetrievedFromViewCache; -/** - * This method attaches the specified controller as a child of the - * the owning view controller of this view. Returns NO if no view - * controller is found (which may happen if the view is not currently - * attached to the view hierarchy). - */ -- (void)NativeRenderAddControllerToClosestParent:(UIViewController *)controller; - -@property (nonatomic, weak) __kindof NativeRenderObjectView *nativeRenderObjectView; +@property (nonatomic, weak) __kindof HippyShadowView *hippyShadowView; @end diff --git a/renderer/native/ios/renderer/component/view/UIView+NativeRender.mm b/renderer/native/ios/renderer/component/view/UIView+Hippy.mm similarity index 73% rename from renderer/native/ios/renderer/component/view/UIView+NativeRender.mm rename to renderer/native/ios/renderer/component/view/UIView+Hippy.mm index b16410f1667..dfc58a9c1ad 100644 --- a/renderer/native/ios/renderer/component/view/UIView+NativeRender.mm +++ b/renderer/native/ios/renderer/component/view/UIView+Hippy.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,20 +20,20 @@ * limitations under the License. */ -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" #import "UIView+MountEvent.h" -#import "HPLog.h" +#import "HippyLog.h" -@implementation UIView (NativeRender) +@implementation UIView (Hippy) -- (NSNumber *)componentTag { +- (NSNumber *)hippyTag { return objc_getAssociatedObject(self, _cmd); } -- (void)setComponentTag:(NSNumber *)tag { - objc_setAssociatedObject(self, @selector(componentTag), tag, OBJC_ASSOCIATION_COPY_NONATOMIC); +- (void)setHippyTag:(NSNumber *)tag { + objc_setAssociatedObject(self, @selector(hippyTag), tag, OBJC_ASSOCIATION_COPY_NONATOMIC); } - (NSNumber *)rootTag { @@ -68,29 +68,29 @@ - (void)setTagName:(NSString *)tagName { objc_setAssociatedObject(self, @selector(tagName), tagName, OBJC_ASSOCIATION_COPY_NONATOMIC); } -- (__kindof NativeRenderObjectView *)nativeRenderObjectView { +- (__kindof HippyShadowView *)hippyShadowView { NSHashTable *hashTable = objc_getAssociatedObject(self, _cmd); return [hashTable anyObject]; } -- (void)setNativeRenderObjectView:(__kindof NativeRenderObjectView *)renderObject { +- (void)setHippyShadowView:(__kindof HippyShadowView *)renderObject { NSHashTable *hashTable = [NSHashTable weakObjectsHashTable]; if (renderObject) { [hashTable addObject:renderObject]; } - objc_setAssociatedObject(self, @selector(nativeRenderObjectView), hashTable, OBJC_ASSOCIATION_RETAIN); + objc_setAssociatedObject(self, @selector(hippyShadowView), hashTable, OBJC_ASSOCIATION_RETAIN); } -- (BOOL)isNativeRenderRootView { - return NativeRenderIsRootView(self.componentTag); +- (BOOL)isHippyRootView { + return HippyIsHippyRootView(self.hippyTag); } -- (NSNumber *)componentTagAtPoint:(CGPoint)point { +- (NSNumber *)hippyTagAtPoint:(CGPoint)point { UIView *view = [self hitTest:point withEvent:nil]; - while (view && !view.componentTag) { + while (view && !view.hippyTag) { view = view.superview; } - return view.componentTag; + return view.hippyTag; } - (NSArray *)subcomponents { @@ -101,7 +101,7 @@ - (UIView *)parentComponent { return [objc_getAssociatedObject(self, _cmd) anyObject]; } -- (void)setParentComponent:(__kindof id)parentComponent { +- (void)setParentComponent:(__kindof id)parentComponent { if (parentComponent) { NSHashTable *hashTable = [NSHashTable weakObjectsHashTable]; [hashTable addObject:parentComponent]; @@ -112,7 +112,7 @@ - (void)setParentComponent:(__kindof id)parentCom } } -- (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { +- (void)insertHippySubview:(UIView *)subview atIndex:(NSInteger)atIndex { // We access the associated object directly here in case someone overrides // the `subcomponents` getter method and returns an immutable array. if (nil == subview) { @@ -133,7 +133,7 @@ - (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { subview.parentComponent = self; } -- (void)moveNativeRenderSubview:(UIView *)subview toIndex:(NSInteger)atIndex { +- (void)moveHippySubview:(UIView *)subview toIndex:(NSInteger)atIndex { if (nil == subview) { return; } @@ -144,10 +144,10 @@ - (void)moveNativeRenderSubview:(UIView *)subview toIndex:(NSInteger)atIndex { if ([subviews containsObject:subview]) { [subviews removeObject:subview]; } - [self insertNativeRenderSubview:subview atIndex:atIndex]; + [self insertHippySubview:subview atIndex:atIndex]; } -- (void)removeNativeRenderSubview:(UIView *)subview { +- (void)removeHippySubview:(UIView *)subview { // We access the associated object directly here in case someone overrides // the `subcomponents` getter method and returns an immutable array. NSMutableArray *subviews = objc_getAssociatedObject(self, @selector(subcomponents)); @@ -157,11 +157,11 @@ - (void)removeNativeRenderSubview:(UIView *)subview { subview.parentComponent = nil; } -- (void)removeFromNativeRenderSuperview { - [(UIView *)self.parentComponent removeNativeRenderSubview:self]; +- (void)removeFromHippySuperview { + [(UIView *)self.parentComponent removeHippySubview:self]; } -- (void)resetNativeRenderSubviews { +- (void)resetHippySubviews { NSMutableArray *subviews = objc_getAssociatedObject(self, @selector(subcomponents)); if (subviews) { [subviews makeObjectsPerformSelector:@selector(sendDetachedFromWindowEvent)]; @@ -173,20 +173,20 @@ - (void)resetNativeRenderSubviews { - (UIView *)NativeRenderRootView { UIView *candidateRootView = self; - BOOL isRootView = [candidateRootView isNativeRenderRootView]; + BOOL isRootView = [candidateRootView isHippyRootView]; while (!isRootView && candidateRootView) { candidateRootView = [candidateRootView parentComponent]; - isRootView = [candidateRootView isNativeRenderRootView]; + isRootView = [candidateRootView isHippyRootView]; } return candidateRootView; } -- (NSInteger)nativeRenderZIndex { +- (NSInteger)hippyZIndex { return [objc_getAssociatedObject(self, _cmd) integerValue]; } -- (void)setNativeRenderZIndex:(NSInteger)zIndex { - objc_setAssociatedObject(self, @selector(nativeRenderZIndex), @(zIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +- (void)setHippyZIndex:(NSInteger)zIndex { + objc_setAssociatedObject(self, @selector(hippyZIndex), @(zIndex), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (BOOL)isNativeRenderSubviewsUpdated { @@ -203,13 +203,13 @@ - (void)setNativeRenderSubviewsUpdated:(BOOL)subViewsUpdated { // Check if sorting is required - in most cases it won't be BOOL sortingRequired = NO; for (UIView *subview in self.subcomponents) { - if (subview.nativeRenderZIndex != 0) { + if (subview.hippyZIndex != 0) { sortingRequired = YES; break; } } subviews = sortingRequired ? [self.subcomponents sortedArrayUsingComparator:^NSComparisonResult(UIView *a, UIView *b) { - if (a.nativeRenderZIndex > b.nativeRenderZIndex) { + if (a.hippyZIndex > b.hippyZIndex) { return NSOrderedDescending; } else { // ensure sorting is stable by treating equal zIndex as ascending so @@ -226,7 +226,7 @@ - (void)clearSortedSubviews { objc_setAssociatedObject(self, @selector(sortedNativeRenderSubviews), nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } -- (void)didUpdateNativeRenderSubviews { +- (void)didUpdateHippySubviews { for (UIView *subview in self.sortedNativeRenderSubviews) { if (subview.superview != self) { [subview sendAttachedToWindowEvent]; @@ -236,7 +236,7 @@ - (void)didUpdateNativeRenderSubviews { } } -- (void)nativeRenderSetFrame:(CGRect)frame { +- (void)hippySetFrame:(CGRect)frame { // These frames are in terms of anchorPoint = topLeft, but internally the // views are anchorPoint = center for easier scale and rotation animations. // Convert the frame so it works with anchorPoint = center. @@ -246,8 +246,8 @@ - (void)nativeRenderSetFrame:(CGRect)frame { // Avoid crashes due to nan coords if (isnan(position.x) || isnan(position.y) || isnan(bounds.origin.x) || isnan(bounds.origin.y) || isnan(bounds.size.width) || isnan(bounds.size.height)) { - HPLogError( - @"Invalid layout for (%@)%@. position: %@. bounds: %@", self.componentTag, self, NSStringFromCGPoint(position), NSStringFromCGRect(bounds)); + HippyLogError( + @"Invalid layout for (%@)%@. position: %@. bounds: %@", self.hippyTag, self, NSStringFromCGPoint(position), NSStringFromCGRect(bounds)); return; } @@ -257,11 +257,11 @@ - (void)nativeRenderSetFrame:(CGRect)frame { self.frame = frame; } -- (void)nativeRenderSetInheritedBackgroundColor:(__unused UIColor *)inheritedBackgroundColor { +- (void)hippySetInheritedBackgroundColor:(__unused UIColor *)inheritedBackgroundColor { // Does nothing by default } -- (UIViewController *)nativeRenderViewController { +- (UIViewController *)hippyViewController { id responder = [self nextResponder]; while (responder) { if ([responder isKindOfClass:[UIViewController class]]) { @@ -276,21 +276,6 @@ - (BOOL)canBeRetrievedFromViewCache { return YES; } -- (void)NativeRenderAddControllerToClosestParent:(UIViewController *)controller { - if (!controller.parentViewController) { - UIView *parentView = (UIView *)self.parentComponent; - while (parentView) { - if (parentView.nativeRenderViewController) { - [parentView.nativeRenderViewController addChildViewController:controller]; - [controller didMoveToParentViewController:parentView.nativeRenderViewController]; - break; - } - parentView = (UIView *)parentView.parentComponent; - } - return; - } -} - - (BOOL)interceptTouchEvent { return NO; } diff --git a/renderer/native/ios/renderer/component/view/UIView+MountEvent.h b/renderer/native/ios/renderer/component/view/UIView+MountEvent.h index 2d224721e73..f110eeca7a5 100644 --- a/renderer/native/ios/renderer/component/view/UIView+MountEvent.h +++ b/renderer/native/ios/renderer/component/view/UIView+MountEvent.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,18 +21,18 @@ */ #import -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" @interface UIView (MountEvent) -@property (nonatomic, copy) NativeRenderDirectEventBlock onAppear; -@property (nonatomic, copy) NativeRenderDirectEventBlock onDisappear; -@property (nonatomic, copy) NativeRenderDirectEventBlock onWillAppear; -@property (nonatomic, copy) NativeRenderDirectEventBlock onWillDisappear; -@property (nonatomic, copy) NativeRenderDirectEventBlock onDidMount; -@property (nonatomic, copy) NativeRenderDirectEventBlock onDidUnmount; -@property (nonatomic, copy) NativeRenderDirectEventBlock onAttachedToWindow; -@property (nonatomic, copy) NativeRenderDirectEventBlock onDetachedFromWindow; +@property (nonatomic, copy) HippyDirectEventBlock onAppear; +@property (nonatomic, copy) HippyDirectEventBlock onDisappear; +@property (nonatomic, copy) HippyDirectEventBlock onWillAppear; +@property (nonatomic, copy) HippyDirectEventBlock onWillDisappear; +@property (nonatomic, copy) HippyDirectEventBlock onDidMount; +@property (nonatomic, copy) HippyDirectEventBlock onDidUnmount; +@property (nonatomic, copy) HippyDirectEventBlock onAttachedToWindow; +@property (nonatomic, copy) HippyDirectEventBlock onDetachedFromWindow; - (void)viewAppearEvent; - (void)viewDisappearEvent; diff --git a/renderer/native/ios/renderer/component/view/UIView+MountEvent.m b/renderer/native/ios/renderer/component/view/UIView+MountEvent.m index b91c1e98e1a..89d10f80570 100644 --- a/renderer/native/ios/renderer/component/view/UIView+MountEvent.m +++ b/renderer/native/ios/renderer/component/view/UIView+MountEvent.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -26,11 +26,11 @@ @implementation UIView (MountEvent) #define MountEvent(setter, getter) \ - - (void)setter:(NativeRenderDirectEventBlock)getter { \ + - (void)setter:(HippyDirectEventBlock)getter { \ objc_setAssociatedObject(self, @selector(getter), getter, OBJC_ASSOCIATION_COPY); \ } \ \ - - (NativeRenderDirectEventBlock)getter { \ + - (HippyDirectEventBlock)getter { \ return objc_getAssociatedObject(self, @selector(getter)); \ } diff --git a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPager.h b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPager.h index 4f098560a1f..fd3a6a1f670 100644 --- a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPager.h +++ b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,7 +23,7 @@ #import #import -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" /** * A Callback block to indicate view pager's item count changed @@ -32,9 +32,9 @@ typedef void (^ViewPagerItemsCountChanged)(NSUInteger count); @interface NativeRenderViewPager : UIScrollView -@property (nonatomic, strong) NativeRenderDirectEventBlock onPageSelected; -@property (nonatomic, strong) NativeRenderDirectEventBlock onPageScroll; -@property (nonatomic, strong) NativeRenderDirectEventBlock onPageScrollStateChanged; +@property (nonatomic, strong) HippyDirectEventBlock onPageSelected; +@property (nonatomic, strong) HippyDirectEventBlock onPageScroll; +@property (nonatomic, strong) HippyDirectEventBlock onPageScrollStateChanged; @property (nonatomic, assign) NSInteger initialPage; @property (nonatomic, assign) CGPoint targetOffset; diff --git a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPager.mm b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPager.mm index a50eddca089..23c3daf3999 100644 --- a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPager.mm +++ b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,10 +22,10 @@ #import "NativeRenderViewPager.h" #import "NativeRenderViewPagerItem.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" #import "UIView+DirectionalLayout.h" #import "UIView+MountEvent.h" -#import "HPLog.h" +#import "HippyLog.h" #include "float.h" @@ -85,9 +85,9 @@ - (void)didMoveToSuperview { #pragma mark native render native methods -- (void)insertNativeRenderSubview:(UIView *)view atIndex:(NSInteger)atIndex { +- (void)insertHippySubview:(UIView *)view atIndex:(NSInteger)atIndex { if (atIndex > self.viewPagerItems.count) { - HPLogWarn(@"Error In NativeRenderViewPager: addSubview —— out of bound of array"); + HippyLogWarn(@"Error In NativeRenderViewPager: addSubview —— out of bound of array"); return; } if (atIndex < [self.viewPagerItems count]) { @@ -97,7 +97,7 @@ - (void)insertNativeRenderSubview:(UIView *)view atIndex:(NSInteger)atIndex { if ([self isLayoutSubviewsRTL]) { view.transform = CGAffineTransformMakeRotation(M_PI); } - [super insertNativeRenderSubview:view atIndex:(NSInteger)atIndex]; + [super insertHippySubview:view atIndex:(NSInteger)atIndex]; [self.viewPagerItems insertObject:view atIndex:atIndex]; if ([view isKindOfClass:[NativeRenderViewPagerItem class]]) { @@ -130,8 +130,8 @@ - (CGRect)frameForItemAtIndex:(NSInteger)index { return CGRectMake(originX, 0, viewPagerSize.width, viewPagerSize.height); } -- (void)removeNativeRenderSubview:(UIView *)subview { - [super removeNativeRenderSubview:subview]; +- (void)removeHippySubview:(UIView *)subview { + [super removeHippySubview:subview]; [self.viewPagerItems removeObject:subview]; [self setNeedsLayout]; if (_itemsChangedBlock) { @@ -139,15 +139,15 @@ - (void)removeNativeRenderSubview:(UIView *)subview { } } -- (void)nativeRenderSetFrame:(CGRect)frame { - [super nativeRenderSetFrame:frame]; +- (void)hippySetFrame:(CGRect)frame { + [super hippySetFrame:frame]; self.needsLayoutItems = YES; self.needsResetPageIndex = YES; [self setNeedsLayout]; } -- (void)didUpdateNativeRenderSubviews { - [super didUpdateNativeRenderSubviews]; +- (void)didUpdateHippySubviews { + [super didUpdateHippySubviews]; self.needsLayoutItems = YES; [self setNeedsLayout]; } @@ -155,7 +155,7 @@ - (void)didUpdateNativeRenderSubviews { #pragma mark native render js call methods - (void)setPage:(NSInteger)pageNumber animated:(BOOL)animated { if (pageNumber >= self.viewPagerItems.count || pageNumber < 0) { - HPLogWarn(@"Error In ViewPager setPage: pageNumber invalid"); + HippyLogWarn(@"Error In ViewPager setPage: pageNumber invalid"); return; } @@ -386,7 +386,7 @@ - (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated { [super setContentOffset:contentOffset animated:animated]; } -- (void)nativeRenderComponentDidFinishTransaction { +- (void)hippyBridgeDidFinishTransaction { BOOL isFrameEqual = CGRectEqualToRect(self.frame, self.previousFrame); BOOL isContentSizeEqual = CGSizeEqualToSize(self.contentSize, self.previousSize); @@ -413,14 +413,14 @@ - (void)layoutSubviews { } if (self.initialPage >= self.viewPagerItems.count) { - HPLogWarn(@"Error In NativeRenderViewPager: layoutSubviews"); + HippyLogWarn(@"Error In NativeRenderViewPager: layoutSubviews"); self.contentSize = CGSizeZero; return; } UIView *lastViewPagerItem = self.viewPagerItems.lastObject; if (!lastViewPagerItem) { - HPLogWarn(@"Error In NativeRenderViewPager: addSubview"); + HippyLogWarn(@"Error In NativeRenderViewPager: addSubview"); self.contentSize = CGSizeZero; return; } @@ -458,7 +458,7 @@ - (NSUInteger)nowPage { } if (thePage < 0) { - HPLogWarn(@"Error In ViewPager nowPage: thePage invalid"); + HippyLogWarn(@"Error In ViewPager nowPage: thePage invalid"); return 0; } else { return (NSUInteger)thePage; diff --git a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItem.h b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItem.h index 1eafcc691e1..91211699019 100644 --- a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItem.h +++ b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItem.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItem.m b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItem.m index b0a2541949f..b9b8f0539b6 100644 --- a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItem.m +++ b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItem.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItemManager.h b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItemManager.h index aad773cd1f2..8900825a99b 100644 --- a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItemManager.h +++ b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItemManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,8 +22,8 @@ #import -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderViewPagerItemManager : NativeRenderViewManager +@interface NativeRenderViewPagerItemManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItemManager.mm b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItemManager.mm index 674a75aa6c7..18c59e8e69d 100644 --- a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItemManager.mm +++ b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerItemManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -25,7 +25,7 @@ @implementation NativeRenderViewPagerItemManager -NATIVE_RENDER_EXPORT_VIEW(ViewPagerItem) +HIPPY_EXPORT_MODULE(ViewPagerItem) - (UIView *)view { return [NativeRenderViewPagerItem new]; diff --git a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerManager.h b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerManager.h index 6e0f2015287..bca2905cd6b 100644 --- a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerManager.h +++ b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,8 +22,8 @@ #import -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" -@interface NativeRenderViewPagerManager : NativeRenderViewManager +@interface NativeRenderViewPagerManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerManager.mm b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerManager.mm index 25512463abe..95a18448dbc 100644 --- a/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerManager.mm +++ b/renderer/native/ios/renderer/component/viewPager/NativeRenderViewPagerManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,45 +20,45 @@ * limitations under the License. */ -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" #import "NativeRenderViewPagerManager.h" #import "NativeRenderViewPager.h" @implementation NativeRenderViewPagerManager -NATIVE_RENDER_EXPORT_VIEW(ViewPager) +HIPPY_EXPORT_MODULE(ViewPager) - (UIView *)view { return [NativeRenderViewPager new]; } -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(bounces, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(initialPage, NSInteger) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollEnabled, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(bounces, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(initialPage, NSInteger) +HIPPY_EXPORT_VIEW_PROPERTY(scrollEnabled, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onPageSelected, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onPageScroll, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onPageScrollStateChanged, NativeRenderDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onPageSelected, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onPageScroll, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onPageScrollStateChanged, HippyDirectEventBlock) - (void)setPage:(NSNumber *)pageNumber withTag:(NSNumber * _Nonnull)componentTag animated:(BOOL)animated { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry){ UIView *view = viewRegistry[componentTag]; if (![view isKindOfClass:[NativeRenderViewPager class]]) { - HPLogError(@"tried to setPage: on an error viewPager %@ with tag #%@", view, componentTag); + HippyLogError(@"tried to setPage: on an error viewPager %@ with tag #%@", view, componentTag); } NSInteger pageNumberInteger = pageNumber.integerValue; [(NativeRenderViewPager *)view setPage:pageNumberInteger animated:animated]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(setPage:(nonnull NSNumber *)componentTag +HIPPY_EXPORT_METHOD(setPage:(nonnull NSNumber *)componentTag pageNumber:(__unused NSNumber *)pageNumber) { [self setPage:pageNumber withTag:componentTag animated:YES]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(setPageWithoutAnimation:(nonnull NSNumber *)componentTag +HIPPY_EXPORT_METHOD(setPageWithoutAnimation:(nonnull NSNumber *)componentTag pageNumber:(__unused NSNumber *)pageNumber) { [self setPage:pageNumber withTag:componentTag animated:NO]; } diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderCollectionViewWaterfallLayout.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderCollectionViewWaterfallLayout.h index 803340c9c7a..93a0f0e4db7 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderCollectionViewWaterfallLayout.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderCollectionViewWaterfallLayout.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderCollectionViewWaterfallLayout.m b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderCollectionViewWaterfallLayout.m index cfab3e87df5..9c7103e02e0 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderCollectionViewWaterfallLayout.m +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderCollectionViewWaterfallLayout.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfall.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfall.h index e80bae30453..a37c728a081 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfall.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfall.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,23 +20,23 @@ * limitations under the License. */ -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" #import "NativeRenderObjectWaterfallItem.h" NS_ASSUME_NONNULL_BEGIN @interface WaterfallItemChangeContext : NSObject -- (NSHashTable<__kindof NativeRenderObjectView *> *)addedItems; -- (NSHashTable<__kindof NativeRenderObjectView *> *)frameChangedItems; -- (NSSet<__kindof NativeRenderObjectView *> *)deletedItems; -- (NSHashTable<__kindof NativeRenderObjectView *> *)movedItems; +- (NSHashTable<__kindof HippyShadowView *> *)addedItems; +- (NSHashTable<__kindof HippyShadowView *> *)frameChangedItems; +- (NSSet<__kindof HippyShadowView *> *)deletedItems; +- (NSHashTable<__kindof HippyShadowView *> *)movedItems; - (void)clear; @end -@interface NativeRenderObjectWaterfall : NativeRenderObjectView +@interface NativeRenderObjectWaterfall : HippyShadowView @property(nonatomic, readonly, strong)WaterfallItemChangeContext *itemChangeContext; diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfall.mm b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfall.mm index 2d5cff0fde7..9008fe669d1 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfall.mm +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfall.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,19 +22,19 @@ #import "NativeRenderObjectWaterfall.h" #import "NativeRenderWaterfallView.h" -#import "HPAsserts.h" +#import "HippyAsserts.h" @interface WaterfallItemChangeContext () { - NSMutableSet *_deletedItems; - NSHashTable *_addedItems; - NSHashTable *_movedItems; - NSHashTable *_frameChangedItems; + NSMutableSet *_deletedItems; + NSHashTable *_addedItems; + NSHashTable *_movedItems; + NSHashTable *_frameChangedItems; } //append methods -- (void)appendDeletedItem:(NativeRenderObjectView *)objectView; -- (void)appendAddedItem:(NativeRenderObjectView *)objectView; -- (void)appendMovedItem:(NativeRenderObjectView *)objectView; -- (void)appendFrameChangedItem:(NativeRenderObjectView *)objectView; +- (void)appendDeletedItem:(HippyShadowView *)objectView; +- (void)appendAddedItem:(HippyShadowView *)objectView; +- (void)appendMovedItem:(HippyShadowView *)objectView; +- (void)appendFrameChangedItem:(HippyShadowView *)objectView; @end @@ -60,37 +60,37 @@ - (id)copyWithZone:(NSZone *)zone { return context; } -- (void)appendDeletedItem:(__kindof NativeRenderObjectView *)objectView { +- (void)appendDeletedItem:(__kindof HippyShadowView *)objectView { [_deletedItems addObject:objectView]; } -- (void)appendAddedItem:(__kindof NativeRenderObjectView *)objectView{ +- (void)appendAddedItem:(__kindof HippyShadowView *)objectView{ [_addedItems addObject:objectView]; } -- (void)appendMovedItem:(__kindof NativeRenderObjectView *)objectView { +- (void)appendMovedItem:(__kindof HippyShadowView *)objectView { [_movedItems addObject:objectView]; } -- (void)appendFrameChangedItem:(__kindof NativeRenderObjectView *)objectView { +- (void)appendFrameChangedItem:(__kindof HippyShadowView *)objectView { if (![_addedItems containsObject:objectView]) { [_frameChangedItems addObject:objectView]; } } -- (NSSet<__kindof NativeRenderObjectView *> *)deletedItems { +- (NSSet<__kindof HippyShadowView *> *)deletedItems { return [_deletedItems copy]; } -- (NSMapTable<__kindof NativeRenderObjectView *, NSNumber *> *)addedItems { +- (NSMapTable<__kindof HippyShadowView *, NSNumber *> *)addedItems { return [_addedItems copy]; } -- (NSMapTable<__kindof NativeRenderObjectView *, NSValue *> *)movedItems { +- (NSMapTable<__kindof HippyShadowView *, NSValue *> *)movedItems { return [_movedItems copy]; } -- (NSHashTable<__kindof NativeRenderObjectView *> *)frameChangedItems { +- (NSHashTable<__kindof HippyShadowView *> *)frameChangedItems { return [_frameChangedItems copy]; } @@ -134,8 +134,8 @@ - (WaterfallItemChangeContext *)itemChangeContext { return _itemChangeContext; } -- (void)insertNativeRenderSubview:(NativeRenderObjectView *)subview atIndex:(NSInteger)atIndex { - [super insertNativeRenderSubview:subview atIndex:atIndex]; +- (void)insertHippySubview:(HippyShadowView *)subview atIndex:(NSInteger)atIndex { + [super insertHippySubview:subview atIndex:atIndex]; if ([subview isKindOfClass:[NativeRenderObjectWaterfallItem class]]) { NativeRenderObjectWaterfallItem *objectItem = (NativeRenderObjectWaterfallItem *)subview; objectItem.observer = self; @@ -143,8 +143,8 @@ - (void)insertNativeRenderSubview:(NativeRenderObjectView *)subview atIndex:(NSI [_itemChangeContext appendAddedItem:subview]; } -- (void)removeNativeRenderSubview:(NativeRenderObjectView *)subview { - [super removeNativeRenderSubview:subview]; +- (void)removeHippySubview:(HippyShadowView *)subview { + [super removeHippySubview:subview]; if ([subview isKindOfClass:[NativeRenderObjectWaterfallItem class]]) { NativeRenderObjectWaterfallItem *objectItem = (NativeRenderObjectWaterfallItem *)subview; objectItem.observer = nil; @@ -152,8 +152,8 @@ - (void)removeNativeRenderSubview:(NativeRenderObjectView *)subview { [_itemChangeContext appendDeletedItem:subview]; } -- (void)moveNativeRenderSubview:(id)subview toIndex:(NSInteger)atIndex { - [super moveNativeRenderSubview:subview toIndex:atIndex]; +- (void)moveHippySubview:(id)subview toIndex:(NSInteger)atIndex { + [super moveHippySubview:subview toIndex:atIndex]; [_itemChangeContext appendMovedItem:subview]; } @@ -165,14 +165,14 @@ - (void)amendLayoutBeforeMount:(NSMutableSet *)blocks if ([self isPropagationDirty:NativeRenderUpdateLifecycleLayoutDirtied]) { __weak NativeRenderObjectWaterfall *weakSelf = self; WaterfallItemChangeContext *context = [_itemChangeContext copy]; - NSArray *dataSource = [self.subcomponents copy]; + NSArray *dataSource = [self.subcomponents copy]; NativeRenderApplierBlock block = ^void(NSDictionary *viewRegistry) { NativeRenderObjectWaterfall *strongSelf = weakSelf; if (!strongSelf) { return; } - NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)[viewRegistry objectForKey:[strongSelf componentTag]]; - HPAssert([view isKindOfClass:[NativeRenderWaterfallView class]], @"view must be kind of NativeRenderWaterfallView"); + NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)[viewRegistry objectForKey:[strongSelf hippyTag]]; + HippyAssert([view isKindOfClass:[NativeRenderWaterfallView class]], @"view must be kind of NativeRenderWaterfallView"); if ([view isKindOfClass:[NativeRenderWaterfallView class]]) { view.dirtyContent = YES; view.changeContext = [context copy]; diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfallItem.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfallItem.h index c640accf17b..2691eefc9e9 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfallItem.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfallItem.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" NS_ASSUME_NONNULL_BEGIN @@ -33,7 +33,7 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface NativeRenderObjectWaterfallItem : NativeRenderObjectView +@interface NativeRenderObjectWaterfallItem : HippyShadowView @property(nonatomic, assign, getter=isLayoutDirty) BOOL layoutDirty; @property(nonatomic, weak) id observer; diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfallItem.mm b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfallItem.mm index 2fe3cd07734..a8cc58155ba 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfallItem.mm +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderObjectWaterfallItem.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -50,7 +50,7 @@ - (void)amendLayoutBeforeMount:(NSMutableSet *)blocks _layoutDirty = YES; } _propagationLifecycle = NativeRenderUpdateLifecycleComputed; - for (NativeRenderObjectView *renderObjectView in self.subcomponents) { + for (HippyShadowView *renderObjectView in self.subcomponents) { [renderObjectView amendLayoutBeforeMount:blocks]; } } diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemView.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemView.h index bd974b2c055..d528b2445e7 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemView.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,11 +21,11 @@ */ #import -#import "NativeRenderView.h" +#import "HippyView.h" NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderWaterfallItemView : NativeRenderView +@interface NativeRenderWaterfallItemView : HippyView @property (nonatomic, copy) NSString *type; diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemView.m b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemView.m index a5f95c31182..12e576a2eb2 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemView.m +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,7 +21,7 @@ */ #import "NativeRenderWaterfallItemView.h" -#import "UIView+NativeRender.h" +#import "UIView+Hippy.h" @implementation NativeRenderWaterfallItemView @@ -32,8 +32,8 @@ - (instancetype)initWithFrame:(CGRect)frame { return self; } -- (void)nativeRenderSetFrame:(CGRect)frame { - [super nativeRenderSetFrame:frame]; +- (void)hippySetFrame:(CGRect)frame { + [super hippySetFrame:frame]; self.frame = self.bounds; } diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemViewManager.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemViewManager.h index 219a9697d5f..ca2d2b92651 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemViewManager.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderWaterfallItemViewManager : NativeRenderViewManager +@interface NativeRenderWaterfallItemViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemViewManager.mm b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemViewManager.mm index bdd76a610b3..bfe847a1cb4 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemViewManager.mm +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallItemViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -26,13 +26,13 @@ @implementation NativeRenderWaterfallItemViewManager -NATIVE_RENDER_EXPORT_VIEW(WaterfallItem) +HIPPY_EXPORT_MODULE(WaterfallItem) - (UIView *)view { return [NativeRenderWaterfallItemView new]; } -- (NativeRenderObjectView *)nativeRenderObjectView { +- (HippyShadowView *)hippyShadowView { return [[NativeRenderObjectWaterfallItem alloc] init]; } diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallView.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallView.h index 3599241cf3d..5a261431397 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallView.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,14 +23,14 @@ #import #import "NativeRenderCollectionViewWaterfallLayout.h" -#import "NativeRenderComponentProtocol.h" -#import "NativeRenderScrollableProtocol.h" +#import "HippyComponent.h" +#import "HippyScrollableProtocol.h" #import "NativeRenderScrollProtocol.h" #import "NativeRenderTouchesView.h" NS_ASSUME_NONNULL_BEGIN -@class NativeRenderWaterfallViewDataSource, NativeRenderHeaderRefresh, NativeRenderFooterRefresh, WaterfallItemChangeContext, NativeRenderObjectView; +@class NativeRenderWaterfallViewDataSource, NativeRenderHeaderRefresh, NativeRenderFooterRefresh, WaterfallItemChangeContext, HippyShadowView; typedef NS_ENUM(NSInteger, NativeRenderScrollState) { ScrollStateStop, @@ -42,7 +42,7 @@ typedef NS_ENUM(NSInteger, NativeRenderScrollState) { * NativeRenderWaterfallView is a waterfall component, internal implementation is UICollectionView */ @interface NativeRenderWaterfallView : NativeRenderTouchesView { + NativeRenderCollectionViewDelegateWaterfallLayout, HippyScrollableProtocol, NativeRenderScrollProtocol> { @protected NativeRenderWaterfallViewDataSource *_dataSource; NativeRenderWaterfallViewDataSource *_previousDataSource; @@ -108,14 +108,14 @@ typedef NS_ENUM(NSInteger, NativeRenderScrollState) { @property(nonatomic, assign) BOOL manualScroll; /** - * NativeRender Events + * Hippy Events */ -@property (nonatomic, copy) NativeRenderDirectEventBlock onScroll; -@property (nonatomic, copy) NativeRenderDirectEventBlock onInitialListReady; -@property (nonatomic, copy) NativeRenderDirectEventBlock onEndReached; -@property (nonatomic, copy) NativeRenderDirectEventBlock onFooterAppeared; -@property (nonatomic, copy) NativeRenderDirectEventBlock onRefresh; -@property (nonatomic, copy) NativeRenderDirectEventBlock onExposureReport; +@property (nonatomic, copy) HippyDirectEventBlock onScroll; +@property (nonatomic, copy) HippyDirectEventBlock onInitialListReady; +@property (nonatomic, copy) HippyDirectEventBlock onEndReached; +@property (nonatomic, copy) HippyDirectEventBlock onFooterAppeared; +@property (nonatomic, copy) HippyDirectEventBlock onRefresh; +@property (nonatomic, copy) HippyDirectEventBlock onExposureReport; - (NSUInteger)maxCachedItemCount; @@ -164,8 +164,8 @@ typedef NS_ENUM(NSInteger, NativeRenderScrollState) { */ - (void)reloadData; -- (void)pushDataSource:(NSArray *)dataSource; -- (NSArray *)popDataSource; +- (void)pushDataSource:(NSArray *)dataSource; +- (NSArray *)popDataSource; /** * Reserved, not implemented diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallView.mm b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallView.mm index 2115233c64f..5e93bd257e6 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallView.mm +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallView.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -24,11 +24,11 @@ #import "NativeRenderHeaderRefresh.h" #import "NativeRenderFooterRefresh.h" #import "NativeRenderWaterfallItemView.h" -#import "UIView+NativeRender.h" -#import "NativeRenderRefresh.h" +#import "UIView+Hippy.h" +#import "HippyRefresh.h" #import "NativeRenderWaterfallViewDataSource.h" -#import "NativeRenderObjectView.h" -#import "NativeRenderImpl.h" +#import "HippyShadowView.h" +#import "HippyUIManager.h" #import "UIView+Render.h" #import "NativeRenderListTableView.h" #import "NativeRenderWaterfallViewCell.h" @@ -37,12 +37,12 @@ static NSString *kWaterfallItemName = @"WaterfallItem"; static const NSTimeInterval delayForPurgeView = 1.f; -@interface NativeRenderWaterfallView () { +@interface NativeRenderWaterfallView () { NSHashTable> *_scrollListeners; BOOL _isInitialListReady; UIColor *_backgroundColor; BOOL _manualScroll; - NSMutableArray *> *_dataSourcePool; + NSMutableArray *> *_dataSourcePool; dispatch_semaphore_t _dataSourceSem; } @@ -121,11 +121,11 @@ - (void)setScrollEventThrottle:(double)scrollEventThrottle { _scrollEventThrottle = scrollEventThrottle; } -- (void)removeNativeRenderSubview:(UIView *)subview { +- (void)removeHippySubview:(UIView *)subview { } -- (void)nativeRenderSetFrame:(CGRect)frame { - [super nativeRenderSetFrame:frame]; +- (void)hippySetFrame:(CGRect)frame { + [super hippySetFrame:frame]; _collectionView.frame = self.bounds; } @@ -163,11 +163,11 @@ - (CGSize)contentSize { - (void)zoomToRect:(CGRect)rect animated:(BOOL)animated { } -- (void)didUpdateNativeRenderSubviews { +- (void)didUpdateHippySubviews { self.dirtyContent = YES; } -- (void)nativeRenderComponentDidFinishTransaction { +- (void)hippyBridgeDidFinishTransaction { if (self.dirtyContent) { [self reloadData]; self.dirtyContent = NO; @@ -179,7 +179,7 @@ - (void)setContainBannerView:(BOOL)containBannerView { } - (void)refreshItemNodes { - NSArray *datasource = [self popDataSource]; + NSArray *datasource = [self popDataSource]; _dataSource = [[NativeRenderWaterfallViewDataSource alloc] initWithDataSource:datasource itemViewName:[self compoentItemName] containBannerView:_containBannerView]; @@ -267,7 +267,7 @@ - (void)setInterItemSpacing:(CGFloat)interItemSpacing { _layout.minimumInteritemSpacing = _interItemSpacing; } -- (void)setOnInitialListReady:(NativeRenderDirectEventBlock)onInitialListReady { +- (void)setOnInitialListReady:(HippyDirectEventBlock)onInitialListReady { _onInitialListReady = onInitialListReady; _isInitialListReady = NO; } @@ -297,21 +297,21 @@ - (void)reloadData { } } -- (void)pushDataSource:(NSArray *)dataSource { +- (void)pushDataSource:(NSArray *)dataSource { dispatch_semaphore_wait(_dataSourceSem, DISPATCH_TIME_FOREVER); [_dataSourcePool addObject:dataSource]; dispatch_semaphore_signal(_dataSourceSem); } -- (NSArray *)popDataSource { +- (NSArray *)popDataSource { dispatch_semaphore_wait(_dataSourceSem, DISPATCH_TIME_FOREVER); - NSArray *datasource = [_dataSourcePool lastObject]; + NSArray *datasource = [_dataSourcePool lastObject]; [_dataSourcePool removeLastObject]; dispatch_semaphore_signal(_dataSourceSem); return datasource; } -- (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { +- (void)insertHippySubview:(UIView *)subview atIndex:(NSInteger)atIndex { if ([subview isKindOfClass:[NativeRenderHeaderRefresh class]]) { if (_headerRefreshView) { [_headerRefreshView removeFromSuperview]; @@ -319,8 +319,8 @@ - (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { _headerRefreshView = (NativeRenderHeaderRefresh *)subview; [_headerRefreshView setScrollView:self.collectionView]; _headerRefreshView.delegate = self; - _headerRefreshView.frame = subview.nativeRenderObjectView.frame; - [_weakItemMap setObject:subview forKey:[subview componentTag]]; + _headerRefreshView.frame = subview.hippyShadowView.frame; + [_weakItemMap setObject:subview forKey:[subview hippyTag]]; } else if ([subview isKindOfClass:[NativeRenderFooterRefresh class]]) { if (_footerRefreshView) { [_footerRefreshView removeFromSuperview]; @@ -328,10 +328,10 @@ - (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { _footerRefreshView = (NativeRenderFooterRefresh *)subview; [_footerRefreshView setScrollView:self.collectionView]; _footerRefreshView.delegate = self; - _footerRefreshView.frame = subview.nativeRenderObjectView.frame; + _footerRefreshView.frame = subview.hippyShadowView.frame; UIEdgeInsets insets = self.collectionView.contentInset; self.collectionView.contentInset = UIEdgeInsetsMake(insets.top, insets.left, _footerRefreshView.frame.size.height, insets.right); - [_weakItemMap setObject:subview forKey:[subview componentTag]]; + [_weakItemMap setObject:subview forKey:[subview hippyTag]]; } } @@ -339,8 +339,8 @@ - (void)insertNativeRenderSubview:(UIView *)subview atIndex:(NSInteger)atIndex { return [[_weakItemMap dictionaryRepresentation] allValues]; } -- (void)removeFromNativeRenderSuperview { - [super removeFromNativeRenderSuperview]; +- (void)removeFromHippySuperview { + [super removeFromHippySuperview]; [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(purgeFurthestIndexPathsFromScreen) object:nil]; [self purgeFurthestIndexPathsFromScreen]; } @@ -397,7 +397,7 @@ - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:( if ([cell isKindOfClass:[NativeRenderWaterfallViewCell class]]) { NativeRenderWaterfallViewCell *hpCell = (NativeRenderWaterfallViewCell *)cell; if (hpCell.cellView) { - [_cachedItems setObject:[hpCell.cellView componentTag] forKey:indexPath]; + [_cachedItems setObject:[hpCell.cellView hippyTag] forKey:indexPath]; hpCell.cellView = nil; } } @@ -405,7 +405,7 @@ - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:( - (void)itemViewForCollectionViewCell:(UICollectionViewCell *)cell indexPath:(NSIndexPath *)indexPath { NativeRenderWaterfallViewCell *hpCell = (NativeRenderWaterfallViewCell *)cell; - NativeRenderObjectView *renderObjectView = [_dataSource cellForIndexPath:indexPath]; + HippyShadowView *renderObjectView = [_dataSource cellForIndexPath:indexPath]; [renderObjectView recusivelySetCreationTypeToInstant]; UIView *cellView = [self.renderImpl createViewRecursivelyFromRenderObject:renderObjectView]; if (cellView) { @@ -413,14 +413,14 @@ - (void)itemViewForCollectionViewCell:(UICollectionViewCell *)cell indexPath:(NS } hpCell.cellView = cellView; cellView.parentComponent = self; - [_weakItemMap setObject:cellView forKey:[cellView componentTag]]; + [_weakItemMap setObject:cellView forKey:[cellView hippyTag]]; } #pragma mark - NativeRenderCollectionViewDelegateWaterfallLayout - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { - NativeRenderObjectView *renderObjectView = [_dataSource cellForIndexPath:indexPath]; + HippyShadowView *renderObjectView = [_dataSource cellForIndexPath:indexPath]; return renderObjectView.frame.size; } @@ -652,7 +652,7 @@ - (UIView *)rootView { } UIView *view = [self superview]; while (view) { - if (0 == [[view componentTag] intValue] % 10) { + if (0 == [[view hippyTag] intValue] % 10) { _rootView = view; return view; } diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewCell.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewCell.h index 79398dc6111..9fd70b6825c 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewCell.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewCell.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewCell.m b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewCell.m index 312920c13b4..1928e20ab46 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewCell.m +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewCell.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewDataSource.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewDataSource.h index d7b64abdec1..7155e4b135a 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewDataSource.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewDataSource.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -25,25 +25,25 @@ NS_ASSUME_NONNULL_BEGIN -@class NativeRenderObjectView, WaterfallItemChangeContext; +@class HippyShadowView, WaterfallItemChangeContext; @interface NativeRenderWaterfallViewDataSource : NSObject -- (instancetype)initWithDataSource:(NSArray<__kindof NativeRenderObjectView *> *)dataSource +- (instancetype)initWithDataSource:(NSArray<__kindof HippyShadowView *> *)dataSource itemViewName:(NSString *)itemViewName containBannerView:(BOOL)containBannerView; @property(nonatomic, readonly) BOOL containBannerView; -@property(nonatomic, readonly) NativeRenderObjectView *bannerView; -@property(nonatomic, copy) NSArray *> *cellRenderObjectViews; +@property(nonatomic, readonly) HippyShadowView *bannerView; +@property(nonatomic, copy) NSArray *> *cellRenderObjectViews; @property(nonatomic, copy) NSString *itemViewName; -- (void)setDataSource:(NSArray<__kindof NativeRenderObjectView *> *)dataSource containBannerView:(BOOL)containBannerView; -- (NativeRenderObjectView *)cellForIndexPath:(NSIndexPath *)indexPath; -- (NativeRenderObjectView *)headerForSection:(NSInteger)section; +- (void)setDataSource:(NSArray<__kindof HippyShadowView *> *)dataSource containBannerView:(BOOL)containBannerView; +- (HippyShadowView *)cellForIndexPath:(NSIndexPath *)indexPath; +- (HippyShadowView *)headerForSection:(NSInteger)section; - (NSInteger)numberOfSection; - (NSInteger)numberOfCellForSection:(NSInteger)section; -- (NSIndexPath *)indexPathOfCell:(NativeRenderObjectView *)cell; +- (NSIndexPath *)indexPathOfCell:(HippyShadowView *)cell; - (NSIndexPath *)indexPathForFlatIndex:(NSInteger)index; - (NSInteger)flatIndexForIndexPath:(NSIndexPath *)indexPath; @@ -54,7 +54,7 @@ NS_ASSUME_NONNULL_BEGIN - (void)cellDiffFromAnother:(NativeRenderWaterfallViewDataSource *)another sectionStartAt:(NSUInteger)startSection - frameChangedItems:(NSHashTable<__kindof NativeRenderObjectView *> *)frameChangedItems + frameChangedItems:(NSHashTable<__kindof HippyShadowView *> *)frameChangedItems result:(void(^)(NSArray *reloadedItemIndexPath, NSArray *InsertedIndexPath, NSArray *deletedIndexPath, diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewDataSource.mm b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewDataSource.mm index 7280e50be83..99dbc3a6745 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewDataSource.mm +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewDataSource.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -22,22 +22,22 @@ #import -#import "HPAsserts.h" +#import "HippyAsserts.h" #import "NativeRenderWaterfallViewDataSource.h" -#import "NativeRenderObjectView.h" +#import "HippyShadowView.h" #import "NativeRenderObjectWaterfall.h" @interface NativeRenderWaterfallViewDataSource () { BOOL _containBannerView; - NSArray *> *_cellRenderObjectViews; - NativeRenderObjectView *_bannerView; + NSArray *> *_cellRenderObjectViews; + HippyShadowView *_bannerView; } @end @implementation NativeRenderWaterfallViewDataSource -- (instancetype)initWithDataSource:(NSArray<__kindof NativeRenderObjectView *> *)dataSource +- (instancetype)initWithDataSource:(NSArray<__kindof HippyShadowView *> *)dataSource itemViewName:(NSString *)itemViewName containBannerView:(BOOL)containBannerView { self = [super init]; @@ -52,9 +52,9 @@ - (id)copyWithZone:(nullable NSZone *)zone { NativeRenderWaterfallViewDataSource *dataSource = [[[self class] allocWithZone:zone] init]; dataSource->_containBannerView = self.containBannerView; dataSource->_bannerView = _bannerView; - NSMutableArray *> *objectSectionViews = [NSMutableArray arrayWithCapacity:[_cellRenderObjectViews count]]; - for (NSArray *objects in _cellRenderObjectViews) { - NSArray *copiedObjects = [objects copy]; + NSMutableArray *> *objectSectionViews = [NSMutableArray arrayWithCapacity:[_cellRenderObjectViews count]]; + for (NSArray *objects in _cellRenderObjectViews) { + NSArray *copiedObjects = [objects copy]; [objectSectionViews addObject:copiedObjects]; } dataSource->_cellRenderObjectViews = [objectSectionViews copy]; @@ -62,11 +62,11 @@ - (id)copyWithZone:(nullable NSZone *)zone { return dataSource; } -- (void)setDataSource:(NSArray *)dataSource { +- (void)setDataSource:(NSArray *)dataSource { [self setDataSource:dataSource containBannerView:NO]; } -- (void)setDataSource:(NSArray *)dataSource +- (void)setDataSource:(NSArray *)dataSource containBannerView:(BOOL)containBannerView { _containBannerView = containBannerView; if ([dataSource count] > 0) { @@ -74,20 +74,20 @@ - (void)setDataSource:(NSArray *)dataSource _bannerView = [dataSource firstObject]; } NSUInteger loc = _containBannerView ? 1 : 0; - NSArray *candidateRenderObjectViews = [dataSource subarrayWithRange:NSMakeRange(loc, [dataSource count] - loc)]; + NSArray *candidateRenderObjectViews = [dataSource subarrayWithRange:NSMakeRange(loc, [dataSource count] - loc)]; NSString *viewName = self.itemViewName; static dispatch_once_t onceToken; static NSPredicate *prediate = nil; dispatch_once(&onceToken, ^{ prediate = [NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary * _Nullable bindings) { - NativeRenderObjectView *renderObjectView = (NativeRenderObjectView *)evaluatedObject; + HippyShadowView *renderObjectView = (HippyShadowView *)evaluatedObject; if ([renderObjectView.viewName isEqualToString:viewName]) { return YES; } return NO; }]; }); - NSArray *objects = [candidateRenderObjectViews filteredArrayUsingPredicate:prediate]; + NSArray *objects = [candidateRenderObjectViews filteredArrayUsingPredicate:prediate]; if ([objects count]) { _cellRenderObjectViews = [NSArray arrayWithObject:objects]; } @@ -97,15 +97,15 @@ - (void)setDataSource:(NSArray *)dataSource } } --(NativeRenderObjectView *)bannerView { +-(HippyShadowView *)bannerView { return _bannerView; } -- (NSArray *> *)cellRenderObjectViews { +- (NSArray *> *)cellRenderObjectViews { return [_cellRenderObjectViews copy]; } -- (NativeRenderObjectView *)cellForIndexPath:(NSIndexPath *)indexPath { +- (HippyShadowView *)cellForIndexPath:(NSIndexPath *)indexPath { if (_containBannerView && 0 == [indexPath section]) { return _bannerView; } @@ -114,7 +114,7 @@ - (NativeRenderObjectView *)cellForIndexPath:(NSIndexPath *)indexPath { } } -- (NativeRenderObjectView *)headerForSection:(NSInteger)section { +- (HippyShadowView *)headerForSection:(NSInteger)section { return nil; } @@ -133,7 +133,7 @@ - (NSInteger)numberOfCellForSection:(NSInteger)section { } } -- (NSIndexPath *)indexPathOfCell:(NativeRenderObjectView *)cell { +- (NSIndexPath *)indexPathOfCell:(HippyShadowView *)cell { NSInteger row = 0; NSInteger section = 0; if (_containBannerView) { @@ -178,9 +178,9 @@ - (NSInteger)flatIndexForIndexPath:(NSIndexPath *)indexPath { return index; } -static BOOL ObjectViewNeedReload(NativeRenderObjectView *object1, - NativeRenderObjectView *object2, - NSHashTable<__kindof NativeRenderObjectView *> *frameChangedItems) { +static BOOL ObjectViewNeedReload(HippyShadowView *object1, + HippyShadowView *object2, + NSHashTable<__kindof HippyShadowView *> *frameChangedItems) { if (object1 != object2) { return YES; } @@ -190,9 +190,9 @@ static BOOL ObjectViewNeedReload(NativeRenderObjectView *object1, return NO; } -static void ObjectsArrayDiff(NSArray *objects1, - NSArray *objects2, - NSHashTable<__kindof NativeRenderObjectView *> *frameChangedItems, +static void ObjectsArrayDiff(NSArray *objects1, + NSArray *objects2, + NSHashTable<__kindof HippyShadowView *> *frameChangedItems, void(^result)(NSIndexSet *reloadIndex, NSIndexSet *insertedIndex, NSIndexSet *deletedIndex)) { NSMutableIndexSet *reloadIndex = [NSMutableIndexSet indexSet]; NSMutableIndexSet *insertedIndex = [NSMutableIndexSet indexSet]; @@ -202,8 +202,8 @@ static void ObjectsArrayDiff(NSArray *objects1, NSEnumerator *obj2Enumer = [objects2 objectEnumerator]; NSUInteger index = 0; do { - NativeRenderObjectView *object1 = [obj1Enumer nextObject]; - NativeRenderObjectView *object2 = [obj2Enumer nextObject]; + HippyShadowView *object1 = [obj1Enumer nextObject]; + HippyShadowView *object2 = [obj2Enumer nextObject]; if (object1 && object2) { if (ObjectViewNeedReload(object1, object2, frameChangedItems)) { [reloadIndex addIndex:index]; @@ -232,7 +232,7 @@ static void ObjectsArrayDiff(NSArray *objects1, } NSUInteger indexBuffer[[indexSet count]]; NSUInteger resultCount = [indexSet getIndexes:indexBuffer maxCount:[indexSet count] inIndexRange:nil]; - HPAssert(resultCount == [indexSet count], @"Should get all index from indexset"); + HippyAssert(resultCount == [indexSet count], @"Should get all index from indexset"); NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:resultCount]; for (NSUInteger i = 0; i < resultCount; i++) { NSUInteger index = indexBuffer[i]; @@ -244,7 +244,7 @@ static void ObjectsArrayDiff(NSArray *objects1, - (void)cellDiffFromAnother:(NativeRenderWaterfallViewDataSource *)another sectionStartAt:(NSUInteger)startSection - frameChangedItems:(NSHashTable<__kindof NativeRenderObjectView *> *)frameChangedItems + frameChangedItems:(NSHashTable<__kindof HippyShadowView *> *)frameChangedItems result:(void(^)(NSArray *reloadedItemIndexPath, NSArray *InsertedIndexPath, NSArray *deletedIndexPath, @@ -256,16 +256,16 @@ - (void)cellDiffFromAnother:(NativeRenderWaterfallViewDataSource *)another NSMutableIndexSet *insertedSecionIndexSet = [NSMutableIndexSet indexSet]; NSMutableIndexSet *deletedSectionIndexSet = [NSMutableIndexSet indexSet]; - NSArray *> *currenCellObjects = self.cellRenderObjectViews; - NSArray *> *anotherCellObjects = another.cellRenderObjectViews; + NSArray *> *currenCellObjects = self.cellRenderObjectViews; + NSArray *> *anotherCellObjects = another.cellRenderObjectViews; //compare sections //sections number equal, NSEnumerator *obj1Enumer = [currenCellObjects objectEnumerator]; NSEnumerator *obj2Enumer = [anotherCellObjects objectEnumerator]; NSUInteger section = startSection; do { - NSArray *objects1 = [obj1Enumer nextObject]; - NSArray *objects2 = [obj2Enumer nextObject]; + NSArray *objects1 = [obj1Enumer nextObject]; + NSArray *objects2 = [obj2Enumer nextObject]; if (objects1 && objects2) { ObjectsArrayDiff(objects1, objects2, frameChangedItems, ^(NSIndexSet *reloadIndex, NSIndexSet *insertedIndex, NSIndexSet *deletedIndex) { NSArray *reloadIndics = IndexPathForIndexSet(section, reloadIndex); @@ -367,20 +367,19 @@ - (void)applyDiff:(NativeRenderWaterfallViewDataSource *)another }]; BOOL success = YES; if ([batchUpdate count]) { - [UIView setAnimationsEnabled:NO]; + [CATransaction begin]; + [CATransaction setDisableActions:YES]; @try { [view performBatchUpdates:^{ for (NSInvocation *invocation in batchUpdate) { [invocation invoke]; } - } completion:^(BOOL finished) { - [UIView setAnimationsEnabled:YES]; - }]; + } completion:nil]; } @catch (NSException *exception) { - success = NO; [view reloadData]; - [UIView setAnimationsEnabled:YES]; + success = NO; } + [CATransaction commit]; } completion(success); } @@ -439,7 +438,7 @@ static NSComparisonResult ContainViewComparison(NativeRenderWaterfallViewDataSou context:(WaterfallItemChangeContext *)context forCollectionView:(UICollectionView *)collectionView { //todo 计算太麻烦了,先直接reload all吧 - NSHashTable<__kindof NativeRenderObjectView *> *movedItems = [context movedItems]; + NSHashTable<__kindof HippyShadowView *> *movedItems = [context movedItems]; if ([movedItems count]) { NSInvocation *invocation = InvocationFromSelector(collectionView, @selector(reloadData), nil); @@ -453,8 +452,8 @@ static NSComparisonResult ContainViewComparison(NativeRenderWaterfallViewDataSou NSIndexSet *cellSectionIndexSet = [NSIndexSet indexSetWithIndex:self.containBannerView ? 1 : 0]; if ([[self.cellRenderObjectViews firstObject] count] && [[another.cellRenderObjectViews firstObject] count]) { //get inserted items - NSHashTable<__kindof NativeRenderObjectView *> *addedItems = [context addedItems]; - NSIndexSet *insertedItemsIndexSet = [[self.cellRenderObjectViews firstObject] indexesOfObjectsPassingTest:^BOOL(NativeRenderObjectView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { + NSHashTable<__kindof HippyShadowView *> *addedItems = [context addedItems]; + NSIndexSet *insertedItemsIndexSet = [[self.cellRenderObjectViews firstObject] indexesOfObjectsPassingTest:^BOOL(HippyShadowView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { if ([addedItems containsObject:obj]) { return YES; } @@ -473,10 +472,10 @@ static NSComparisonResult ContainViewComparison(NativeRenderWaterfallViewDataSou [invocations addObject:invocation]; } //get deleteed items - NSSet<__kindof NativeRenderObjectView *> *deletedItems = [context deletedItems]; + NSSet<__kindof HippyShadowView *> *deletedItems = [context deletedItems]; if ([deletedItems count]) { NSMutableIndexSet *deletedItemsIndexSet = [NSMutableIndexSet indexSet]; - [deletedItems enumerateObjectsUsingBlock:^(__kindof NativeRenderObjectView * _Nonnull obj, BOOL * _Nonnull stop) { + [deletedItems enumerateObjectsUsingBlock:^(__kindof HippyShadowView * _Nonnull obj, BOOL * _Nonnull stop) { NSUInteger index = [[[another cellRenderObjectViews]firstObject] indexOfObject:obj]; if (NSNotFound != index) { [deletedItemsIndexSet addIndex:index]; @@ -496,11 +495,11 @@ static NSComparisonResult ContainViewComparison(NativeRenderWaterfallViewDataSou } } //get frame update items - NSHashTable<__kindof NativeRenderObjectView *> *frameChangedItems = [context frameChangedItems]; + NSHashTable<__kindof HippyShadowView *> *frameChangedItems = [context frameChangedItems]; if ([frameChangedItems count]) { NSMutableArray *frameChangedIndexPaths = [NSMutableArray arrayWithCapacity:[frameChangedItems count]]; NSEnumerator *enumerator = [frameChangedItems objectEnumerator]; - NativeRenderObjectView *objectView = [enumerator nextObject]; + HippyShadowView *objectView = [enumerator nextObject]; while (objectView) { NSUInteger index = [[self.cellRenderObjectViews firstObject] indexOfObject:objectView]; if (NSNotFound != index) { diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewManager.h b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewManager.h index 0036e2a6a59..65892cc2e2c 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewManager.h +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderWaterfallViewManager : NativeRenderViewManager +@interface NativeRenderWaterfallViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewManager.mm b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewManager.mm index b2a216e2f23..200f087feb6 100644 --- a/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewManager.mm +++ b/renderer/native/ios/renderer/component/waterfalllist/NativeRenderWaterfallViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,126 +23,126 @@ #import "NativeRenderWaterfallViewManager.h" #import "NativeRenderWaterfallView.h" #import "NativeRenderObjectWaterfall.h" -#import "NativeRenderImpl.h" +#import "HippyUIManager.h" @implementation NativeRenderWaterfallViewManager -NATIVE_RENDER_EXPORT_VIEW(WaterfallView) +HIPPY_EXPORT_MODULE(WaterfallView) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(contentInset, UIEdgeInsets) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(numberOfColumns, NSInteger) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(preloadItemNumber, NSInteger) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(columnSpacing, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(interItemSpacing, CGFloat) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onInitialListReady, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onEndReached, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onFooterAppeared, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onRefresh, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onExposureReport, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(containBannerView, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(containPullHeader, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(containPullFooter, BOOL) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(scrollEventThrottle, double) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onScroll, NativeRenderDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(contentInset, UIEdgeInsets) +HIPPY_EXPORT_VIEW_PROPERTY(numberOfColumns, NSInteger) +HIPPY_EXPORT_VIEW_PROPERTY(preloadItemNumber, NSInteger) +HIPPY_EXPORT_VIEW_PROPERTY(columnSpacing, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(interItemSpacing, CGFloat) +HIPPY_EXPORT_VIEW_PROPERTY(onInitialListReady, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onEndReached, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onFooterAppeared, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onRefresh, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onExposureReport, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(containBannerView, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(containPullHeader, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(containPullFooter, BOOL) +HIPPY_EXPORT_VIEW_PROPERTY(scrollEventThrottle, double) +HIPPY_EXPORT_VIEW_PROPERTY(onScroll, HippyDirectEventBlock) - (UIView *)view { return [[NativeRenderWaterfallView alloc] init]; } -- (NativeRenderObjectView *)nativeRenderObjectView { +- (HippyShadowView *)hippyShadowView { return [[NativeRenderObjectWaterfall alloc] init]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(refreshCompleted:(nonnull NSNumber *)reactTag +HIPPY_EXPORT_METHOD(refreshCompleted:(nonnull NSNumber *)reactTag status:(nonnull NSNumber *)status text:(nonnull NSString *)text duration:(nonnull NSNumber *)duration imageUrl:(nonnull NSString *)imageUrl) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)viewRegistry[reactTag]; if (view == nil) return; if (![view isKindOfClass:[NativeRenderWaterfallView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); } [view refreshCompleted:status.integerValue text:text]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(startRefresh:(nonnull NSNumber *)reactTag) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(startRefresh:(nonnull NSNumber *)reactTag) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)viewRegistry[reactTag]; if (view == nil) return; if (![view isKindOfClass:[NativeRenderWaterfallView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); } [view startRefreshFromJS]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(startRefreshWithType:(nonnull NSNumber *)reactTag +HIPPY_EXPORT_METHOD(startRefreshWithType:(nonnull NSNumber *)reactTag type:(NSNumber *)type) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)viewRegistry[reactTag]; if (view == nil) return; if (![view isKindOfClass:[NativeRenderWaterfallView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); } [view startRefreshFromJSWithType:[type unsignedIntegerValue]]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(callExposureReport:(nonnull NSNumber *)reactTag) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(callExposureReport:(nonnull NSNumber *)reactTag) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)viewRegistry[reactTag]; if (view == nil) return; if (![view isKindOfClass:[NativeRenderWaterfallView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); } [view callExposureReport]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(scrollToIndex:(nonnull NSNumber *)reactTag +HIPPY_EXPORT_METHOD(scrollToIndex:(nonnull NSNumber *)reactTag xIndex:(nonnull NSNumber *)xIndex yIndex:(nonnull NSNumber *)yIndex animation:(nonnull NSNumber *)animation) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)viewRegistry[reactTag]; if (view == nil) return; if (![view isKindOfClass:[NativeRenderWaterfallView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); } [view scrollToIndex:xIndex.integerValue animated:[animation boolValue]]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(scrollToContentOffset:(nonnull NSNumber *)reactTag +HIPPY_EXPORT_METHOD(scrollToContentOffset:(nonnull NSNumber *)reactTag x:(nonnull NSNumber *)x y:(nonnull NSNumber *)y animation:(nonnull NSNumber *)animation) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)viewRegistry[reactTag]; if (view == nil) return; if (![view isKindOfClass:[NativeRenderWaterfallView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); } [view scrollToOffset:CGPointMake([x floatValue], [y floatValue]) animated:[animation boolValue]]; }]; } -NATIVE_RENDER_COMPONENT_EXPORT_METHOD(startLoadMore:(nonnull NSNumber *)reactTag) { - [self.renderImpl addUIBlock:^(__unused NativeRenderImpl *renderContext, NSDictionary *viewRegistry) { +HIPPY_EXPORT_METHOD(startLoadMore:(nonnull NSNumber *)reactTag) { + [self.bridge.uiManager addUIBlock:^(__unused HippyUIManager *uiManager, NSDictionary *viewRegistry) { NativeRenderWaterfallView *view = (NativeRenderWaterfallView *)viewRegistry[reactTag]; if (view == nil) return; if (![view isKindOfClass:[NativeRenderWaterfallView class]]) { - HPLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); + HippyLogError(@"Invalid view returned from registry, expecting NativeRenderWaterfallView, got: %@", view); } [view startLoadMore]; }]; diff --git a/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebView.h b/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebView.h index 1cff478332e..4229d821227 100644 --- a/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebView.h +++ b/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebView.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,16 +21,16 @@ */ #import -#import "NativeRenderComponentProtocol.h" +#import "HippyComponent.h" NS_ASSUME_NONNULL_BEGIN @interface NativeRenderSimpleWebView : WKWebView @property (nonatomic, strong) NSString *url; @property (nonatomic, strong) NSDictionary *source; -@property (nonatomic, copy) NativeRenderDirectEventBlock onLoadStart; -@property (nonatomic, copy) NativeRenderDirectEventBlock onLoadEnd; -@property (nonatomic, copy) NativeRenderDirectEventBlock onLoad; +@property (nonatomic, copy) HippyDirectEventBlock onLoadStart; +@property (nonatomic, copy) HippyDirectEventBlock onLoadEnd; +@property (nonatomic, copy) HippyDirectEventBlock onLoad; @end diff --git a/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebView.m b/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebView.m index 755a06781e7..25f864bdff9 100644 --- a/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebView.m +++ b/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebView.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,7 +21,7 @@ */ #import "NativeRenderSimpleWebView.h" -#import "HPToolUtils.h" +#import "HippyUtils.h" @implementation NativeRenderSimpleWebView @@ -44,7 +44,7 @@ - (void)setSource:(NSDictionary *)source { - (void)loadUrl:(NSString *)urlString { _url = urlString; - NSURL *url = HPURLWithString(urlString, NULL); + NSURL *url = HippyURLWithString(urlString, NULL); if (!url) { return; } diff --git a/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebViewManager.h b/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebViewManager.h index fe331746e4e..99624461457 100644 --- a/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebViewManager.h +++ b/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebViewManager.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,12 +20,12 @@ * limitations under the License. */ -#import "NativeRenderViewManager.h" +#import "HippyViewManager.h" #import "NativeRenderSimpleWebView.h" NS_ASSUME_NONNULL_BEGIN -@interface NativeRenderSimpleWebViewManager : NativeRenderViewManager +@interface NativeRenderSimpleWebViewManager : HippyViewManager @end diff --git a/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebViewManager.mm b/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebViewManager.mm index 4f5cec1d966..b9ea67249f9 100644 --- a/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebViewManager.mm +++ b/renderer/native/ios/renderer/component/webview/NativeRenderSimpleWebViewManager.mm @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -24,12 +24,12 @@ @implementation NativeRenderSimpleWebViewManager -NATIVE_RENDER_EXPORT_VIEW(WebView) +HIPPY_EXPORT_MODULE(WebView) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(source, NSDictionary) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onLoadStart, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onLoadEnd, NativeRenderDirectEventBlock) -NATIVE_RENDER_EXPORT_VIEW_PROPERTY(onLoad, NativeRenderDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(source, NSDictionary) +HIPPY_EXPORT_VIEW_PROPERTY(onLoadStart, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onLoadEnd, HippyDirectEventBlock) +HIPPY_EXPORT_VIEW_PROPERTY(onLoad, HippyDirectEventBlock) - (UIView *)view { return [NativeRenderSimpleWebView new]; diff --git a/renderer/native/ios/utils/HPConvert+NativeRender.h b/renderer/native/ios/utils/HippyConvert+NativeRender.h similarity index 90% rename from renderer/native/ios/utils/HPConvert+NativeRender.h rename to renderer/native/ios/utils/HippyConvert+NativeRender.h index f07eb3dc1aa..1cca8b3a692 100644 --- a/renderer/native/ios/utils/HPConvert+NativeRender.h +++ b/renderer/native/ios/utils/HippyConvert+NativeRender.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,11 +20,11 @@ * limitations under the License. */ -#import "HPConvert.h" +#import "HippyConvert.h" NS_ASSUME_NONNULL_BEGIN -@interface HPConvert (Transform) +@interface HippyConvert (Transform) + (CATransform3D)CATransform3D:(id)json; + (CGFloat)convertToRadians:(id)json; @@ -41,7 +41,7 @@ typedef NS_ENUM(NSInteger, NativeRenderAnimationType) { NativeRenderAnimationTypeKeyboard, }; -@interface HPConvert (NativeRenderAnimationType) +@interface HippyConvert (NativeRenderAnimationType) + (NativeRenderAnimationType)NativeRenderAnimationType:(id)json; @@ -54,7 +54,7 @@ typedef NS_ENUM(NSInteger, NativeRenderPointerEvents) { NativeRenderPointerEventsBoxOnly, }; -@interface HPConvert (NativeRenderPointerEvents) +@interface HippyConvert (NativeRenderPointerEvents) + (NativeRenderPointerEvents)NativeRenderPointerEvents:(id)json; @@ -67,7 +67,7 @@ typedef NS_ENUM(NSInteger, NativeRenderBorderStyle) { NativeRenderBorderStyleNone, }; -@interface HPConvert (NativeRenderBorderStyle) +@interface HippyConvert (NativeRenderBorderStyle) + (NativeRenderBorderStyle)NativeRenderBorderStyle:(id)json; @@ -92,7 +92,7 @@ typedef NS_ENUM(NSInteger, NativeRenderTextVerticalAlignType) { NativeRenderTextVerticalAlignTop = 4, }; -@interface HPConvert (NativeRenderTextEnumDefines) +@interface HippyConvert (NativeRenderTextEnumDefines) + (NativeRenderTextDecorationLineType)NativeRenderTextDecorationLineType:(id)json; diff --git a/renderer/native/ios/utils/HPConvert+NativeRender.m b/renderer/native/ios/utils/HippyConvert+NativeRender.m similarity index 83% rename from renderer/native/ios/utils/HPConvert+NativeRender.m rename to renderer/native/ios/utils/HippyConvert+NativeRender.m index 115e21ce24d..4b1f3514cd4 100644 --- a/renderer/native/ios/utils/HPConvert+NativeRender.m +++ b/renderer/native/ios/utils/HippyConvert+NativeRender.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,10 +20,10 @@ * limitations under the License. */ -#import "HPConvert+NativeRender.h" -#import "HPToolUtils.h" +#import "HippyConvert+NativeRender.h" +#import "HippyUtils.h" -@implementation HPConvert (Transform) +@implementation HippyConvert (Transform) static const NSUInteger kMatrixArrayLength = 4 * 4; @@ -51,15 +51,15 @@ + (CATransform3D)CATransform3DFromMatrix:(id)json { return transform; } if (![json isKindOfClass:[NSArray class]]) { - HPLogError(@"[%@], a CATransform3D. Expected array for transform matrix.", json); + HippyLogError(@"[%@], a CATransform3D. Expected array for transform matrix.", json); return transform; } if ([json count] != kMatrixArrayLength) { - HPLogError(@"[%@], a CATransform3D. Expected 4x4 matrix array.", json); + HippyLogError(@"[%@], a CATransform3D. Expected 4x4 matrix array.", json); return transform; } for (NSUInteger i = 0; i < kMatrixArrayLength; i++) { - ((CGFloat *)&transform)[i] = [HPConvert CGFloat:json[i]]; + ((CGFloat *)&transform)[i] = [HippyConvert CGFloat:json[i]]; } return transform; } @@ -71,13 +71,13 @@ + (CATransform3D)CATransform3D:(id)json { return transform; } if (![json isKindOfClass:[NSArray class]]) { - HPLogError(@"[%@],a CATransform3D. Did you pass something other than an array?", json); + HippyLogError(@"[%@],a CATransform3D. Did you pass something other than an array?", json); return transform; } // legacy matrix support if ([(NSArray *)json count] == kMatrixArrayLength && [json[0] isKindOfClass:[NSNumber class]]) { - HPLogWarn( - @"[HPConvert CATransform3D:] has deprecated a matrix as input. Pass an array of configs (which can contain a matrix key) instead."); + HippyLogWarn( + @"[HippyConvert CATransform3D:] has deprecated a matrix as input. Pass an array of configs (which can contain a matrix key) instead."); return [self CATransform3DFromMatrix:json]; } @@ -85,11 +85,11 @@ + (CATransform3D)CATransform3D:(id)json { for (NSDictionary *transformConfig in (NSArray *)json) { if (transformConfig.count != 1) { - HPLogError(@"[%@], a CATransform3D. You must specify exactly one property per transform object.", json); + HippyLogError(@"[%@], a CATransform3D. You must specify exactly one property per transform object.", json); return transform; } NSString *property = transformConfig.allKeys[0]; - id value = HPNilIfNull(transformConfig[property]); + id value = HippyNilIfNull(transformConfig[property]); if ([property isEqualToString:@"matrix"]) { transform = [self CATransform3DFromMatrix:value]; @@ -127,9 +127,9 @@ + (CATransform3D)CATransform3D:(id)json { } else if ([property isEqualToString:@"translate"]) { NSArray *array = (NSArray *)value; - CGFloat translateX = [HPNilIfNull(array[0]) floatValue]; - CGFloat translateY = [HPNilIfNull(array[1]) floatValue]; - CGFloat translateZ = array.count > 2 ? [HPNilIfNull(array[2]) floatValue] : 0; + CGFloat translateX = [HippyNilIfNull(array[0]) floatValue]; + CGFloat translateY = [HippyNilIfNull(array[1]) floatValue]; + CGFloat translateZ = array.count > 2 ? [HippyNilIfNull(array[2]) floatValue] : 0; transform = CATransform3DTranslate(transform, translateX, translateY, translateZ); } else if ([property isEqualToString:@"translateX"]) { @@ -153,7 +153,7 @@ + (CATransform3D)CATransform3D:(id)json { transform.m12 = tanf(skew); } else { - HPLogError(@"Unsupported transform type for a CATransform3D: %@.", property); + HippyLogError(@"Unsupported transform type for a CATransform3D: %@.", property); } } return transform; @@ -161,7 +161,7 @@ + (CATransform3D)CATransform3D:(id)json { @end -@implementation HPConvert (NativeRenderAnimationType) +@implementation HippyConvert (NativeRenderAnimationType) HP_ENUM_CONVERTER(NativeRenderAnimationType, (@{ @"spring": @(NativeRenderAnimationTypeSpring), @@ -175,7 +175,7 @@ @implementation HPConvert (NativeRenderAnimationType) @end -@implementation HPConvert (NativeRenderPointerEvents) +@implementation HippyConvert (NativeRenderPointerEvents) HP_ENUM_CONVERTER(NativeRenderPointerEvents, (@{ @"none": @(NativeRenderPointerEventsNone), @@ -187,7 +187,7 @@ @implementation HPConvert (NativeRenderPointerEvents) @end -@implementation HPConvert (NativeRenderBorderStyle) +@implementation HippyConvert (NativeRenderBorderStyle) HP_ENUM_CONVERTER(NativeRenderBorderStyle, (@{ @"solid": @(NativeRenderBorderStyleSolid), @@ -199,7 +199,7 @@ @implementation HPConvert (NativeRenderBorderStyle) @end -@implementation HPConvert (NativeRenderTextEnumDefines) +@implementation HippyConvert (NativeRenderTextEnumDefines) HP_ENUM_CONVERTER(NativeRenderTextDecorationLineType, (@{ @"none": @(NativeRenderTextDecorationLineTypeNone), diff --git a/renderer/native/ios/utils/NativeRenderGradientObject.h b/renderer/native/ios/utils/NativeRenderGradientObject.h index 1a8b6f93647..2a5b085bc3c 100644 --- a/renderer/native/ios/utils/NativeRenderGradientObject.h +++ b/renderer/native/ios/utils/NativeRenderGradientObject.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -23,7 +23,7 @@ #import #import #import -#import "NativeRenderBorderDrawing.h" +#import "HippyBorderDrawing.h" NS_ASSUME_NONNULL_BEGIN @@ -86,7 +86,7 @@ typedef struct _CanvasInfo { @end -HP_EXTERN void NativeRenderDrawLinearGradientInContext(NativeRenderGradientObject *object, CGContextRef context, CanvasInfo canvasInfo); -HP_EXTERN void NativeRenderDrawRadialGradientInContext(NativeRenderGradientObject *object, CGContextRef context, CGSize); +HIPPY_EXTERN void NativeRenderDrawLinearGradientInContext(NativeRenderGradientObject *object, CGContextRef context, CanvasInfo canvasInfo); +HIPPY_EXTERN void NativeRenderDrawRadialGradientInContext(NativeRenderGradientObject *object, CGContextRef context, CGSize); NS_ASSUME_NONNULL_END diff --git a/renderer/native/ios/utils/NativeRenderGradientObject.m b/renderer/native/ios/utils/NativeRenderGradientObject.m index 5f98262bbfd..6bd8dd357dc 100644 --- a/renderer/native/ios/utils/NativeRenderGradientObject.m +++ b/renderer/native/ios/utils/NativeRenderGradientObject.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,9 +20,9 @@ * limitations under the License. */ -#import "HPAsserts.h" -#import "HPToolUtils.h" -#import "NativeRenderBorderDrawing.h" +#import "HippyAsserts.h" +#import "HippyUtils.h" +#import "HippyBorderDrawing.h" #import "NativeRenderGradientObject.h" @interface NativeRenderGradientLocationParser () { @@ -273,7 +273,7 @@ - (instancetype)initWithGradientObject:(NSDictionary *)object { for (NSUInteger i = 0; i < [colorStopList count]; i++) { NSDictionary *colorStop = [colorStopList objectAtIndex:i]; NSNumber *colorNumber = [colorStop objectForKey:@"color"]; - UIColor *color = HPConvertNumberToColor([colorNumber integerValue]); + UIColor *color = HippyConvertNumberToColor([colorNumber integerValue]); [colors addObject:color]; NSNumber *stop = [colorStop objectForKey:@"ratio"]; if (stop) { @@ -284,8 +284,8 @@ - (instancetype)initWithGradientObject:(NSDictionary *)object { self.locations = [locationParser computeLocations]; } @catch (NSException *exception) { NSString *errorString = [NSString stringWithFormat:@"gradient parse error:%@", [exception reason]]; - NSError *error = HPErrorWithMessageAndModuleName(errorString, nil); - HPFatal(error, nil); + NSError *error = HippyErrorWithMessageAndModuleName(errorString, nil); + HippyFatal(error); return self; } } @@ -355,7 +355,7 @@ void NativeRenderDrawLinearGradientInContext(NativeRenderGradientObject *object, CGContextRestoreGState(context); } -HP_EXTERN void NativeRenderDrawRadialGradientInContext(NativeRenderGradientObject *object, CGContextRef context, CGSize size) { +HIPPY_EXTERN void NativeRenderDrawRadialGradientInContext(NativeRenderGradientObject *object, CGContextRef context, CGSize size) { NSCAssert(context, @"context cannot be null for drawing radial gradient"); NSCAssert(NO, @"NativeRenderDrawRadialGradientInContext not implemented"); } diff --git a/renderer/native/ios/utils/NativeRenderUtils.h b/renderer/native/ios/utils/NativeRenderUtils.h index 3c6270151fe..fc85ede6517 100644 --- a/renderer/native/ios/utils/NativeRenderUtils.h +++ b/renderer/native/ios/utils/NativeRenderUtils.h @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -21,27 +21,26 @@ */ #import - -#import "MacroDefines.h" +#import "HippyDefines.h" NS_ASSUME_NONNULL_BEGIN // Get screen metrics in a thread-safe way -HP_EXTERN CGFloat NativeRenderScreenScale(void); -HP_EXTERN CGSize NativeRenderScreenSize(void); +HIPPY_EXTERN CGFloat NativeRenderScreenScale(void); +HIPPY_EXTERN CGSize NativeRenderScreenSize(void); // Round float coordinates to nearest whole screen pixel (not point) -HP_EXTERN CGFloat NativeRenderRoundPixelValue(CGFloat value); -HP_EXTERN CGFloat NativeRenderCeilPixelValue(CGFloat value); -HP_EXTERN CGFloat NativeRenderFloorPixelValue(CGFloat value); +HIPPY_EXTERN CGFloat NativeRenderRoundPixelValue(CGFloat value); +HIPPY_EXTERN CGFloat NativeRenderCeilPixelValue(CGFloat value); +HIPPY_EXTERN CGFloat NativeRenderFloorPixelValue(CGFloat value); // Convert a size in points to pixels, rounded up to the nearest integral size -HP_EXTERN CGSize NativeRenderSizeInPixels(CGSize pointSize, CGFloat scale); +HIPPY_EXTERN CGSize NativeRenderSizeInPixels(CGSize pointSize, CGFloat scale); -HP_EXTERN BOOL NativeRenderCGRectNearlyEqual(CGRect frame1, CGRect frame2); +HIPPY_EXTERN BOOL NativeRenderCGRectNearlyEqual(CGRect frame1, CGRect frame2); -HP_EXTERN BOOL NativeRenderCGPointNearlyEqual(CGPoint point1, CGPoint point2); +HIPPY_EXTERN BOOL NativeRenderCGPointNearlyEqual(CGPoint point1, CGPoint point2); -HP_EXTERN BOOL NativeRenderCGSizeNearlyEqual(CGSize size1, CGSize size2); +HIPPY_EXTERN BOOL NativeRenderCGSizeNearlyEqual(CGSize size1, CGSize size2); NS_ASSUME_NONNULL_END diff --git a/renderer/native/ios/utils/NativeRenderUtils.m b/renderer/native/ios/utils/NativeRenderUtils.m index e98f12f7706..577931e611f 100644 --- a/renderer/native/ios/utils/NativeRenderUtils.m +++ b/renderer/native/ios/utils/NativeRenderUtils.m @@ -2,7 +2,7 @@ * iOS SDK * * Tencent is pleased to support the open source community by making - * NativeRender available. + * Hippy available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. * All rights reserved. @@ -20,7 +20,7 @@ * limitations under the License. */ -#import "HPToolUtils.h" +#import "HippyUtils.h" #import "NativeRenderUtils.h" CGFloat NativeRenderScreenScale(void) {