/
RCTConvert.m
1285 lines (1183 loc) · 41.5 KB
/
RCTConvert.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RCTConvert.h"
#import <objc/message.h>
#import <CoreText/CoreText.h>
#import "RCTDefines.h"
#import "RCTImageSource.h"
#import "RCTParserUtils.h"
#import "RCTUtils.h"
@implementation RCTConvert
RCT_CONVERTER(id, id, self)
RCT_CONVERTER(BOOL, BOOL, boolValue)
RCT_NUMBER_CONVERTER(double, doubleValue)
RCT_NUMBER_CONVERTER(float, floatValue)
RCT_NUMBER_CONVERTER(int, intValue)
RCT_NUMBER_CONVERTER(int64_t, longLongValue);
RCT_NUMBER_CONVERTER(uint64_t, unsignedLongLongValue);
RCT_NUMBER_CONVERTER(NSInteger, integerValue)
RCT_NUMBER_CONVERTER(NSUInteger, unsignedIntegerValue)
/**
* This macro is used for creating converter functions for directly
* representable json values that require no conversion.
*/
#if RCT_DEBUG
#define RCT_JSON_CONVERTER(type) \
+(type *)type : (id)json \
{ \
if ([json isKindOfClass:[type class]]) { \
return json; \
} else if (json) { \
RCTLogConvertError(json, @ #type); \
} \
return nil; \
}
#else
#define RCT_JSON_CONVERTER(type) \
+(type *)type : (id)json \
{ \
return json; \
}
#endif
RCT_JSON_CONVERTER(NSArray)
RCT_JSON_CONVERTER(NSDictionary)
RCT_JSON_CONVERTER(NSString)
RCT_JSON_CONVERTER(NSNumber)
RCT_CUSTOM_CONVERTER(NSSet *, NSSet, [NSSet setWithArray:json])
RCT_CUSTOM_CONVERTER(NSData *, NSData, [json dataUsingEncoding:NSUTF8StringEncoding])
+ (NSIndexSet *)NSIndexSet:(id)json
{
json = [self NSNumberArray:json];
NSMutableIndexSet *indexSet = [NSMutableIndexSet new];
for (NSNumber *number in json) {
NSInteger index = number.integerValue;
if (RCT_DEBUG && index < 0) {
RCTLogError(@"Invalid index value %lld. Indices must be positive.", (long long)index);
}
[indexSet addIndex:index];
}
return indexSet;
}
+ (NSURL *)NSURL:(id)json
{
NSString *path = [self NSString:RCTNilIfNull(json)];
if (!path) {
return nil;
}
@try { // NSURL has a history of crashing with bad input, so let's be safe
NSURL *URL = [NSURL URLWithString:path];
if (URL.scheme) { // Was a well-formed absolute URL
return URL;
}
// Check if it has a scheme
if ([path rangeOfString:@":"].location != NSNotFound) {
NSMutableCharacterSet *urlAllowedCharacterSet = [NSMutableCharacterSet new];
[urlAllowedCharacterSet formUnionWithCharacterSet:[NSCharacterSet URLUserAllowedCharacterSet]];
[urlAllowedCharacterSet formUnionWithCharacterSet:[NSCharacterSet URLPasswordAllowedCharacterSet]];
[urlAllowedCharacterSet formUnionWithCharacterSet:[NSCharacterSet URLHostAllowedCharacterSet]];
[urlAllowedCharacterSet formUnionWithCharacterSet:[NSCharacterSet URLPathAllowedCharacterSet]];
[urlAllowedCharacterSet formUnionWithCharacterSet:[NSCharacterSet URLQueryAllowedCharacterSet]];
[urlAllowedCharacterSet formUnionWithCharacterSet:[NSCharacterSet URLFragmentAllowedCharacterSet]];
path = [path stringByAddingPercentEncodingWithAllowedCharacters:urlAllowedCharacterSet];
URL = [NSURL URLWithString:path];
if (URL) {
return URL;
}
}
// Assume that it's a local path
path = path.stringByRemovingPercentEncoding;
if ([path hasPrefix:@"~"]) {
// Path is inside user directory
path = path.stringByExpandingTildeInPath;
} else if (!path.absolutePath) {
// Assume it's a resource path
path = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:path];
}
if (!(URL = [NSURL fileURLWithPath:path])) {
RCTLogConvertError(json, @"a valid URL");
}
return URL;
} @catch (__unused NSException *e) {
RCTLogConvertError(json, @"a valid URL");
return nil;
}
}
RCT_ENUM_CONVERTER(
NSURLRequestCachePolicy,
(@{
@"default" : @(NSURLRequestUseProtocolCachePolicy),
@"reload" : @(NSURLRequestReloadIgnoringLocalCacheData),
@"force-cache" : @(NSURLRequestReturnCacheDataElseLoad),
@"only-if-cached" : @(NSURLRequestReturnCacheDataDontLoad),
}),
NSURLRequestUseProtocolCachePolicy,
integerValue)
+ (NSURLRequest *)NSURLRequest:(id)json
{
if ([json isKindOfClass:[NSString class]]) {
NSURL *URL = [self NSURL:json];
return URL ? [NSURLRequest requestWithURL:URL] : nil;
}
if ([json isKindOfClass:[NSDictionary class]]) {
NSString *URLString = json[@"uri"] ?: json[@"url"];
NSURL *URL;
NSString *bundleName = json[@"bundle"];
if (bundleName) {
URLString = [NSString stringWithFormat:@"%@.bundle/%@", bundleName, URLString];
}
URL = [self NSURL:URLString];
if (!URL) {
return nil;
}
NSData *body = [self NSData:json[@"body"]];
NSString *method = [self NSString:json[@"method"]].uppercaseString ?: @"GET";
NSURLRequestCachePolicy cachePolicy = [self NSURLRequestCachePolicy:json[@"cache"]];
NSDictionary *headers = [self NSDictionary:json[@"headers"]];
if ([method isEqualToString:@"GET"] && headers == nil && body == nil &&
cachePolicy == NSURLRequestUseProtocolCachePolicy) {
return [NSURLRequest requestWithURL:URL];
}
if (headers) {
__block BOOL allHeadersAreStrings = YES;
[headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, id header, BOOL *stop) {
if (![header isKindOfClass:[NSString class]]) {
RCTLogError(
@"Values of HTTP headers passed must be of type string. "
"Value of header '%@' is not a string.",
key);
allHeadersAreStrings = NO;
*stop = YES;
}
}];
if (!allHeadersAreStrings) {
// Set headers to nil here to avoid crashing later.
headers = nil;
}
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPBody = body;
request.HTTPMethod = method;
request.cachePolicy = cachePolicy;
request.allHTTPHeaderFields = headers;
return [request copy];
}
if (json) {
RCTLogConvertError(json, @"a valid URLRequest");
}
return nil;
}
+ (RCTFileURL *)RCTFileURL:(id)json
{
NSURL *fileURL = [self NSURL:json];
if (!fileURL.fileURL) {
RCTLogError(@"URI must be a local file, '%@' isn't.", fileURL);
return nil;
}
if (![[NSFileManager defaultManager] fileExistsAtPath:fileURL.path]) {
RCTLogError(@"File '%@' could not be found.", fileURL);
return nil;
}
return fileURL;
}
+ (NSDate *)NSDate:(id)json
{
if ([json isKindOfClass:[NSNumber class]]) {
return [NSDate dateWithTimeIntervalSince1970:[self NSTimeInterval:json]];
} else if ([json isKindOfClass:[NSString class]]) {
static NSDateFormatter *formatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
formatter = [NSDateFormatter new];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ";
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
});
NSDate *date = [formatter dateFromString:json];
if (!date) {
RCTLogError(
@"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) {
RCTLogConvertError(json, @"a date");
}
return nil;
}
+ (NSLocale *)NSLocale:(id)json
{
if ([json isKindOfClass:[NSString class]]) {
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:json];
if (!locale) {
RCTLogError(@"JSON String '%@' could not be interpreted as a valid locale. ", json);
}
return locale;
} else if (json) {
RCTLogConvertError(json, @"a locale");
}
return nil;
}
// JS Standard for time is milliseconds
RCT_CUSTOM_CONVERTER(NSTimeInterval, NSTimeInterval, [self double:json] / 1000.0)
// JS standard for time zones is minutes.
RCT_CUSTOM_CONVERTER(NSTimeZone *, NSTimeZone, [NSTimeZone timeZoneForSecondsFromGMT:[self double:json] * 60.0])
NSNumber *RCTConvertEnumValue(const char *typeName, NSDictionary *mapping, NSNumber *defaultValue, id json)
{
if (!json) {
return defaultValue;
}
if ([json isKindOfClass:[NSNumber class]]) {
NSArray *allValues = mapping.allValues;
if ([allValues containsObject:json] || [json isEqual:defaultValue]) {
return json;
}
RCTLogError(@"Invalid %s '%@'. should be one of: %@", typeName, json, allValues);
return defaultValue;
}
if (RCT_DEBUG && ![json isKindOfClass:[NSString class]]) {
RCTLogError(@"Expected NSNumber or NSString for %s, received %@: %@", typeName, [json classForCoder], json);
}
id value = mapping[json];
if (RCT_DEBUG && !value && [json description].length > 0) {
RCTLogError(
@"Invalid %s '%@'. should be one of: %@",
typeName,
json,
[[mapping allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]);
}
return value ?: defaultValue;
}
NSNumber *RCTConvertMultiEnumValue(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 = RCTConvertEnumValue(typeName, mapping, defaultValue, arrayElement);
result |= value.longLongValue;
}
return @(result);
}
return RCTConvertEnumValue(typeName, mapping, defaultValue, json);
}
RCT_ENUM_CONVERTER(
NSLineBreakMode,
(@{
@"clip" : @(NSLineBreakByClipping),
@"head" : @(NSLineBreakByTruncatingHead),
@"tail" : @(NSLineBreakByTruncatingTail),
@"middle" : @(NSLineBreakByTruncatingMiddle),
@"wordWrapping" : @(NSLineBreakByWordWrapping),
}),
NSLineBreakByTruncatingTail,
integerValue)
RCT_ENUM_CONVERTER(
NSTextAlignment,
(@{
@"auto" : @(NSTextAlignmentNatural),
@"left" : @(NSTextAlignmentLeft),
@"center" : @(NSTextAlignmentCenter),
@"right" : @(NSTextAlignmentRight),
@"justify" : @(NSTextAlignmentJustified),
}),
NSTextAlignmentNatural,
integerValue)
RCT_ENUM_CONVERTER(
NSUnderlineStyle,
(@{
@"solid" : @(NSUnderlineStyleSingle),
@"double" : @(NSUnderlineStyleDouble),
@"dotted" : @(NSUnderlinePatternDot | NSUnderlineStyleSingle),
@"dashed" : @(NSUnderlinePatternDash | NSUnderlineStyleSingle),
}),
NSUnderlineStyleSingle,
integerValue)
RCT_ENUM_CONVERTER(
RCTBorderStyle,
(@{
@"solid" : @(RCTBorderStyleSolid),
@"dotted" : @(RCTBorderStyleDotted),
@"dashed" : @(RCTBorderStyleDashed),
}),
RCTBorderStyleSolid,
integerValue)
RCT_ENUM_CONVERTER(
RCTTextDecorationLineType,
(@{
@"none" : @(RCTTextDecorationLineTypeNone),
@"underline" : @(RCTTextDecorationLineTypeUnderline),
@"line-through" : @(RCTTextDecorationLineTypeStrikethrough),
@"underline line-through" : @(RCTTextDecorationLineTypeUnderlineStrikethrough),
}),
RCTTextDecorationLineTypeNone,
integerValue)
RCT_ENUM_CONVERTER(
NSWritingDirection,
(@{
@"auto" : @(NSWritingDirectionNatural),
@"ltr" : @(NSWritingDirectionLeftToRight),
@"rtl" : @(NSWritingDirectionRightToLeft),
}),
NSWritingDirectionNatural,
integerValue)
RCT_ENUM_CONVERTER(
UITextAutocapitalizationType,
(@{
@"none" : @(UITextAutocapitalizationTypeNone),
@"words" : @(UITextAutocapitalizationTypeWords),
@"sentences" : @(UITextAutocapitalizationTypeSentences),
@"characters" : @(UITextAutocapitalizationTypeAllCharacters)
}),
UITextAutocapitalizationTypeSentences,
integerValue)
RCT_ENUM_CONVERTER(
UITextFieldViewMode,
(@{
@"never" : @(UITextFieldViewModeNever),
@"while-editing" : @(UITextFieldViewModeWhileEditing),
@"unless-editing" : @(UITextFieldViewModeUnlessEditing),
@"always" : @(UITextFieldViewModeAlways),
}),
UITextFieldViewModeNever,
integerValue)
+ (UIKeyboardType)UIKeyboardType:(id)json RCT_DYNAMIC
{
static NSDictionary<NSString *, NSNumber *> *mapping;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSMutableDictionary<NSString *, NSNumber *> *temporaryMapping = [NSMutableDictionary dictionaryWithDictionary:@{
@"default" : @(UIKeyboardTypeDefault),
@"ascii-capable" : @(UIKeyboardTypeASCIICapable),
@"numbers-and-punctuation" : @(UIKeyboardTypeNumbersAndPunctuation),
@"url" : @(UIKeyboardTypeURL),
@"number-pad" : @(UIKeyboardTypeNumberPad),
@"phone-pad" : @(UIKeyboardTypePhonePad),
@"name-phone-pad" : @(UIKeyboardTypeNamePhonePad),
@"email-address" : @(UIKeyboardTypeEmailAddress),
@"decimal-pad" : @(UIKeyboardTypeDecimalPad),
@"twitter" : @(UIKeyboardTypeTwitter),
@"web-search" : @(UIKeyboardTypeWebSearch),
// Added for Android compatibility
@"numeric" : @(UIKeyboardTypeDecimalPad),
}];
temporaryMapping[@"ascii-capable-number-pad"] = @(UIKeyboardTypeASCIICapableNumberPad);
mapping = temporaryMapping;
});
UIKeyboardType type = RCTConvertEnumValue("UIKeyboardType", mapping, @(UIKeyboardTypeDefault), json).integerValue;
return type;
}
RCT_MULTI_ENUM_CONVERTER(
UIDataDetectorTypes,
(@{
@"phoneNumber" : @(UIDataDetectorTypePhoneNumber),
@"link" : @(UIDataDetectorTypeLink),
@"address" : @(UIDataDetectorTypeAddress),
@"calendarEvent" : @(UIDataDetectorTypeCalendarEvent),
@"none" : @(UIDataDetectorTypeNone),
@"all" : @(UIDataDetectorTypeAll),
}),
UIDataDetectorTypePhoneNumber,
unsignedLongLongValue)
RCT_MULTI_ENUM_CONVERTER(
WKDataDetectorTypes,
(@{
@"phoneNumber" : @(WKDataDetectorTypePhoneNumber),
@"link" : @(WKDataDetectorTypeLink),
@"address" : @(WKDataDetectorTypeAddress),
@"calendarEvent" : @(WKDataDetectorTypeCalendarEvent),
@"trackingNumber" : @(WKDataDetectorTypeTrackingNumber),
@"flightNumber" : @(WKDataDetectorTypeFlightNumber),
@"lookupSuggestion" : @(WKDataDetectorTypeLookupSuggestion),
@"none" : @(WKDataDetectorTypeNone),
@"all" : @(WKDataDetectorTypeAll),
}),
WKDataDetectorTypePhoneNumber,
unsignedLongLongValue)
RCT_ENUM_CONVERTER(
UIKeyboardAppearance,
(@{
@"default" : @(UIKeyboardAppearanceDefault),
@"light" : @(UIKeyboardAppearanceLight),
@"dark" : @(UIKeyboardAppearanceDark),
}),
UIKeyboardAppearanceDefault,
integerValue)
RCT_ENUM_CONVERTER(
UIReturnKeyType,
(@{
@"default" : @(UIReturnKeyDefault),
@"go" : @(UIReturnKeyGo),
@"google" : @(UIReturnKeyGoogle),
@"join" : @(UIReturnKeyJoin),
@"next" : @(UIReturnKeyNext),
@"route" : @(UIReturnKeyRoute),
@"search" : @(UIReturnKeySearch),
@"send" : @(UIReturnKeySend),
@"yahoo" : @(UIReturnKeyYahoo),
@"done" : @(UIReturnKeyDone),
@"emergency-call" : @(UIReturnKeyEmergencyCall),
}),
UIReturnKeyDefault,
integerValue)
RCT_ENUM_CONVERTER(
UIViewContentMode,
(@{
@"scale-to-fill" : @(UIViewContentModeScaleToFill),
@"scale-aspect-fit" : @(UIViewContentModeScaleAspectFit),
@"scale-aspect-fill" : @(UIViewContentModeScaleAspectFill),
@"redraw" : @(UIViewContentModeRedraw),
@"center" : @(UIViewContentModeCenter),
@"top" : @(UIViewContentModeTop),
@"bottom" : @(UIViewContentModeBottom),
@"left" : @(UIViewContentModeLeft),
@"right" : @(UIViewContentModeRight),
@"top-left" : @(UIViewContentModeTopLeft),
@"top-right" : @(UIViewContentModeTopRight),
@"bottom-left" : @(UIViewContentModeBottomLeft),
@"bottom-right" : @(UIViewContentModeBottomRight),
// Cross-platform values
@"cover" : @(UIViewContentModeScaleAspectFill),
@"contain" : @(UIViewContentModeScaleAspectFit),
@"stretch" : @(UIViewContentModeScaleToFill),
}),
UIViewContentModeScaleAspectFill,
integerValue)
RCT_ENUM_CONVERTER(
UIBarStyle,
(@{
@"default" : @(UIBarStyleDefault),
@"black" : @(UIBarStyleBlack),
@"blackOpaque" : @(UIBarStyleBlackOpaque),
@"blackTranslucent" : @(UIBarStyleBlackTranslucent),
}),
UIBarStyleDefault,
integerValue)
static void convertCGStruct(const char *type, NSArray *fields, CGFloat *result, id json)
{
NSUInteger count = fields.count;
if ([json isKindOfClass:[NSArray class]]) {
if (RCT_DEBUG && [json count] != count) {
RCTLogError(
@"Expected array with count %llu, but count is %llu: %@",
(unsigned long long)count,
(unsigned long long)[json count],
json);
} else {
for (NSUInteger i = 0; i < count; i++) {
result[i] = [RCTConvert CGFloat:RCTNilIfNull(json[i])];
}
}
} else if ([json isKindOfClass:[NSDictionary class]]) {
for (NSUInteger i = 0; i < count; i++) {
result[i] = [RCTConvert CGFloat:RCTNilIfNull(json[fields[i]])];
}
} else if (json) {
RCTLogConvertError(json, @(type));
}
}
/**
* This macro is used for creating converter functions for structs that consist
* of a number of CGFloat properties, such as CGPoint, CGRect, etc.
*/
#define RCT_CGSTRUCT_CONVERTER(type, values) \
+(type)type : (id)json \
{ \
static NSArray *fields; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
fields = values; \
}); \
type result; \
convertCGStruct(#type, fields, (CGFloat *)&result, json); \
return result; \
}
RCT_CUSTOM_CONVERTER(CGFloat, CGFloat, [self double:json])
RCT_CGSTRUCT_CONVERTER(CGPoint, (@[ @"x", @"y" ]))
RCT_CGSTRUCT_CONVERTER(CGSize, (@[ @"width", @"height" ]))
RCT_CGSTRUCT_CONVERTER(CGRect, (@[ @"x", @"y", @"width", @"height" ]))
+ (UIEdgeInsets)UIEdgeInsets:(id)json
{
static NSArray *fields;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
fields = @[ @"top", @"left", @"bottom", @"right" ];
});
if ([json isKindOfClass:[NSNumber class]]) {
CGFloat value = [json doubleValue];
return UIEdgeInsetsMake(value, value, value, value);
} else {
UIEdgeInsets result;
convertCGStruct("UIEdgeInsets", fields, (CGFloat *)&result, json);
return result;
}
}
RCT_ENUM_CONVERTER(
CGLineJoin,
(@{
@"miter" : @(kCGLineJoinMiter),
@"round" : @(kCGLineJoinRound),
@"bevel" : @(kCGLineJoinBevel),
}),
kCGLineJoinMiter,
intValue)
RCT_ENUM_CONVERTER(
CGLineCap,
(@{
@"butt" : @(kCGLineCapButt),
@"round" : @(kCGLineCapRound),
@"square" : @(kCGLineCapSquare),
}),
kCGLineCapButt,
intValue)
RCT_CGSTRUCT_CONVERTER(CGAffineTransform, (@[ @"a", @"b", @"c", @"d", @"tx", @"ty" ]))
static NSString *const RCTFallback = @"fallback";
static NSString *const RCTFallbackARGB = @"fallback-argb";
static NSString *const RCTSelector = @"selector";
static NSString *const RCTIndex = @"index";
/** The following dictionary defines the react-native semantic colors for ios.
* If the value for a given name is empty then the name itself
* is used as the UIColor selector.
* If the RCTSelector key is present then that value is used for a selector instead
* of the key name.
* If the given selector is not available on the running OS version then
* the RCTFallback selector is used instead.
* If the RCTIndex key is present then object returned from UIColor is an
* NSArray and the object at index RCTIndex is to be used.
*/
static NSDictionary<NSString *, NSDictionary *> *RCTSemanticColorsMap()
{
static NSDictionary<NSString *, NSDictionary *> *colorMap = nil;
if (colorMap == nil) {
NSMutableDictionary<NSString *, NSDictionary *> *map = [@{
// https://developer.apple.com/documentation/uikit/uicolor/ui_element_colors
// Label Colors
@"labelColor" : @{
// iOS 13.0
RCTFallbackARGB :
@(0xFF000000) // fallback for iOS<=12: RGBA returned by this semantic color in light mode on iOS 13
},
@"secondaryLabelColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x993c3c43)
},
@"tertiaryLabelColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x4c3c3c43)
},
@"quaternaryLabelColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x2d3c3c43)
},
// Fill Colors
@"systemFillColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x33787880)
},
@"secondarySystemFillColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x28787880)
},
@"tertiarySystemFillColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x1e767680)
},
@"quaternarySystemFillColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x14747480)
},
// Text Colors
@"placeholderTextColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x4c3c3c43)
},
// Standard Content Background Colors
@"systemBackgroundColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFffffff)
},
@"secondarySystemBackgroundColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFf2f2f7)
},
@"tertiarySystemBackgroundColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFffffff)
},
// Grouped Content Background Colors
@"systemGroupedBackgroundColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFf2f2f7)
},
@"secondarySystemGroupedBackgroundColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFffffff)
},
@"tertiarySystemGroupedBackgroundColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFf2f2f7)
},
// Separator Colors
@"separatorColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x493c3c43)
},
@"opaqueSeparatorColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFc6c6c8)
},
// Link Color
@"linkColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFF007aff)
},
// Nonadaptable Colors
@"darkTextColor" : @{},
@"lightTextColor" : @{},
// https://developer.apple.com/documentation/uikit/uicolor/standard_colors
// Adaptable Colors
@"systemBlueColor" : @{},
@"systemBrownColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFa2845e)
},
@"systemGreenColor" : @{},
@"systemIndigoColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFF5856d6)
},
@"systemOrangeColor" : @{},
@"systemPinkColor" : @{},
@"systemPurpleColor" : @{},
@"systemRedColor" : @{},
@"systemTealColor" : @{},
@"systemYellowColor" : @{},
// Adaptable Gray Colors
@"systemGrayColor" : @{},
@"systemGray2Color" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFaeaeb2)
},
@"systemGray3Color" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFc7c7cc)
},
@"systemGray4Color" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFd1d1d6)
},
@"systemGray5Color" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFe5e5ea)
},
@"systemGray6Color" : @{
// iOS 13.0
RCTFallbackARGB : @(0xFFf2f2f7)
},
// Transparent Color
@"clearColor" : @{
// iOS 13.0
RCTFallbackARGB : @(0x00000000)
},
} mutableCopy];
// The color names are the Objective-C UIColor selector names,
// but Swift selector names are valid as well, so make aliases.
static NSString *const RCTColorSuffix = @"Color";
NSMutableDictionary<NSString *, NSDictionary *> *aliases = [NSMutableDictionary new];
for (NSString *objcSelector in map) {
RCTAssert(
[objcSelector hasSuffix:RCTColorSuffix], @"A selector in the color map did not end with the suffix Color.");
NSMutableDictionary *entry = [map[objcSelector] mutableCopy];
RCTAssert([entry objectForKey:RCTSelector] == nil, @"Entry should not already have an RCTSelector");
NSString *swiftSelector = [objcSelector substringToIndex:[objcSelector length] - [RCTColorSuffix length]];
entry[RCTSelector] = objcSelector;
aliases[swiftSelector] = entry;
}
[map addEntriesFromDictionary:aliases];
#if DEBUG
[map addEntriesFromDictionary:@{
// The follow exist for Unit Tests
@"unitTestFallbackColor" : @{RCTFallback : @"gridColor"},
@"unitTestFallbackColorIOS" : @{RCTFallback : @"blueColor"},
@"unitTestFallbackColorEven" : @{
RCTSelector : @"unitTestFallbackColorEven",
RCTIndex : @0,
RCTFallback : @"controlAlternatingRowBackgroundColors"
},
@"unitTestFallbackColorOdd" : @{
RCTSelector : @"unitTestFallbackColorOdd",
RCTIndex : @1,
RCTFallback : @"controlAlternatingRowBackgroundColors"
},
}];
#endif
colorMap = [map copy];
}
return colorMap;
}
/** Returns a UIColor based on a semantic color name.
* Returns nil if the semantic color name is invalid.
*/
static UIColor *RCTColorFromSemanticColorName(NSString *semanticColorName)
{
NSDictionary<NSString *, NSDictionary *> *colorMap = RCTSemanticColorsMap();
UIColor *color = nil;
NSDictionary<NSString *, id> *colorInfo = colorMap[semanticColorName];
if (colorInfo) {
NSString *semanticColorSelector = colorInfo[RCTSelector];
if (semanticColorSelector == nil) {
semanticColorSelector = semanticColorName;
}
SEL selector = NSSelectorFromString(semanticColorSelector);
if (![UIColor respondsToSelector:selector]) {
NSNumber *fallbackRGB = colorInfo[RCTFallbackARGB];
if (fallbackRGB != nil) {
RCTAssert([fallbackRGB isKindOfClass:[NSNumber class]], @"fallback ARGB is not a number");
return [RCTConvert UIColor:fallbackRGB];
}
semanticColorSelector = colorInfo[RCTFallback];
selector = NSSelectorFromString(semanticColorSelector);
}
RCTAssert([UIColor respondsToSelector:selector], @"RCTUIColor does not respond to a semantic color selector.");
Class klass = [UIColor class];
IMP imp = [klass methodForSelector:selector];
id (*getSemanticColorObject)(id, SEL) = (void *)imp;
id colorObject = getSemanticColorObject(klass, selector);
if ([colorObject isKindOfClass:[UIColor class]]) {
color = colorObject;
} else if ([colorObject isKindOfClass:[NSArray class]]) {
NSArray *colors = colorObject;
NSNumber *index = colorInfo[RCTIndex];
RCTAssert(index, @"index should not be null");
color = colors[[index unsignedIntegerValue]];
} else {
RCTAssert(false, @"selector return an unknown object type");
}
}
return color;
}
/** Returns an alphabetically sorted comma separated list of the valid semantic color names
*/
static NSString *RCTSemanticColorNames()
{
NSMutableString *names = [NSMutableString new];
NSDictionary<NSString *, NSDictionary *> *colorMap = RCTSemanticColorsMap();
NSArray *allKeys =
[[[colorMap allKeys] mutableCopy] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
for (id key in allKeys) {
if ([names length]) {
[names appendString:@", "];
}
[names appendString:key];
}
return names;
}
+ (UIColor *)UIColor:(id)json
{
if (!json) {
return nil;
}
if ([json isKindOfClass:[NSArray class]]) {
NSArray *components = [self NSNumberArray:json];
CGFloat alpha = components.count > 3 ? [self CGFloat:components[3]] : 1.0;
return [UIColor colorWithRed:[self CGFloat:components[0]]
green:[self CGFloat:components[1]]
blue:[self CGFloat:components[2]]
alpha:alpha];
} else if ([json isKindOfClass:[NSNumber class]]) {
NSUInteger argb = [self NSUInteger:json];
CGFloat a = ((argb >> 24) & 0xFF) / 255.0;
CGFloat r = ((argb >> 16) & 0xFF) / 255.0;
CGFloat g = ((argb >> 8) & 0xFF) / 255.0;
CGFloat b = (argb & 0xFF) / 255.0;
return [UIColor colorWithRed:r green:g blue:b alpha:a];
} else if ([json isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = json;
id value = nil;
if ((value = [dictionary objectForKey:@"semantic"])) {
if ([value isKindOfClass:[NSString class]]) {
NSString *semanticName = value;
UIColor *color = [UIColor colorNamed:semanticName];
if (color != nil) {
return color;
}
color = RCTColorFromSemanticColorName(semanticName);
if (color == nil) {
RCTLogConvertError(
json,
[@"a UIColor. Expected one of the following values: " stringByAppendingString:RCTSemanticColorNames()]);
}
return color;
} else if ([value isKindOfClass:[NSArray class]]) {
for (id name in value) {
UIColor *color = [UIColor colorNamed:name];
if (color != nil) {
return color;
}
color = RCTColorFromSemanticColorName(name);
if (color != nil) {
return color;
}
}
RCTLogConvertError(
json,
[@"a UIColor. None of the names in the array were one of the following values: "
stringByAppendingString:RCTSemanticColorNames()]);
return nil;
}
RCTLogConvertError(
json, @"a UIColor. Expected either a single name or an array of names but got something else.");
return nil;
} else if ((value = [dictionary objectForKey:@"dynamic"])) {
NSDictionary *appearances = value;
id light = [appearances objectForKey:@"light"];
UIColor *lightColor = [RCTConvert UIColor:light];
id dark = [appearances objectForKey:@"dark"];
UIColor *darkColor = [RCTConvert UIColor:dark];
id highContrastLight = [appearances objectForKey:@"highContrastLight"];
UIColor *highContrastLightColor = [RCTConvert UIColor:highContrastLight];
id highContrastDark = [appearances objectForKey:@"highContrastDark"];
UIColor *highContrastDarkColor = [RCTConvert UIColor:highContrastDark];
if (lightColor != nil && darkColor != nil) {
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
if (@available(iOS 13.0, *)) {
UIColor *color = [UIColor colorWithDynamicProvider:^UIColor *_Nonnull(
UITraitCollection *_Nonnull collection) {
if (collection.userInterfaceStyle == UIUserInterfaceStyleDark) {
if (collection.accessibilityContrast == UIAccessibilityContrastHigh && highContrastDarkColor != nil) {
return highContrastDarkColor;
} else {
return darkColor;
}
} else {
if (collection.accessibilityContrast == UIAccessibilityContrastHigh && highContrastLightColor != nil) {
return highContrastLightColor;
} else {
return lightColor;
}
}
}];
return color;
} else {
#endif
return lightColor;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
}
#endif
} else {
RCTLogConvertError(json, @"a UIColor. Expected an iOS dynamic appearance aware color.");
return nil;
}
} else {
RCTLogConvertError(json, @"a UIColor. Expected an iOS semantic color or dynamic appearance aware color.");
return nil;
}
} else {
RCTLogConvertError(json, @"a UIColor. Did you forget to call processColor() on the JS side?");
return nil;
}
}
+ (CGColorRef)CGColor:(id)json
{
return [self UIColor:json].CGColor;
}
+ (YGValue)YGValue:(id)json
{
if (!json) {
return YGValueUndefined;
} else if ([json isKindOfClass:[NSNumber class]]) {
return (YGValue){[json floatValue], YGUnitPoint};
} else if ([json isKindOfClass:[NSString class]]) {
NSString *s = (NSString *)json;
if ([s isEqualToString:@"auto"]) {
return (YGValue){YGUndefined, YGUnitAuto};
} else if ([s hasSuffix:@"%"]) {
return (YGValue){[[s substringToIndex:s.length] floatValue], YGUnitPercent};
} else {
RCTLogConvertError(json, @"a YGValue. Did you forget the % or pt suffix?");
}
} else {
RCTLogConvertError(json, @"a YGValue.");
}
return YGValueUndefined;
}
NSArray *RCTConvertArrayValue(SEL type, id json)
{
__block BOOL copy = NO;
__block NSArray *values = json = [RCTConvert NSArray:json];
[json enumerateObjectsUsingBlock:^(id jsonValue, NSUInteger idx, __unused BOOL *stop) {
id value = ((id(*)(Class, SEL, id))objc_msgSend)([RCTConvert class], type, jsonValue);
if (copy) {
if (value) {
[(NSMutableArray *)values addObject:value];
}
} else if (value != jsonValue) {
// 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:json[i]];
}
if (value) {
[(NSMutableArray *)values addObject:value];
}
copy = YES;
}
}];
return values;
}