<commit_before>import { PropertyChangeData } from "ui/core/dependency-observable";
import { PropertyMetadata } from "ui/core/proxy";
import { View, AddArrayFromBuilder } from "ui/core/view";
import { Label } from "ui/label";
import { Color } from 'color';
import * as utils from "utils/utils";
import * as types from "utils/types";
import * as common from "../common";

global.moduleMerge(common, exports);

declare var ADTransitioningDelegate,
    ADCubeTransition,
    ADTransitioningViewController;

export class Pager extends common.Pager {

    private _orientation: UIPageViewControllerNavigationOrientation;
    private _options: NSDictionary<any, any>;
    private _views: any[];
    private _transformer;
    private _ios: UIPageViewController;

    private widthMeasureSpec: number;
    private heightMeasureSpec: number;

    private left = 0;
    private top = 0;
    private right = 0;
    private bottom = 0;

    private cachedViewControllers: WeakRef<PagerView>[] = [];

    borderRadius: number;
    borderWidth: number;
    borderColor: string;
    backgroundColor: any;

    constructor() {
        super();
        this._views = [];
        const that = new WeakRef(this);
        this._orientation = UIPageViewControllerNavigationOrientation.Horizontal;
        this._transformer = UIPageViewControllerTransitionStyle.Scroll;
        const nsVal = <any>[0.0];
        const nsKey = <any>[UIPageViewControllerOptionInterPageSpacingKey];
        this._options = NSDictionary.dictionaryWithObjectsForKeys(nsKey, nsVal);
        this._ios = UIPageViewController.alloc().initWithTransitionStyleNavigationOrientationOptions(this._transformer, this._orientation, this._options);
        this._ios.dataSource = PagerDataSource.initWithOwner(that);
        this._ios.delegate = PagerViewControllerDelegate.initWithOwner(that);
        const pc = this._nativeView.subviews[0];
        pc.hidden = true;
        const sv = this._nativeView.subviews[1];
        if (this.borderRadius) {
            sv.layer.cornerRadius = this.borderRadius;
        }
        if (this.borderColor) {
            sv.layer.borderColor = new Color(this.borderColor).ios.CGColor;
        }
        if (this.backgroundColor) {
            sv.layer.backgroundColor = new Color(this.backgroundColor).ios.CGColor;
        }
        if (this.borderWidth) {
            sv.layer.borderWidth = this.borderWidth;
        }
        // this._ios.view.sendSubviewToBack(pc)
        // this._ios.view.frame = CGRectMake(0, 0, utils.ios.getter(UIScreen, UIScreen.mainScreen.bounds).size.width, utils.ios.getter(UIScreen, UIScreen.mainScreen.bounds).size.height - 300);
        // sv.frame = CGRectMake(0, 0, sv.frame.size.width, sv.frame.size.height);
        // sv.setNeedsLayout();
    }

    get views() {
        return this._views;
    }

    set views(value: any[]) {
        this._views = value;
    }

    get transformer() {
        return this._transformer;
    }

    get ios() {
        return this._ios;
    }

    get _nativeView(): UIView {
        return this._ios.view;
    }

    get _childrenCount(): number {
        return this.items ? this.items.length : 0;
    }

    selectedIndexUpdatedFromNative(newIndex: number) {
        console.log(`Pager.updateSelectedIndexFromNative: -> ${newIndex}`);
        const oldIndex = this.selectedIndex;
        this._onPropertyChangedFromNative(common.Pager.selectedIndexProperty, newIndex);
        this.notify({ eventName: common.Pager.selectedIndexChangedEvent, object: this, oldIndex, newIndex });
    }

    updateNativeIndex(oldIndex: number, newIndex: number) {
        console.log(`Pager.updateNativeIndex: ${oldIndex} -> ${newIndex}`);
        this._navigateNativeViewPagerToIndex(oldIndex, newIndex);
    }

    updateNativeItems(oldItems: View[], newItems: View[]) {
        console.log(`Pager.updateNativeItems: ${newItems ? newItems.length : 0}`);
        if (oldItems) {
            this.cachedViewControllers = [];
        }
        if (newItems) {
            this._initNativeViewPager();
        }
    }

    runUpdate() {}

    getViewController(selectedIndex: number): UIViewController {
        // console.log(`Pager.getViewController: ${selectedIndex}`);
        let vc: PagerView;
        if (this.cachedViewControllers[selectedIndex]) {
            // console.log(`- got PagerView from cache`);
            vc = this.cachedViewControllers[selectedIndex].get();
        }
        if (!vc) {
            // console.log(`- created new PagerView`);
            vc = PagerView.initWithOwnerTag(new WeakRef(this), selectedIndex);
            this.cachedViewControllers[selectedIndex] = new WeakRef(vc);
        }
        let view: View;
        if (this.items && this.items.length) {
            view = this.items[selectedIndex];
        } else {
            let lbl = new Label();
            lbl.text = "Pager.items not set.";
            view = lbl;
        }
        vc.view = view.ios;
        this.prepareView(view);
        return vc;
    }

    onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void {
        // console.log(`Pager.onMeasure: ${widthMeasureSpec}x${heightMeasureSpec}`);
        this.widthMeasureSpec = widthMeasureSpec;
        this.heightMeasureSpec = heightMeasureSpec;
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    onLayout(left: number, top: number, right: number, bottom: number): void {
        // console.log(`Pager.onLayout ${left}, ${top}, ${right}, ${bottom}`);
        super.onLayout(left, top, right, bottom);
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
        if (this.items) {
            this.items.forEach((item) => {
                this.prepareView(item);
            });
        }
        // refresh the UIViewController
        this._initNativeViewPager();
    }

    onLoaded() {
        // console.log(`Pager.ios.onLoaded`);
    }

    onUnloaded() {
        // console.log(`Pager.ios.onUnloaded`);
    }

    _viewControllerRemovedFromParent(controller: PagerView): void {
        // console.log(`Pager.viewControllerRemovedFromParent ${controller.tag}`);
        // this.freeViewControllers.push(new WeakRef(controller));
        // controller.tag = undefined;
        // controller.view = undefined;
        // controller.owner = undefined;
    }
    
    private _initNativeViewPager() {
        let controller = this.getViewController(this.selectedIndex);
        this._ios.setViewControllersDirectionAnimatedCompletion(<any>[controller], UIPageViewControllerNavigationDirection.Forward, false, () => {});
    }

    private _navigateNativeViewPagerToIndex(fromIndex: number, toIndex: number) {
        const vc = this.getViewController(toIndex);
        if (!vc) throw new Error('no VC');
        // console.log(`Pager._navigateNativeViewPagerToIndex: ${toIndex}`);
        const direction = fromIndex < toIndex ?
            UIPageViewControllerNavigationDirection.Forward : UIPageViewControllerNavigationDirection.Reverse;
        this._ios.setViewControllersDirectionAnimatedCompletion(NSArray.arrayWithObject(vc), direction, true, () => {});
    }<commit_msg>fix(iOS): don’t init native viewpager if no items<commit_after>import { PropertyChangeData } from "ui/core/dependency-observable";
import { PropertyMetadata } from "ui/core/proxy";
import { View, AddArrayFromBuilder } from "ui/core/view";
import { Label } from "ui/label";
import { Color } from 'color';
import * as utils from "utils/utils";
import * as types from "utils/types";
import * as common from "../common";

global.moduleMerge(common, exports);

declare var ADTransitioningDelegate,
    ADCubeTransition,
    ADTransitioningViewController;

export class Pager extends common.Pager {

    private _orientation: UIPageViewControllerNavigationOrientation;
    private _options: NSDictionary<any, any>;
    private _views: any[];
    private _transformer;
    private _ios: UIPageViewController;

    private widthMeasureSpec: number;
    private heightMeasureSpec: number;

    private left = 0;
    private top = 0;
    private right = 0;
    private bottom = 0;

    private cachedViewControllers: WeakRef<PagerView>[] = [];

    borderRadius: number;
    borderWidth: number;
    borderColor: string;
    backgroundColor: any;

    constructor() {
        super();
        this._views = [];
        const that = new WeakRef(this);
        this._orientation = UIPageViewControllerNavigationOrientation.Horizontal;
        this._transformer = UIPageViewControllerTransitionStyle.Scroll;
        const nsVal = <any>[0.0];
        const nsKey = <any>[UIPageViewControllerOptionInterPageSpacingKey];
        this._options = NSDictionary.dictionaryWithObjectsForKeys(nsKey, nsVal);
        this._ios = UIPageViewController.alloc().initWithTransitionStyleNavigationOrientationOptions(this._transformer, this._orientation, this._options);
        this._ios.dataSource = PagerDataSource.initWithOwner(that);
        this._ios.delegate = PagerViewControllerDelegate.initWithOwner(that);
        const pc = this._nativeView.subviews[0];
        pc.hidden = true;
        const sv = this._nativeView.subviews[1];
        if (this.borderRadius) {
            sv.layer.cornerRadius = this.borderRadius;
        }
        if (this.borderColor) {
            sv.layer.borderColor = new Color(this.borderColor).ios.CGColor;
        }
        if (this.backgroundColor) {
            sv.layer.backgroundColor = new Color(this.backgroundColor).ios.CGColor;
        }
        if (this.borderWidth) {
            sv.layer.borderWidth = this.borderWidth;
        }
        // this._ios.view.sendSubviewToBack(pc)
        // this._ios.view.frame = CGRectMake(0, 0, utils.ios.getter(UIScreen, UIScreen.mainScreen.bounds).size.width, utils.ios.getter(UIScreen, UIScreen.mainScreen.bounds).size.height - 300);
        // sv.frame = CGRectMake(0, 0, sv.frame.size.width, sv.frame.size.height);
        // sv.setNeedsLayout();
    }

    get views() {
        return this._views;
    }

    set views(value: any[]) {
        this._views = value;
    }

    get transformer() {
        return this._transformer;
    }

    get ios() {
        return this._ios;
    }

    get _nativeView(): UIView {
        return this._ios.view;
    }

    get _childrenCount(): number {
        return this.items ? this.items.length : 0;
    }

    selectedIndexUpdatedFromNative(newIndex: number) {
        console.log(`Pager.updateSelectedIndexFromNative: -> ${newIndex}`);
        const oldIndex = this.selectedIndex;
        this._onPropertyChangedFromNative(common.Pager.selectedIndexProperty, newIndex);
        this.notify({ eventName: common.Pager.selectedIndexChangedEvent, object: this, oldIndex, newIndex });
    }

    updateNativeIndex(oldIndex: number, newIndex: number) {
        console.log(`Pager.updateNativeIndex: ${oldIndex} -> ${newIndex}`);
        this._navigateNativeViewPagerToIndex(oldIndex, newIndex);
    }

    updateNativeItems(oldItems: View[], newItems: View[]) {
        console.log(`Pager.updateNativeItems: ${newItems ? newItems.length : 0}`);
        if (oldItems) {
            this.cachedViewControllers = [];
        }
        if (newItems.length > 0) {
            // re-init
            this._initNativeViewPager();
        }
    }

    runUpdate() {}

    getViewController(selectedIndex: number): UIViewController {
        // console.log(`Pager.getViewController: ${selectedIndex}`);
        let vc: PagerView;
        if (this.cachedViewControllers[selectedIndex]) {
            // console.log(`- got PagerView from cache`);
            vc = this.cachedViewControllers[selectedIndex].get();
        }
        if (!vc) {
            // console.log(`- created new PagerView`);
            vc = PagerView.initWithOwnerTag(new WeakRef(this), selectedIndex);
            this.cachedViewControllers[selectedIndex] = new WeakRef(vc);
        }
        let view: View;
        if (this.items && this.items.length) {
            view = this.items[selectedIndex];
        } else {
            let lbl = new Label();
            lbl.text = "Pager.items not set.";
            view = lbl;
        }
        vc.view = view.ios;
        this.prepareView(view);
        return vc;
    }

    onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void {
        // console.log(`Pager.onMeasure: ${widthMeasureSpec}x${heightMeasureSpec}`);
        this.widthMeasureSpec = widthMeasureSpec;
        this.heightMeasureSpec = heightMeasureSpec;
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    onLayout(left: number, top: number, right: number, bottom: number): void {
        // console.log(`Pager.onLayout ${left}, ${top}, ${right}, ${bottom}`);
        super.onLayout(left, top, right, bottom);
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
        if (this.items && this.items.length > 0) {
            this.items.forEach((item) => {
                this.prepareView(item);
            });
            this._initNativeViewPager();
        }
    }

    onLoaded() {
        // console.log(`Pager.ios.onLoaded`);
    }

    onUnloaded() {
        // console.log(`Pager.ios.onUnloaded`);
    }

    _viewControllerRemovedFromParent(controller: PagerView): void {
        // console.log(`Pager.viewControllerRemovedFromParent ${controller.tag}`);
        // this.freeViewControllers.push(new WeakRef(controller));
        // controller.tag = undefined;
        // controller.view = undefined;
        // controller.owner = undefined;
    }
    
    private _initNativeViewPager() {
        let controller = this.getViewController(this.selectedIndex);
        this._ios.setViewControllersDirectionAnimatedCompletion(<any>[controller], UIPageViewControllerNavigationDirection.Forward, false, () => {});
    }

    private _navigateNativeViewPagerToIndex(fromIndex: number, toIndex: number) {
        const vc = this.getViewController(toIndex);
        if (!vc) throw new Error('no VC');
        // console.log(`Pager._navigateNativeViewPagerToIndex: ${toIndex}`);
        const direction = fromIndex < toIndex ?
            UIPageViewControllerNavigationDirection.Forward : UIPageViewControllerNavigationDirection.Reverse;
        this._ios.setViewControllersDirectionAnimatedCompletion(NSArray.arrayWithObject(vc), direction, true, () => {});
    }
{'fraction_non_alphanumeric': 0.118953431882851, 'fraction_numerical': 0.0024984384759525295, 'mean_word_length': 2.742857142857143, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5127745', 'n_tokens_mistral': 4162, 'n_tokens_neox': 4048, 'n_words': 770}