-
Notifications
You must be signed in to change notification settings - Fork 352
/
Jason.m
3901 lines (3439 loc) · 159 KB
/
Jason.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
//
// Jason.m
// Jasonette
//
// Copyright © 2016 gliechtenstein. All rights reserved.
//
#import "Jason.h"
#import "JasonAppDelegate.h"
#import "NSData+ImageContentType.h"
#import "UIImage+GIF.h"
@interface Jason(){
UINavigationController *navigationController;
UITabBarController *tabController;
REMenu *menu_component;
JasonViewController *VC;
NSString *title;
NSString *desc;
NSString *icon;
id module;
UIBarButtonItem *rightButtonItem;
NSString *ROOT_URL;
BOOL INITIAL_LOADING;
BOOL isForeground;
BOOL header_needs_refresh;
NSDictionary *rendered_page;
NSMutableDictionary *previous_footer;
NSMutableDictionary *previus_header;
AVCaptureVideoPreviewLayer *avPreviewLayer;
NSMutableArray *queue;
BOOL tabNeedsRefresh;
}
@end
@implementation Jason
#pragma mark - Jason Core initializers
+ (Jason*)client {
static dispatch_once_t predicate = 0;
static id sharedObject = nil;
dispatch_once(&predicate, ^{
sharedObject = [[self alloc] init];
});
return sharedObject;
}
- (id)init {
if (self = [super init]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onForeground) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
self.searchMode = NO;
self.services = [[NSMutableDictionary alloc] init];
// Add observers for public API
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(notifySuccess:)
name:@"Jason.success"
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(notifyError:)
name:@"Jason.error"
object:nil];
}
return self;
}
- (JasonViewController *)getVC {
return VC;
}
#pragma mark - Jason Core API Notifications
- (void)notifySuccess:(NSNotification *)notification {
NSDictionary *args = notification.object;
NSLog(@"JasonCore: notifySuccess: %@", args);
[[Jason client] success:args];
}
- (void)notifyError:(NSNotification *)notification {
NSDictionary *args = notification.object;
NSLog(@"JasonCore: notifyError: %@", args);
[[Jason client] error:args];
}
- (void) loadViewByFile: (NSString *)url asFinal:(BOOL)final onVC: (JasonViewController *)vc{
VC = vc;
[self loadViewByFile:url asFinal:final];
}
- (void) loadViewByFile: (NSString *)url asFinal:(BOOL)final{
id jsonResponseObject = [JasonHelper read_local_json:url];
[self include:jsonResponseObject andCompletionHandler:^(id res){
VC.original = @{@"$jason": res[@"$jason"]};
[self drawViewFromJason: VC.original asFinal:final];
}];
}
#pragma mark - Jason Core API (USE ONLY THESE METHODS TO ACCESS Jason Core!)
- (void)start: (NSDictionary *) href{
/**************************************************
*
* Public API for initializing Jason
* (ex) [[Jason client] start] from JasonAppDelegate
*
**************************************************/
JasonAppDelegate *app = (JasonAppDelegate *)[[UIApplication sharedApplication] delegate];
NSDictionary *plist = [self getSettings];
ROOT_URL = plist[@"url"];
INITIAL_LOADING = [plist[@"loading"] boolValue];
NSString *launch_url = plist[@"launch"];
NSDictionary *launch = nil;
if (launch_url && launch_url.length > 0) {
launch = [JasonHelper read_local_json:launch_url];
}
// FLEX DEBUGGER
#if DEBUG
if(plist[@"debug"] && [plist[@"debug"] boolValue]){
[[FLEXManager sharedManager] showExplorer];
}
#endif
JasonViewController *vc = [[JasonViewController alloc] init];
if(href){
if(href[@"url"]){
vc.url = href[@"url"];
}
if(href[@"options"]){
vc.options = href[@"options"];
}
if(href[@"loading"]){
vc.loading = href[@"loading"];
}
} else {
vc.url = ROOT_URL;
vc.loading = INITIAL_LOADING;
}
if (launch) {
vc.preload = launch;
}
vc.view.backgroundColor = [UIColor whiteColor];
vc.extendedLayoutIncludesOpaqueBars = YES;
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
navigationController.navigationBar.shadowImage = [UIImage new];
[navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
navigationController.navigationBar.translucent = NO;
navigationController.navigationBar.backgroundColor = [UIColor clearColor];
[JasonHelper setStatusBarBackgroundColor: [UIColor clearColor]];
UITabBarController *tab = [[UITabBarController alloc] init];
tab.tabBar.backgroundColor = [UIColor whiteColor];
tab.tabBar.shadowImage = [[UIImage alloc] init];
tab.viewControllers = @[nav];
tab.tabBar.hidden = YES;
[tab setDelegate:self];
app.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
app.window.rootViewController = tab;
[app.window makeKeyAndVisible];
}
- (void)call: (NSDictionary *)action{
/**************************************************
*
* Invoke any action from any module
* (ex) [[Jason client] call: @{@"type": @"$render"}]
*
**************************************************/
[self call: action with: nil];
}
- (void)call: (id)action with: (NSDictionary*)data{
JasonMemory *memory = [JasonMemory client];
// If executing, queue the action with "call" type
if (memory.executing || !VC.events) {
if (!queue) {
queue = [[NSMutableArray alloc] init];
}
if (data) {
[queue addObject:@{ @"action": action, @"data": data }];
} else {
[queue addObject:@{@"action": action}];
}
return;
}
if(data && data.count > 0){
memory._register = data;
}
if([action isKindOfClass:[NSDictionary class]]){
if((NSDictionary *)action && ((NSDictionary *)action).count > 0){
memory._stack = action;
[self exec];
}
} else {
if(memory._register && memory._register.count > 0) {
memory._stack = [self filloutTemplate: action withData: memory._register];
[self exec];
}
}
}
- (void)success{
/**************************************************
*
* ONLY Used from modules as a "success" callback when there's no return value.
* When successful, return from any module by calling:
*
* [[Jason client] success] ==> No return value
*
* When it returns with "success", the returned object will be automatically passed to the next action in the action call chain
*
**************************************************/
[self success:@{}];
}
- (void)success: (id) result withOriginalUrl: (NSString *)url {
if([url isEqualToString:VC.url]){
[self success: result];
}
}
- (void)success: (id)result{
/**************************************************
*
* ONLY Used from Actions as a "success" callback when there's a return value.
* When successful, return from any module by calling:
*
* [[Jason client] success: result] ==> 'result' can be accessed using the variable '$jason' in the next action
*
* When it returns with "success", the returned object will be automatically passed to the next action in the action call chain
*
**************************************************/
if(result){
if([result isKindOfClass:[NSDictionary class]]){
if(((NSDictionary *)result).count > 0){
[JasonMemory client]._register = @{@"$jason": result};
} else {
[JasonMemory client]._register = result;
}
} else {
[JasonMemory client]._register = @{@"$jason": result};
}
} else {
[JasonMemory client]._register = @{@"$jason": @{}};
}
[self networkLoading:NO with:nil];
[self next];
}
- (void)error{
/**************************************************
*
* ONLY Used from modules as a "error" callback.
*
* [[Jason client] error] ==> No return value
*
**************************************************/
[self error:@{}];
}
- (void)error: (id) result withOriginalUrl: (NSString *)url {
if([url isEqualToString:VC.url]){
[self error: result];
}
}
- (void)error: (id)result{
/**************************************************
*
* ONLY Used from modules as a "error" callback.
*
* [[Jason client] error: result] ==> 'result' can be accessed in the error handling action using the variable '$jason'
*
**************************************************/
if(result){
if([result isKindOfClass:[NSDictionary class]]){
if(((NSDictionary *)result).count > 0){
[JasonMemory client]._register = @{@"$jason": result};
} else {
[JasonMemory client]._register = result;
}
} else {
[JasonMemory client]._register = @{@"$jason": result};
}
} else {
[JasonMemory client]._register = @{@"$jason": @{}};
}
// In case oauth was in process, set it back to No
self.oauth_in_process = NO;
[self exception];
}
- (void)loading:(BOOL)turnon{
/************************************************************************************
*
* Loading indicator
*
* pass YES to start loading
* pass NO to end loading
*
**************************************************************************************/
if(turnon){
[JDStatusBarNotification addStyleNamed:@"SBStyle1"
prepare:^JDStatusBarStyle *(JDStatusBarStyle *style) {
style.barColor = navigationController.navigationBar.backgroundColor;
style.textColor = navigationController.navigationBar.tintColor;
style.animationType = JDStatusBarAnimationTypeFade;
return style;
}];
[JDStatusBarNotification showWithStatus:@"Loading" styleName:@"SBStyle1"];
if(navigationController.navigationBar.barStyle == UIStatusBarStyleDefault){
[JDStatusBarNotification showActivityIndicator:YES indicatorStyle:UIActivityIndicatorViewStyleWhite];
} else {
[JDStatusBarNotification showActivityIndicator:YES indicatorStyle:UIActivityIndicatorViewStyleGray];
}
} else {
if([JDStatusBarNotification isVisible]){
[JDStatusBarNotification dismissAnimated:YES];
}
}
}
-(void)networkLoading:(BOOL)turnon with: (NSDictionary *)options;{
dispatch_async(dispatch_get_main_queue(), ^{
if(turnon && (options == nil || (options != nil && options[@"loading"] && [options[@"loading"] boolValue]))){
MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:VC.view animated:true];
hud.animationType = MBProgressHUDAnimationFade;
hud.userInteractionEnabled = NO;
}
else if(!turnon){
[MBProgressHUD hideHUDForView:VC.view animated:true];
}
});
}
# pragma mark - Jason public API (Can be accessed by calling {"type": "$(METHOD_NAME)"}
- (void)parse{
NSDictionary *options = [self options];
if(options[@"data"] && options[@"template"]){
id data = options[@"data"];
NSString *template_name = options[@"template"];
id template = VC.parser[template_name];
id result = [JasonHelper parse:data with:template];
[self success:result];
} else {
[self error:@{@"message": @"Need to pass both data and template"}];
}
}
- (void)href{
JasonMemory *memory = [JasonMemory client];
VC.callback = memory._stack;
NSDictionary *href = [self options];
memory._stack = @{}; // empty stack before visiting
[self go:href];
}
- (void)search{
[[NSNotificationCenter defaultCenter] postNotificationName:@"focusSearch" object:nil];
}
- (void)blur{
[[NSNotificationCenter defaultCenter] postNotificationName:@"blur" object:nil];
}
- (void)home{
[self unlock];
[self go:@{@"transition": @"root"}];
}
- (void)close{
[self okWithMode: @"close"];
}
- (void)back{
/********************************************************************************
*
* Go back to previous view
* if it's a modal, dismiss the modal
* if not, pop back
*
********************************************************************************/
[self unlock];
if(VC.isModal){
[navigationController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
} else {
[navigationController popViewControllerAnimated:YES];
}
}
- (void)cancel{
[self unlock];
[self ok];
}
- (void) okWithMode: (NSString *) mode {
// When user decides to close on intro without "Open"ing, should respect the decision and
// remove local_jason
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults valueForKey:@"local_jason"]){
[defaults removeObjectForKey:@"local_jason"];
[defaults synchronize];
}
// Dismiss Keyboard
[[NSNotificationCenter defaultCenter] postNotificationName:@"dismissSearchInput" object:nil];
[VC.view endEditing:YES];
// Act and close
JasonMemory *memory = [JasonMemory client];
if(memory._stack && memory._stack.count > 0){
memory.need_to_exec = YES;
if (self.options && self.options.count > 0) {
memory._register = @{@"$jason": self.options};
}
} else {
[self unlock];
}
if(menu_component){
if([menu_component isOpen]){
[menu_component close];
}
}
[navigationController setToolbarHidden:YES];
if ([mode isEqualToString:@"close"]) {
[navigationController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
} else {
if(VC.isModal){
[navigationController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
} else {
[navigationController popViewControllerAnimated:YES];
}
}
}
- (void)ok{
[self okWithMode: @"normal"];
}
- (void)ok: (NSDictionary *)data{
JasonMemory *memory = [JasonMemory client];
if(memory._stack && memory._stack.count > 0){
if(data && data.count > 0) {
[memory set_register: data];
}
}
[self ok];
}
- (void)set{
NSDictionary * kv = [self options];
for(NSString *key in kv){
VC.form[key] = kv[key];
}
[self success];
}
- (void)menu{
if(menu_component){
if([menu_component isOpen]){
[menu_component close];
return;
}
}
JasonMemory *memory = [JasonMemory client];
NSDictionary *options = memory._stack[@"options"];
if(!options) return;
NSArray *items = options[@"items"];
if(items && items.count > 0){
NSMutableArray *menu_item_array = [[NSMutableArray alloc] init];
UIColor *backgroundColor = navigationController.navigationBar.barTintColor;
UIColor *foregroundColor = navigationController.navigationBar.tintColor;
for(NSDictionary *item in items){
NSString *itemtitle = item[@"text"];
NSString *subtitle = @"";
NSDictionary *item_action = item[@"action"];
NSDictionary *item_href = item[@"href"];
REMenuItem *menuItem = [[REMenuItem alloc] initWithTitle:itemtitle
subtitle:subtitle
image:nil
highlightedImage:nil
action:^(REMenuItem *item) {
[menu_component close];
if(item_action){
[memory set_stack:item_action];
[self exec];
} else if (item_href){
[self go:item_href];
}
}];
menuItem.backgroundColor = backgroundColor;
menuItem.textColor = foregroundColor;
menuItem.font = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:14.0];
menuItem.separatorColor = menuItem.backgroundColor;
[menu_item_array addObject:menuItem];
}
menu_component =[[REMenu alloc] initWithItems:menu_item_array];
menu_component.backgroundColor = backgroundColor;
menu_component.borderColor = backgroundColor;
menu_component.shadowRadius = 0.0;
menu_component.separatorHeight = 0.0;
menu_component.itemHeight = 50.0;
menu_component.animationDuration = 0.1;
[menu_component showFromNavigationController:navigationController];
}
}
- (void)lambda{
/*
# LAMBDA - Functional Programming for Actions
# Call an action by name, with arguments. Wait for it to finish. And continue on with its return value.
# How it works
1. Calls another action by name
2. Can also pass arguments via `options`, which will be interpreted as `$jason` in the callee action
2. Waits for the callee action to return via `$return.success` or `$return.error`
3. The Callee action can return using the `$return.success` or `$return.error` actions.
4. `$return.success` calls the caller action's `success` action with return value. The caller action picks up where it left off and continues walking down the `success` action call chain.
4. `$return.error` calls the caller action's `error` action with return value. The caller action picks up where it left off and continues walking down the `error` action call chain.
# Example 1: Basic lambda (Same as trigger)
{
"type": "$lambda",
"options": {
"name": "fetch"
}
}
# Example 2: Basic lambda with success/error handlers
{
"type": "$lambda",
"options": {
"name": "fetch"
}
"success": {
"type": "$render"
},
"error": {
"type": "$util.toast",
"options": {
"text": "Error"
}
}
}
# Example 3: Passing arguments
{
"type": "$lambda",
"options": {
"name": "fetch",
"options": {
"url": "https://www.jasonbase.com/things/73g"
}
},
"success": {
"type": "$render"
},
"error": {
"type": "$util.toast",
"options": {
"text": "Error"
}
}
}
# Example 4: Using the previous action's return value
{
"type": "$network.request",
"options": {
"url": "https://www.jasonbase.com/things/73g"
},
"success": {
"type": "$lambda",
"options": {
"name": "draw"
},
"success": {
"type": "$render"
},
"error": {
"type": "$util.toast",
"options": {
"text": "Error"
}
}
}
}
# Example 5: Using the previous action's return value as well as custom options
{
"type": "$network.request",
"options": {
"url": "https://www.jasonbase.com/things/73g"
},
"success": {
"type": "$lambda",
"options": {
"name": "draw",
"options": {
"p1": "another param",
"p2": "yet another param"
}
},
"success": {
"type": "$render"
},
"error": {
"type": "$util.toast",
"options": {
"text": "Error"
}
}
}
}
*/
/*
# Example:
{
"type": "$lambda",
"options": {
"name": "draw",
"options": {
"p1": "another param",
"p2": "yet another param"
}
},
"success": {
"type": "$render"
},
"error": {
"type": "$util.toast",
"options": {
"text": "Error"
}
}
}
*/
NSDictionary *options = [self options];
/*
options = {
"name": "draw",
"options": {
"p1": "another param",
"p2": "yet another param"
}
}
*/
NSString *name = options[@"name"];
/*
name = "draw"
*/
if(name){
// options can be an array or an object
id args = options[@"options"];
/*
args = {
"p1": "another param",
"p2": "yet another param"
}
*/
JasonMemory *memory = [JasonMemory client];
// set register
if(args){
args = [self filloutTemplate: args withData: memory._register];
memory._register = @{@"$jason": args};
} else {
// do nothing. keep the register and propgate
}
id lambda = [[VC valueForKey:@"events"] valueForKey:name];
/*
lambda = [{
"{{#if $jason.items}}: {
"type": "$render",
"options": {
"data": "{{$jason.items}}"
}
}
}, {
"{{#else}}": {
"type": "$util.toast",
"options": {
"text": "Nothing to render"
}
}
}]
*/
NSDictionary *resolved_lambda;
if([lambda isKindOfClass:[NSArray class]]){
resolved_lambda = [self filloutTemplate:lambda withData:memory._register];
} else {
resolved_lambda = lambda;
}
/*
resolved_lambda = {
"type": "$render"
}
*/
// set current stack as the caller (before overwriting the stack)
memory._caller = [memory._stack copy];
// set stack
memory._stack = resolved_lambda;
// exec
[self exec];
} else {
[self error];
}
}
- (void)render{
NSDictionary *stack = [JasonMemory client]._stack;
/**************************************************
*
* PART 1: Prepare data by filling it in with all the variables
*
**************************************************/
if([JasonMemory client]._register && [JasonMemory client]._register.count > 0){
VC.data = [JasonMemory client]._register;
}
NSMutableDictionary *data_stub;
if(VC.data){
data_stub = [VC.data mutableCopy];
} else {
data_stub = [[NSMutableDictionary alloc] init];
}
NSDictionary *kv = [self variables];
for(NSString *key in kv){
data_stub[key] = kv[key];
}
if(stack[@"options"]){
if(!stack[@"options"][@"type"] || [stack[@"options"][@"type"] isEqualToString:@"json"]){
if(stack[@"options"][@"data"]){
/**************************************************
*
* You can pass in 'data' as one of the options for $render action, like so:
*
* {
* "type": "$render",
* "options": {
* "data": {
* "results": [{
* "id": "1",
* "name": "tom"
* }, {
* "id": "2",
* "name": "kat"
* }]
* }
* }
* }
*
* 1. In this case we override the $jason value with the value inside `data`.
*
* In above example, The $jason value at the point of rendering becomes:
*
* $jason = {
* "results": [{
* "id": "1",
* "name": "tom"
* }, {
* "id": "2",
* "name": "kat"
* }]
* }
*
* 2. The `data` can also be a template expression, in which case it will parse whatever data is being passed in to `$render` before using it as the data.
*
* {
* "type": "$render",
* "options": {
* "data": {
* "results": {
* "{{#each $jason}}": {
* "id": "{{id}}",
* "name": "{{name}}"
* }
* }
* }
* }
* }
*
**************************************************/
data_stub[@"$jason"] = [self filloutTemplate:stack[@"options"][@"data"] withData:data_stub];
}
}
}
VC.data = data_stub;
/**************************************************
*
* PART 2: Get the template
*
**************************************************/
// The default template is 'body'
NSString *template_name = @"body";
if(stack[@"options"] && stack[@"options"][@"template"]){
/**************************************************
*
* render can have 'template' attribute as an option, like so:
*
* {
* "type": "$render",
* "options": {
* "template": "empty"
* }
* }
*
* In this case we use the specified 'empty' template instead of 'body'
**************************************************/
template_name = stack[@"options"][@"template"];
}
NSDictionary *body_parser = VC.parser[template_name];
/**********************************************************************
*
* PART 3: Actually render the prepared data with the selected template
*
**********************************************************************/
if(body_parser){
// if self.data is not empty, render
if(stack[@"options"] && stack[@"options"][@"type"]){
if([stack[@"options"][@"type"] isEqualToString:@"html"]){
rendered_page = [JasonHelper parse: data_stub ofType:@"html" with:body_parser];
} else if([stack[@"options"][@"type"] isEqualToString:@"xml"]){
rendered_page = [JasonHelper parse: data_stub ofType:@"xml" with:body_parser];
} else {
rendered_page = [JasonHelper parse: data_stub with:body_parser];
}
} else {
rendered_page = [JasonHelper parse: data_stub with:body_parser];
}
if(rendered_page){
if(rendered_page[@"nav"]) {
// Deprecated
[self setupHeader:rendered_page[@"nav"]];
} else if(rendered_page[@"header"]) {
[self setupHeader:rendered_page[@"header"]];
} else {
[self setupHeader:nil];
}
if(rendered_page[@"footer"]){
[self setupTabBar:rendered_page[@"footer"][@"tabs"]];
} else if(rendered_page[@"tabs"]){
// Deprecated
[self setupTabBar:rendered_page[@"tabs"]];
} else {
[self setupTabBar:nil];
}
if(rendered_page[@"style"] && rendered_page[@"style"][@"background"]){
if([rendered_page[@"style"][@"background"] isKindOfClass:[NSDictionary class]]){
// Advanced background
// example:
// "background": {
// "type": "camera",
// "options": {
// ...
// }
// }
[self drawAdvancedBackground:rendered_page[@"style"][@"background"]];
} else {
[self drawBackground:rendered_page[@"style"][@"background"]];
}
} else if (rendered_page[@"background"]) {
if ([rendered_page[@"background"] isKindOfClass:[NSDictionary class]]) {
// advanced background
[self drawAdvancedBackground:rendered_page[@"background"]];
} else {
[self drawBackground:rendered_page[@"background"]];
}
} else {
[self drawBackground:@"#ffffff"];
}
}
VC.rendered = rendered_page;
if([VC respondsToSelector:@selector(reload:final:)]) [VC reload:rendered_page final:VC.contentLoaded];
// Cache the view after drawing
[self cache_view];
}
[self success];
}
- (void)visit{
JasonMemory *memory = [JasonMemory client];
NSMutableDictionary *href = [[self options] mutableCopy];
memory._stack = @{};
NSString *url = href[@"url"];
if(url && url.length > 0){
url = [url stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([url hasPrefix:@"data:"]){
url = url;
}else if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]) {
url = url;
} else {
url = [NSString stringWithFormat:@"http://%@", url];
}
href[@"url"] = url;
[self call:@{
@"type": @"$href",
@"options": href
}];
}
}
- (void)snapshot{
if(self.avCaptureSession){
// don't snapshot when camera is running
[[Jason client] error];
} else {
UIImage *image = [JasonHelper takescreenshot];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *contentType = @"image/jpeg";
NSString *dataFormatString = @"data:image/jpeg;base64,%@";
NSString *base64data = [imageData base64EncodedStringWithOptions:0];
NSString* dataString = [NSString stringWithFormat:dataFormatString, base64data];
NSURL* dataURI = [NSURL URLWithString:dataString];
[[Jason client] success:@{@"data": base64data, @"data_uri": dataURI.absoluteString, @"content_type" :contentType}];
}
}
- (void) scroll {
if(self.options && self.options[@"position"]) {
NSString *position = self.options[@"position"];
if([position isEqualToString:@"top"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"scrollToTop" object:nil userInfo:nil];
} else if ([position isEqualToString:@"bottom"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"scrollToBottom" object:nil userInfo:nil];
}
}
[[Jason client] success];
}
# pragma mark - View initialization & teardown
- (void)include: (id)json andCompletionHandler:(void(^)(id obj))callback{
NSString *j = [JasonHelper stringify:json];
// 1. Extract "@": "path@URL" patterns and create an array from the URLs
// 2. Make concurrent requests to each item in the array
// 3. Store each result under "[URL]" key
// 4. Whenever we need to process JSON and encouter the "@" : "path@URL" pattern, we look into the "[URL]" value and parse it using path (if it exists)
NSError* regexError = nil;
// The pattern leaves out any url that starts with "$" because that will be handled by resolve_local_reference
NSString *pattern = @"\"([+@])\"[ ]*:[ ]*\"([^$\"@]+@)?([^$\"]+)\"";
NSMutableSet *urlSet = [[NSMutableSet alloc] init];
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:®exError];
NSArray *matches = [regex matchesInString:j options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, j.length)];
for(int i = 0; i<matches.count; i++){
NSTextCheckingResult* match = matches[i];
NSRange group1 = [match rangeAtIndex:1];
NSRange group2 = [match rangeAtIndex:2];
NSRange group3 = [match rangeAtIndex:3];
if(group1.length > 0){
}
if(group2.length > 0){
// Group2 is for path
}
if(group3.length > 0){
// Group2 is for the URL