<commit_before>define([
    'knockout-plus',
    'kb_common/html',
    'kb_common/bootstrapUtils',
    'kb_common_ts/Auth2Error',
    'kb_plugin_auth2-client',
    'yaml!../config.yml',
    'bootstrap'
], function (
    ko,
    html,
    BS,
    Auth2Error,
    Plugin,
    config
) {
    var t = html.tag,
        div = t('div'),
        span = t('span'),
        br = t('br', { close: false }),
        p = t('p'),
        a = t('a'),
        b = t('b'),
        button = t('button'),
        h3 = t('h3'),
        legend = t('legend'),
        i = t('i'),
        ul = t('ul'),
        li = t('li'),
        iframe = t('iframe');

    function buildTabs() {
        return div({}, [
            ul({
                class: 'nav nav-tabs',
                role: 'tablist',
                dataBind: {
                    foreach: 'tabs'
                }
            }, [
                '<!-- ko if: show -->',
                li({
                    role: 'presentation',
                    style: {
                        fontWeight: 'bold'
                    },
                    dataBind: {
                        css: {
                            active: 'active'
                        }
                    }
                }, a({
                    dataBind: {
                        attrs: {
                            id: 'name',
                            href: '"#" + name'
                        },
                        html: 'label',
                        click: '$component.doSelectTab'
                    }
                })),
                '<!-- /ko -->'
            ]),
            div({
                class: 'tab-content',
                dataBind: {
                    foreach: 'tabs'
                }
            }, [
                '<!-- ko if: show -->',
                div({
                    role: 'tabpanel',
                    class: 'tab-pane',
                    style: {
                        paddingTop: '10px'
                    },
                    dataBind: {
                        css: {
                            active: 'active'
                        },
                        attrs: {
                            id: 'name'
                        },
                        template: {
                            nodes: 'template'
                        }
                    }
                }),
                '<!-- /ko -->'
            ])
        ]);
    }

    function buildLoginControl(runtime) {
        return div({
            dataBind: {
                ifnot: 'authorized'
            },
            style: {
                width: '80%',
                display: 'inline-block',
                minWidth: '210px'
            }
        }, [
            div({
                class: 'btn-group-vertical',
                style: {
                    width: '100%'
                },
                minWidth: '200px'
            }, [
                button({
                    class: 'btn btn-default',
                    style: {
                        textAlign: 'center'
                    },
                    dataBind: {
                        click: 'doSetSigninMode',
                        css: {
                            active: 'mode() === "signin"'
                        },
                        attr: {
                            'data-control': '"signin-button"'
                        }
                    }
                }, div({
                    style: {
                        display: 'inline-block',
                        width: '50%',
                        textAlign: 'left',
                        fontWeight: 'bold',
                        verticalAlign: 'middle'
                    }
                }, [
                    span({
                        class: 'fa fa-sign-in fa-2x',
                        style: {
                            marginRight: '10px',
                            verticalAlign: 'middle'
                        }
                    }),
                    span({
                        style: {
                            verticalAlign: 'middle'
                        }
                    }, 'Sign In')

                ])),
                div({
                        dataBind: {
                            visible: 'mode() === "signin"'
                        }
                    },
                    div({
                        style: {
                            marginBottom: '20px',
                            padding: '4px',
                            // borderBottom: '1px silver solid',
                            backgroundColor: '#DDD',
                            textAlign: 'left'
                        }
                    }, [
                        div({
                            style: {
                                margin: '6px 0 0 0',
                                fontStyle: 'italic',
                                textAlign: 'center'
                            }
                        }, [
                            'Choose Globus if you signed up',
                            br(),
                            'before ',
                            span({
                                dataBind: {
                                    text: '$component.config.launchDate'
                                }
                            })
                        ]),
                        div({
                            // class: 'btn-group-vertical',
                            style: {
                                width: '100%',
                                display: 'inline-block',
                            },
                            dataBind: {
                                foreach: 'providers'
                            }
                        }, div({
                            dataBind: {
                                component: {
                                    name: '"signin-button"',
                                    params: {
                                        provider: '$data',
                                        runtime: '$component.runtime',
                                        nextRequest: '$component.nextRequest',
                                        assetsPath: '$component.assetsPath',
                                        origin: '"login"'
                                    }
                                }
                            }
                        }))
                        // div({
                        //     style: {
                        //         marginTop: '0.5em',
                        //         textAlign: 'center'
                        //     }
                        // }, [
                        //     input({
                        //         type: 'checkbox',
                        //         dataBind: {
                        //             checked: 'isSessionPersistent',

                        //         },
                        //     }),
                        //     ' Stay signed in'
                        // ]),
                    ])),
                button({
                    class: 'btn btn-default',
                    style: {
                        textAlign: 'center',
                        marginTop: '10px'
                    },
                    dataBind: {
                        click: 'doSignup',
                        attr: {
                            'data-control': '"signup-button"'
                        }
                    }
                }, div({
                    style: {
                        display: 'inline-block',
                        width: '50%',
                        textAlign: 'left',
                        fontWeight: 'bold',
                        verticalAlign: 'middle'
                    }
                }, [
                    span({
                        class: 'fa fa-user-plus fa-2x',
                        style: {
                            marginRight: '10px',
                            verticalAlign: 'middle'
                        }
                    }),
                    span({
                        style: {
                            verticalAlign: 'middle'
                        }
                    }, 'New User')

                ]))
            ]),
            div({
                style: {
                    marginTop: '2em'
                }
            }, [
                a({
                    dataBind: {
                        attr: {
                            href: 'docs.troubleshooting.signin'
                        }
                    }
                }, 'Need Help?')
            ])
        ]);
    }

    function buildAuthControl() {
        return div({
            style: {
                textAlign: 'center'
            }
        }, [
            buildLoginControl()
        ]);
    }

    function buildWelcomeTab() {
        return div({

        }, [
            h3({
                style: {
                    marginTop: '0'
                }
            }, 'Sign in Changes'),

            div({
                class: 'embed-container',
                style: {
                    marginBottom: '12px'
                }
            }, iframe({
                src: 'https://www.youtube.com/embed/6ql7HAUzU7U',
                frameborder: '0',
                allowfullscreen: true
            })),
            p([
                'On ',
                span({
                    dataBind: {
                        text: '$component.config.launchDate'
                    }
                }),
                ' KBase launched a new sign-in system. ',
                'One of the changes is to replace a direct login to KBase with a sign-in ',
                'system using Google and Globus for user identification.'
            ]),
            p([
                b('If you already had a KBase account'),
                ' you will now ',
                'need to sign in using Globus. After clicking the Sign In button to the right, click the Globus button that appears, follow the steps to sign in, and use your KBase username (with your KBase password) as your Globus ID.'
            ]),
            p({
                style: {
                    xfontStyle: 'italic'
                }
            }, [
                'The reason your KBase username and password work at Globus is that KBase has always ',
                'used Globus and Globus ID behind the scenes. You may remember originally signing up with Globus, ',
                'but have likely not been exposed to it since.'
            ]),
            p([
                b('If you are a new user'),
                ' you may use the identity provider most convenient for you. '
            ]),
            p([
                a({ href: 'http://kbase.us/auth-update-2017' }, 'Read more about the update')
            ])

        ]);
    }

    function buildAboutTab() {
        return div([
            p([
                'After signing in, you can start working with KBase. Upload your experimental data and perform comparative genomics and systems biology analyses by creating ',
                i('Narratives'),
                ': interactive, dynamic, and shareable documents. Narratives include all your analysis steps, commentary, and visualizations.'
            ]),
            p([
                'Want to learn more?  Check out the ',
                a({
                    dataBind: {
                        attr: {
                            href: '$component.docs.narrativeGuide.url'
                        }
                    }
                    //href: runtime.config('resources.documentation.narrativeGuide.url')
                }, 'Narrative Interface User Guide'),
                ' or the ',
                a({
                    href: 'https://youtu.be/6ql7HAUzU7U'
                }, 'Narrative Interface video tutorial'),
                ', and a ',
                a({
                    dataBind: {
                        attr: {
                            href: '$component.docs.tutorials.url'
                        }
                    }
                    // href: runtime.config('resources.documentation.tutorials.url')
                }, 'library of tutorials'),
                ' that show you how to use various KBase apps to analyze your data.'
            ]),
        ]);
    }

    function buildAuthorizationRequired() {
        return div([
            p([
                'Authorization is required to access the path: ',
                span({
                    style: {
                        fontWeight: 'bold'
                    },
                    dataBind: {
                        text: '$component.nextRequest.original'
                    }
                })
            ]),
            p([
                'After signing in you will be redirected to the requested path.'
            ])
        ]);
    }

    function buildIntroNormal() {
        return div({}, [
            buildTabs()
        ]);
    }

    function template() {
        return div({
            class: 'container-fluid component-login-view',
            dataPlugin: 'auth2-client',
            dataComponent: 'login-view',
            dataWidget: 'login'
        }, [
            div({ class: 'row' }, [
                div({ class: 'col-sm-8 ' },
                    buildIntroNormal()
                ),
                div({ class: 'col-sm-4' }, [
                    div({ class: 'well well-kbase' }, [
                        div({ class: 'login-form' }, [
                            legend({ style: 'text-align: center' }, 'Use KBase'),
                            buildAuthControl()
                        ])
                    ])
                ])
            ])
        ]);
    }

    function makeNodes(markup) {
        var node = document.createElement('div');
        node.innerHTML = markup;
        return [node.firstChild];
    }

    function viewModel(params) {
        var runtime = params.runtime;
        var nextRequest = params.nextRequest;
        var source = params.source;
        var docs = runtime.config('resources.documentation');

        var authorized = runtime.service('session').isAuthorized();

        // todo set initial value from sessino service,
        // udpate session service when the value changes.
        // var isSessionPersistent = ko.observable(runtime.service('session').getClient().isSessionPersistent());

        // isSessionPersistent.subscribe(function (persist) {
        //     runtime.service('session').getClient().setSessionPersistent(persist);
        // });

        // TODO; populate from session, as above.
        var username = runtime.service('session').getUsername();

        var providers = runtime.service('session').getProviders().sort(function (a, b) {
            if (a.id === 'Google') {
                return -1;
            } else if (b.id === 'Google') {
                return 1;
            }
            if (a.id < b.id) {
                return -1;
            } else if (a.id > b.id) {
                return 1;
            }
            return 0;
        });

        function doSignup() {
            runtime.service('session').getClient().loginCancel()
                .catch(Auth2Error.AuthError, function (err) {
                    // ignore this specific error...
                    console.warn('Skipping error', err);
                })
                .finally(function () {
                    // don't care whether it succeeded or failed.
                    runtime.send('app', 'navigate', {
                        path: 'signup'
                    });
                });
        }

        var mode = ko.observable();

        function doSetSigninMode() {
            var currentMode = mode();
            if (currentMode === 'signin') {
                mode(null);
            } else {
                mode('signin');
            }
        }

        function doSetSignupMode() {
            var currentMode = mode();
            if (currentMode === 'signup') {
                mode(null);
            } else {
                mode('signup');
            }
        }

        // var title = ko.observable();
        var tabs = ko.observableArray([{
            name: 'authorization',
            label: 'Authorization Required',
            show: ko.computed(function () {
                return (source === 'authorization');
            }),
            active: ko.observable(false),
            template: makeNodes(buildAuthorizationRequired())
        }, {
            name: 'welcome',
            label: 'Updates',
            show: true,
            active: ko.observable(false),
            template: makeNodes(buildWelcomeTab())
        }, {
            name: 'about',
            label: span({ class: 'fa fa-info-circle' }),
            show: true,
            active: ko.observable(false),
            template: makeNodes(buildAboutTab())
        }]);
        if (source === 'authorization') {
            tabs()[0].active(true);
        } else {
            tabs()[1].active(true);
        }

        function doSelectTab(data) {
            var selected = tabs().filter(function (item) {
                return item.active();
            });
            if (selected.length > 0 && selected[0].name === data.name) {
                return;
            }
            tabs().forEach(function (item) {
                if (item.active()) {
                    item.active(false);
                }
            });
            data.active(true);

        }

        var filteredTabs = tabs().filter(function (item) {
            return item.show;
        });

        return {
            runtime: runtime,
            nextRequest: nextRequest,
            assetsPath: Plugin.plugin.fullPath,
            source: source,
            docs: docs,
            // isSessionPersistent: isSessionPersistent,
            providers: providers,
            authorized: authorized,
            username: username,
            // doSignin: doSignin,
            doSignup: doSignup,
            doSetSigninMode: doSetSigninMode,
            doSetSignupMode: doSetSignupMode,
            mode: mode,
            tabs: filteredTabs,
            doSelectTab: doSelectTab,
            config: config
        };
    }

    function component() {
        return {
            template: template(),
            viewModel: viewModel
        };
    }
    ko.components.register('login-view', component());
});<commit_msg>update sign-in intro video embed<commit_after>define([
    'knockout-plus',
    'kb_common/html',
    'kb_common/bootstrapUtils',
    'kb_common_ts/Auth2Error',
    'kb_plugin_auth2-client',
    'yaml!../config.yml',
    'bootstrap'
], function (
    ko,
    html,
    BS,
    Auth2Error,
    Plugin,
    config
) {
    var t = html.tag,
        div = t('div'),
        span = t('span'),
        br = t('br', { close: false }),
        p = t('p'),
        a = t('a'),
        b = t('b'),
        button = t('button'),
        h3 = t('h3'),
        legend = t('legend'),
        i = t('i'),
        ul = t('ul'),
        li = t('li'),
        iframe = t('iframe');

    function buildTabs() {
        return div({}, [
            ul({
                class: 'nav nav-tabs',
                role: 'tablist',
                dataBind: {
                    foreach: 'tabs'
                }
            }, [
                '<!-- ko if: show -->',
                li({
                    role: 'presentation',
                    style: {
                        fontWeight: 'bold'
                    },
                    dataBind: {
                        css: {
                            active: 'active'
                        }
                    }
                }, a({
                    dataBind: {
                        attrs: {
                            id: 'name',
                            href: '"#" + name'
                        },
                        html: 'label',
                        click: '$component.doSelectTab'
                    }
                })),
                '<!-- /ko -->'
            ]),
            div({
                class: 'tab-content',
                dataBind: {
                    foreach: 'tabs'
                }
            }, [
                '<!-- ko if: show -->',
                div({
                    role: 'tabpanel',
                    class: 'tab-pane',
                    style: {
                        paddingTop: '10px'
                    },
                    dataBind: {
                        css: {
                            active: 'active'
                        },
                        attrs: {
                            id: 'name'
                        },
                        template: {
                            nodes: 'template'
                        }
                    }
                }),
                '<!-- /ko -->'
            ])
        ]);
    }

    function buildLoginControl(runtime) {
        return div({
            dataBind: {
                ifnot: 'authorized'
            },
            style: {
                width: '80%',
                display: 'inline-block',
                minWidth: '210px'
            }
        }, [
            div({
                class: 'btn-group-vertical',
                style: {
                    width: '100%'
                },
                minWidth: '200px'
            }, [
                button({
                    class: 'btn btn-default',
                    style: {
                        textAlign: 'center'
                    },
                    dataBind: {
                        click: 'doSetSigninMode',
                        css: {
                            active: 'mode() === "signin"'
                        },
                        attr: {
                            'data-control': '"signin-button"'
                        }
                    }
                }, div({
                    style: {
                        display: 'inline-block',
                        width: '50%',
                        textAlign: 'left',
                        fontWeight: 'bold',
                        verticalAlign: 'middle'
                    }
                }, [
                    span({
                        class: 'fa fa-sign-in fa-2x',
                        style: {
                            marginRight: '10px',
                            verticalAlign: 'middle'
                        }
                    }),
                    span({
                        style: {
                            verticalAlign: 'middle'
                        }
                    }, 'Sign In')

                ])),
                div({
                        dataBind: {
                            visible: 'mode() === "signin"'
                        }
                    },
                    div({
                        style: {
                            marginBottom: '20px',
                            padding: '4px',
                            // borderBottom: '1px silver solid',
                            backgroundColor: '#DDD',
                            textAlign: 'left'
                        }
                    }, [
                        div({
                            style: {
                                margin: '6px 0 0 0',
                                fontStyle: 'italic',
                                textAlign: 'center'
                            }
                        }, [
                            'Choose Globus if you signed up',
                            br(),
                            'before ',
                            span({
                                dataBind: {
                                    text: '$component.config.launchDate'
                                }
                            })
                        ]),
                        div({
                            // class: 'btn-group-vertical',
                            style: {
                                width: '100%',
                                display: 'inline-block',
                            },
                            dataBind: {
                                foreach: 'providers'
                            }
                        }, div({
                            dataBind: {
                                component: {
                                    name: '"signin-button"',
                                    params: {
                                        provider: '$data',
                                        runtime: '$component.runtime',
                                        nextRequest: '$component.nextRequest',
                                        assetsPath: '$component.assetsPath',
                                        origin: '"login"'
                                    }
                                }
                            }
                        }))
                        // div({
                        //     style: {
                        //         marginTop: '0.5em',
                        //         textAlign: 'center'
                        //     }
                        // }, [
                        //     input({
                        //         type: 'checkbox',
                        //         dataBind: {
                        //             checked: 'isSessionPersistent',

                        //         },
                        //     }),
                        //     ' Stay signed in'
                        // ]),
                    ])),
                button({
                    class: 'btn btn-default',
                    style: {
                        textAlign: 'center',
                        marginTop: '10px'
                    },
                    dataBind: {
                        click: 'doSignup',
                        attr: {
                            'data-control': '"signup-button"'
                        }
                    }
                }, div({
                    style: {
                        display: 'inline-block',
                        width: '50%',
                        textAlign: 'left',
                        fontWeight: 'bold',
                        verticalAlign: 'middle'
                    }
                }, [
                    span({
                        class: 'fa fa-user-plus fa-2x',
                        style: {
                            marginRight: '10px',
                            verticalAlign: 'middle'
                        }
                    }),
                    span({
                        style: {
                            verticalAlign: 'middle'
                        }
                    }, 'New User')

                ]))
            ]),
            div({
                style: {
                    marginTop: '2em'
                }
            }, [
                a({
                    dataBind: {
                        attr: {
                            href: 'docs.troubleshooting.signin'
                        }
                    }
                }, 'Need Help?')
            ])
        ]);
    }

    function buildAuthControl() {
        return div({
            style: {
                textAlign: 'center'
            }
        }, [
            buildLoginControl()
        ]);
    }

    function buildWelcomeTab() {
        return div({

        }, [
            h3({
                style: {
                    marginTop: '0'
                }
            }, 'Sign in Changes'),

            div({
                class: 'embed-container',
                style: {
                    marginBottom: '12px'
                }
            }, iframe({
                src: 'https://www.youtube.com/embed/RkqrCqoAPMo',
                frameborder: '0',
                allowfullscreen: true
            })),
            p([
                'On ',
                span({
                    dataBind: {
                        text: '$component.config.launchDate'
                    }
                }),
                ' KBase launched a new sign-in system. ',
                'One of the changes is to replace a direct login to KBase with a sign-in ',
                'system using Google and Globus for user identification.'
            ]),
            p([
                b('If you already had a KBase account'),
                ' you will now ',
                'need to sign in using Globus. After clicking the Sign In button to the right, click the Globus button that appears, follow the steps to sign in, and use your KBase username (with your KBase password) as your Globus ID.'
            ]),
            p({
                style: {
                    xfontStyle: 'italic'
                }
            }, [
                'The reason your KBase username and password work at Globus is that KBase has always ',
                'used Globus and Globus ID behind the scenes. You may remember originally signing up with Globus, ',
                'but have likely not been exposed to it since.'
            ]),
            p([
                b('If you are a new user'),
                ' you may use the identity provider most convenient for you. '
            ]),
            p([
                a({ href: 'http://kbase.us/auth-update-2017' }, 'Read more about the update')
            ])

        ]);
    }

    function buildAboutTab() {
        return div([
            p([
                'After signing in, you can start working with KBase. Upload your experimental data and perform comparative genomics and systems biology analyses by creating ',
                i('Narratives'),
                ': interactive, dynamic, and shareable documents. Narratives include all your analysis steps, commentary, and visualizations.'
            ]),
            p([
                'Want to learn more?  Check out the ',
                a({
                    dataBind: {
                        attr: {
                            href: '$component.docs.narrativeGuide.url'
                        }
                    }
                    //href: runtime.config('resources.documentation.narrativeGuide.url')
                }, 'Narrative Interface User Guide'),
                ' or the ',
                a({
                    href: 'https://youtu.be/6ql7HAUzU7U'
                }, 'Narrative Interface video tutorial'),
                ', and a ',
                a({
                    dataBind: {
                        attr: {
                            href: '$component.docs.tutorials.url'
                        }
                    }
                    // href: runtime.config('resources.documentation.tutorials.url')
                }, 'library of tutorials'),
                ' that show you how to use various KBase apps to analyze your data.'
            ]),
        ]);
    }

    function buildAuthorizationRequired() {
        return div([
            p([
                'Authorization is required to access the path: ',
                span({
                    style: {
                        fontWeight: 'bold'
                    },
                    dataBind: {
                        text: '$component.nextRequest.original'
                    }
                })
            ]),
            p([
                'After signing in you will be redirected to the requested path.'
            ])
        ]);
    }

    function buildIntroNormal() {
        return div({}, [
            buildTabs()
        ]);
    }

    function template() {
        return div({
            class: 'container-fluid component-login-view',
            dataPlugin: 'auth2-client',
            dataComponent: 'login-view',
            dataWidget: 'login'
        }, [
            div({ class: 'row' }, [
                div({ class: 'col-sm-8 ' },
                    buildIntroNormal()
                ),
                div({ class: 'col-sm-4' }, [
                    div({ class: 'well well-kbase' }, [
                        div({ class: 'login-form' }, [
                            legend({ style: 'text-align: center' }, 'Use KBase'),
                            buildAuthControl()
                        ])
                    ])
                ])
            ])
        ]);
    }

    function makeNodes(markup) {
        var node = document.createElement('div');
        node.innerHTML = markup;
        return [node.firstChild];
    }

    function viewModel(params) {
        var runtime = params.runtime;
        var nextRequest = params.nextRequest;
        var source = params.source;
        var docs = runtime.config('resources.documentation');

        var authorized = runtime.service('session').isAuthorized();

        // todo set initial value from sessino service,
        // udpate session service when the value changes.
        // var isSessionPersistent = ko.observable(runtime.service('session').getClient().isSessionPersistent());

        // isSessionPersistent.subscribe(function (persist) {
        //     runtime.service('session').getClient().setSessionPersistent(persist);
        // });

        // TODO; populate from session, as above.
        var username = runtime.service('session').getUsername();

        var providers = runtime.service('session').getProviders().sort(function (a, b) {
            if (a.id === 'Google') {
                return -1;
            } else if (b.id === 'Google') {
                return 1;
            }
            if (a.id < b.id) {
                return -1;
            } else if (a.id > b.id) {
                return 1;
            }
            return 0;
        });

        function doSignup() {
            runtime.service('session').getClient().loginCancel()
                .catch(Auth2Error.AuthError, function (err) {
                    // ignore this specific error...
                    console.warn('Skipping error', err);
                })
                .finally(function () {
                    // don't care whether it succeeded or failed.
                    runtime.send('app', 'navigate', {
                        path: 'signup'
                    });
                });
        }

        var mode = ko.observable();

        function doSetSigninMode() {
            var currentMode = mode();
            if (currentMode === 'signin') {
                mode(null);
            } else {
                mode('signin');
            }
        }

        function doSetSignupMode() {
            var currentMode = mode();
            if (currentMode === 'signup') {
                mode(null);
            } else {
                mode('signup');
            }
        }

        // var title = ko.observable();
        var tabs = ko.observableArray([{
            name: 'authorization',
            label: 'Authorization Required',
            show: ko.computed(function () {
                return (source === 'authorization');
            }),
            active: ko.observable(false),
            template: makeNodes(buildAuthorizationRequired())
        }, {
            name: 'welcome',
            label: 'Updates',
            show: true,
            active: ko.observable(false),
            template: makeNodes(buildWelcomeTab())
        }, {
            name: 'about',
            label: span({ class: 'fa fa-info-circle' }),
            show: true,
            active: ko.observable(false),
            template: makeNodes(buildAboutTab())
        }]);
        if (source === 'authorization') {
            tabs()[0].active(true);
        } else {
            tabs()[1].active(true);
        }

        function doSelectTab(data) {
            var selected = tabs().filter(function (item) {
                return item.active();
            });
            if (selected.length > 0 && selected[0].name === data.name) {
                return;
            }
            tabs().forEach(function (item) {
                if (item.active()) {
                    item.active(false);
                }
            });
            data.active(true);

        }

        var filteredTabs = tabs().filter(function (item) {
            return item.show;
        });

        return {
            runtime: runtime,
            nextRequest: nextRequest,
            assetsPath: Plugin.plugin.fullPath,
            source: source,
            docs: docs,
            // isSessionPersistent: isSessionPersistent,
            providers: providers,
            authorized: authorized,
            username: username,
            // doSignin: doSignin,
            doSignup: doSignup,
            doSetSigninMode: doSetSigninMode,
            doSetSignupMode: doSetSignupMode,
            mode: mode,
            tabs: filteredTabs,
            doSelectTab: doSelectTab,
            config: config
        };
    }

    function component() {
        return {
            template: template(),
            viewModel: viewModel
        };
    }
    ko.components.register('login-view', component());
});<|endoftext|>


<commit_before>window.Recipe = Backbone.Model.extend({

});<commit_msg>experimenting with the RecipeView<commit_after>window.Recipe = Backbone.Model.extend({

});

window.RecipeView = Backbone.View.extend({
	initialize: function(){
		this.template = _.template($('#recipeTemplate').html());
	},

	render: function(){
		var renderedContent = this.template(this.model.toJSON());
		$(this.el).html(renderedContent);
		return this;
	}
});
<|endoftext|>


<commit_before>/* get GPS coordinates from Phone */

var locationOptions = {
  enableHighAccuracy: false,
  maximumAge: 10000,
  timeout: 60000
};

function locationSuccess(pos) {
  // sendAppMessage converts values to uin32_t therefore convert to int
  var coordinates = pos.coords;
  Pebble.sendAppMessage({"longitude": Math.round(coordinates.longitude * 1000000),
                         "latitude":  Math.round(coordinates.latitude * 1000000)});

}

function locationError(err) {
  // GPS_INVALID = 99999
  Pebble.sendAppMessage({"longitude": 99999,
                         "latitude":  99999});
}

Pebble.addEventListener('appmessage',
  function(e) {
    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
  }
);

Pebble.addEventListener('ready',
  function(e) {
    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
  }
);
<commit_msg>increase GPS Age<commit_after>/* get GPS coordinates from Phone */

var locationOptions = {
  enableHighAccuracy: false,
  maximumAge: 600000,
  timeout: 60000
};

function locationSuccess(pos) {
  // sendAppMessage converts values to uin32_t therefore convert to int
  var coordinates = pos.coords;
  Pebble.sendAppMessage({"longitude": Math.round(coordinates.longitude * 1000000),
                         "latitude":  Math.round(coordinates.latitude * 1000000)});

}

function locationError(err) {
  // GPS_INVALID = 99999
  Pebble.sendAppMessage({"longitude": 99999,
                         "latitude":  99999});
}

Pebble.addEventListener('appmessage',
  function(e) {
    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
  }
);

Pebble.addEventListener('ready',
  function(e) {
    navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
  }
);
<|endoftext|>


<commit_before>import React from 'react'
import Plugin from '../Plugin'
import ConsolePanel from './ConsolePanel'

export default class ConsolePlugin extends Plugin {
  constructor (id, name) {
    super(id, name)
    this.ref = null
    this.eventBuffer = []
    // Hold native console object
    this.console = this.hookConsole()
  }

  // Hook native console methods
  hookConsole () {
    const console = {}
    const names = ['log', 'info', 'error', 'warn', 'debug', 'clear']
    names.forEach(name => {
      // save native console methods
      console[name] = window.console[name]

      window.console[name] = (...args) => {
        let _level = name
        let _args = args
        if (name === 'clear') {
          _level = 'clear'
          _args = ['Console was cleared']
        }
        const event = this.xConsole.createEvent('console', {level: _level, args: _args})
        this.onEvent(event)

        // call native console method
        console[name](...args)
      }
    })
    return console
  }

  onEvent (event) {
    // Only focus on console event
    if (!event || event.type !== 'console') return

    // Save console event data before plugin mounted
    if (!this.ref) {
      this.eventBuffer.push(event)
      return
    }

    event.detail = event.detail || {}
    switch (event.detail.level) {
      // 'console.clear()' event
      case 'clear':
        this.eventBuffer.length = 0
        this.ref.setState({ events: [event] })
        return
    }

    // Show console event on UI
    this.ref.setState((preState, props) => {
      return { events: [...preState.events, event] }
    })
  }

  render () {
    const eventBuffer = this.eventBuffer
    this.eventBuffer.length = 0

    return (
      <ConsolePanel
        eventBuffer={eventBuffer}
        ref={ref => (this.ref = ref)}
      />
    )
  }
}
<commit_msg>refactor(ConsolePlugin): improve code readability<commit_after>import React from 'react'
import Plugin from '../Plugin'
import ConsolePanel from './ConsolePanel'

export default class ConsolePlugin extends Plugin {
  constructor (id, name) {
    super(id, name)
    this.ref = null
    this.eventBuffer = []
    // Hold native console object
    this.console = this.hookConsole()
  }

  // Hook native console methods
  hookConsole () {
    const console = {}
    const methodNames = ['log', 'info', 'error', 'warn', 'debug', 'clear']
    methodNames.forEach(name => {
      // save native console methods
      console[name] = window.console[name]

      // hook console methods
      window.console[name] = (...args) => {
        let event
        switch (name) {
          case 'log':
          case 'info':
          case 'error':
          case 'warn':
          case 'debug':
            event = this.xConsole.createEvent('console', {
              level: name,
              args
            })
            break
          case 'clear':
            event = this.xConsole.createEvent('console', {
              level: name,
              args: ['Console was cleared']
            })
            break
          default:
            event = null
            break
        }

        // trigger event if it's not null
        if (event) {
          this.onEvent(event)
        }

        // call native console method
        console[name](...args)
      }
    })
    return console
  }

  onEvent (event) {
    // Only focus on console event
    if (!event || event.type !== 'console') return

    // Save console event data before plugin mounted
    if (!this.ref) {
      this.eventBuffer.push(event)
      return
    }

    event.detail = event.detail || {}
    switch (event.detail.level) {
      // 'console.clear()' event
      case 'clear':
        this.eventBuffer.length = 0
        this.ref.setState({ events: [event] })
        return
    }

    // Show console event on UI
    this.ref.setState((preState, props) => {
      return { events: [...preState.events, event] }
    })
  }

  render () {
    const eventBuffer = this.eventBuffer
    this.eventBuffer.length = 0

    return (
      <ConsolePanel
        eventBuffer={eventBuffer}
        ref={ref => (this.ref = ref)}
      />
    )
  }
}
<|endoftext|>


<commit_before>var send;
var shares = {};

if (!window.console) {
    var stub = function() { };
    window.console = { log: stub, warn: stub, error: stub };
}

function humanSize(size) {
    var units = ['T', 'G', 'M', 'K'];
    var unit = '';
    while(size >= 1024 && units.length > 0) {
	size /= 1024;
	unit = units.pop();
    }
    return (Math.round(size * 10) / 10) + ' ' +
	unit + 'B';
}

function Share(file, shareInfo) {
    var that = this;

    this.id = shareInfo.id;
    this.file = file;
    this.name = shareInfo.name;

    var div = $('

 ×

');
    div.find('.name').text(shareInfo.name);
    div.find('.size').text(humanSize(shareInfo.size));
    div.find('a.remove').click(function(ev) {
	ev.preventDefault();
	that.remove();
    });
    $('#shares').append(div);
    this.div = div;
}

Share.prototype.remove = function() {
    var div = this.div;
    div.slideUp(250, function() {
	div.remove();
    });

    send({ unshare: { id: this.id } });
    delete shares[this.id];
    delete fileCache[this.name];
};

Share.prototype.upload = function(token, by) {
    var that = this;

    var up = new UploadProgress(this.div, by);
    var shut = function() {
	console.log({shut:arguments});
	up.end();
    };
    var reader = new FileReader();
    reader.onload = function() {
	console.log('read '+reader.result.length);

	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
console.log('readyState: '+xhr.readyState);
	    if (xhr.readyState === 4)  // DONE
		shut();
	};
	up.trackXHR(xhr);
console.log('post to '+document.location.pathname + '/f' + that.id + '/' + token);
	xhr.open("POST",
		 document.location.pathname + '/f' + that.id + '/' + token);
	xhr.send(window.btoa(reader.result));
    };
    reader.onabort = shut;
    reader.onerror = shut;
    // give some time to render UploadProgress
    window.setTimeout(function() {
	console.log({reader:that.file});
	reader.readAsBinaryString(that.file);
    }, 10);
};

function UploadProgress(parent, by) {
    var p = $('
<canvas width="100" height="16"></canvas>
');
    this.p = p;
    parent.append(p);

    if (by)
	p.find('.by').text(by);

    this.progress = -1;
    this.draw();
}

UploadProgress.prototype.draw = function() {
    if (!this.canvas)
	this.canvas = this.p.find('canvas')[0];
    var ctx = this.canvas.getContext('2d');
    var w = this.canvas.width, h = this.canvas.height;

    ctx.clearRect(0, 0, w, h);

    ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.lineWidth = 1;
    var line = function(x1, y1, x2, y2) {
	ctx.moveTo(x1, y1);
	ctx.lineTo(x2, y2);
	ctx.stroke();
    };

    /*line(0, 1, 0, h - 2);  // left
    line(1, 0, w - 2, 0);  // top
    line(1, h - 1, w - 2, h - 1);  // bottom
    line(w - 1, 1, w - 1, h - 2);  // right*/

    if (this.progress < 0) {
	ctx.globalAlpha = 0.2;
	ctx.fillStyle = '#800000';
	ctx.fillRect(1, 1, w - 2, h - 2);
    } else {
	ctx.globalAlpha = 0.8;
	ctx.fillStyle = '#AA0000';
	ctx.fillRect(1, 1, this.progress * (w - 2), h - 2);
    }
};

UploadProgress.prototype.trackXHR = function(xhr, by) {
    var that = this;

    if (!xhr.upload) {
	console.error('not receiving upload notifications');
	this.end();
	return;
    }

    xhr.upload.onloadstart = function() {
	that.progress = 0;
	that.draw();
    };
    xhr.upload.onprogress = function(ev) {
	that.progress = ev.loaded / ev.total;
	that.draw();
    };
    xhr.upload.onloadend = function() {
	console.log('onloadend');
	that.progress = 1;
	that.end();
    };
};

UploadProgress.prototype.end = function() {
console.log('up end');
    var p = this.p;
    p.fadeOut(1000, function() {
console.log('up remove');
	p.remove();
console.log('up removed');
    });
    this.draw();
};

function RemoteShare(shareInfo) {
    var li = $('

');
    var a = li.find('a');
    a.text(shareInfo.name);
    a.attr('href', document.location.pathname + '/f' + shareInfo.id);
    var size = li.find('.size');
    size.text(humanSize(shareInfo.size));
    if (shareInfo.by) {
	var by = $('');
	by.text(shareInfo.by);
	li.find('.meta').append(' by ').append(by);
    }

    li.hide();
    li.slideDown(500);
    $('#remote').append(li);

    this.li = li;
    this.id = shareInfo.id;
}

RemoteShare.prototype.remove = function() {
    this.li.remove();
    delete shares[this.id];
};

var fileCache = {};

function fileChosen(ev) {
    var files = $('#file')[0].files;
    for(var i = 0; i < files.length; i++) {
	var file = files.item(i);
	fileCache[file.name] = file;

	send({ share: { name: file.name,
			size: file.size,
			type: file.type } });
    }
    $('#file')[0].value = null;
};

var socket = null;
function connect() {
    if (socket !== null)
	return;

    socket = new io.Socket(null,
			   { transports: ['websocket', 'htmlfile',
			                  'xhr-multipart', 'xhr-polling']
			   });
    var currentSocket = socket;
console.log(socket);
    socket.connect();

    send = function(json) {
	socket.send(JSON.stringify(json));
    };

    socket.on('connect', function(){
	send({ join: document.location.pathname });
	$('#loading').hide();
	$('#dashboard').show();
    });
    socket.on('message', function(data){
console.log(data);
	var json;
	try {
	    json = JSON.parse(data);
	} catch (x) {
	    console.error("Cannot parse: " + data);
	    return;
	}

	if (json.shared && json.shared.id !== null) {
	    // Own share confirmed
	    if (fileCache[json.shared.name]) {
		shares[json.shared.id] = new Share(fileCache[json.shared.name], json.shared);
	    } else {
		send({ unshare: { id: json.shared.id } });
	    }
	}
	if (json.share && json.share.id) {
	    // New remote share
	    shares[json.share.id] = new RemoteShare(json.share);
	}
	if (json.transfer) {
	    // TODO: implement long path for error case
	    shares[json.transfer.id].upload(json.transfer.token, json.transfer.by);
	}
	if (json.unshare &&
	    json.unshare.id &&
	    shares.hasOwnProperty(json.unshare.id)) {
	    // already removes itself from shares & the DOM
	    shares[json.unshare.id].remove();
	}
    });

    var reconnect = function() {
console.log({reconnect:arguments});
	$('#dashboard').hide();
	$('#loading').show();

	if (socket === currentSocket)
	    socket = null;
	window.setTimeout(connect, Math.ceil((0.5 + 3 * Math.random()) * 1000));
    };
    socket.on('error',  reconnect);
    socket.on('close', reconnect);

socket.on('close', function() { console.log('close'); });
socket.on('error', function() { console.log('error'); });
}

$(document).ready(function() {
    connect();

    /* New file */
    $('#file').bind('change', fileChosen);
});

<commit_msg>style: wider <canvas><commit_after>var send;
var shares = {};

if (!window.console) {
    var stub = function() { };
    window.console = { log: stub, warn: stub, error: stub };
}

function humanSize(size) {
    var units = ['T', 'G', 'M', 'K'];
    var unit = '';
    while(size >= 1024 && units.length > 0) {
	size /= 1024;
	unit = units.pop();
    }
    return (Math.round(size * 10) / 10) + ' ' +
	unit + 'B';
}

function Share(file, shareInfo) {
    var that = this;

    this.id = shareInfo.id;
    this.file = file;
    this.name = shareInfo.name;

    var div = $('

 ×

');
    div.find('.name').text(shareInfo.name);
    div.find('.size').text(humanSize(shareInfo.size));
    div.find('a.remove').click(function(ev) {
	ev.preventDefault();
	that.remove();
    });
    $('#shares').append(div);
    this.div = div;
}

Share.prototype.remove = function() {
    var div = this.div;
    div.slideUp(250, function() {
	div.remove();
    });

    send({ unshare: { id: this.id } });
    delete shares[this.id];
    delete fileCache[this.name];
};

Share.prototype.upload = function(token, by) {
    var that = this;

    var up = new UploadProgress(this.div, by);
    var shut = function() {
	console.log({shut:arguments});
	up.end();
    };
    var reader = new FileReader();
    reader.onload = function() {
	console.log('read '+reader.result.length);

	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
console.log('readyState: '+xhr.readyState);
	    if (xhr.readyState === 4)  // DONE
		shut();
	};
	up.trackXHR(xhr);
console.log('post to '+document.location.pathname + '/f' + that.id + '/' + token);
	xhr.open("POST",
		 document.location.pathname + '/f' + that.id + '/' + token);
	xhr.send(window.btoa(reader.result));
    };
    reader.onabort = shut;
    reader.onerror = shut;
    // give some time to render UploadProgress
    window.setTimeout(function() {
	console.log({reader:that.file});
	reader.readAsBinaryString(that.file);
    }, 10);
};

function UploadProgress(parent, by) {
    var p = $('
<canvas width="160" height="16"></canvas>
');
    this.p = p;
    parent.append(p);

    if (by)
	p.find('.by').text(by);

    this.progress = -1;
    this.draw();
}

UploadProgress.prototype.draw = function() {
    if (!this.canvas)
	this.canvas = this.p.find('canvas')[0];
    var ctx = this.canvas.getContext('2d');
    var w = this.canvas.width, h = this.canvas.height;

    ctx.clearRect(0, 0, w, h);

    ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.lineWidth = 1;
    var line = function(x1, y1, x2, y2) {
	ctx.moveTo(x1, y1);
	ctx.lineTo(x2, y2);
	ctx.stroke();
    };

    /*line(0, 1, 0, h - 2);  // left
    line(1, 0, w - 2, 0);  // top
    line(1, h - 1, w - 2, h - 1);  // bottom
    line(w - 1, 1, w - 1, h - 2);  // right*/

    if (this.progress < 0) {
	ctx.globalAlpha = 0.2;
	ctx.fillStyle = '#800000';
	ctx.fillRect(1, 1, w - 2, h - 2);
    } else {
	ctx.globalAlpha = 0.8;
	ctx.fillStyle = '#AA0000';
	ctx.fillRect(1, 1, this.progress * (w - 2), h - 2);
    }
};

UploadProgress.prototype.trackXHR = function(xhr, by) {
    var that = this;

    if (!xhr.upload) {
	console.error('not receiving upload notifications');
	this.end();
	return;
    }

    xhr.upload.onloadstart = function() {
	that.progress = 0;
	that.draw();
    };
    xhr.upload.onprogress = function(ev) {
	that.progress = ev.loaded / ev.total;
	that.draw();
    };
    xhr.upload.onloadend = function() {
	console.log('onloadend');
	that.progress = 1;
	that.end();
    };
};

UploadProgress.prototype.end = function() {
console.log('up end');
    var p = this.p;
    p.fadeOut(1000, function() {
console.log('up remove');
	p.remove();
console.log('up removed');
    });
    this.draw();
};

function RemoteShare(shareInfo) {
    var li = $('

');
    var a = li.find('a');
    a.text(shareInfo.name);
    a.attr('href', document.location.pathname + '/f' + shareInfo.id);
    var size = li.find('.size');
    size.text(humanSize(shareInfo.size));
    if (shareInfo.by) {
	var by = $('');
	by.text(shareInfo.by);
	li.find('.meta').append(' by ').append(by);
    }

    li.hide();
    li.slideDown(500);
    $('#remote').append(li);

    this.li = li;
    this.id = shareInfo.id;
}

RemoteShare.prototype.remove = function() {
    this.li.remove();
    delete shares[this.id];
};

var fileCache = {};

function fileChosen(ev) {
    var files = $('#file')[0].files;
    for(var i = 0; i < files.length; i++) {
	var file = files.item(i);
	fileCache[file.name] = file;

	send({ share: { name: file.name,
			size: file.size,
			type: file.type } });
    }
    $('#file')[0].value = null;
};

var socket = null;
function connect() {
    if (socket !== null)
	return;

    socket = new io.Socket(null,
			   { transports: ['websocket', 'htmlfile',
			                  'xhr-multipart', 'xhr-polling']
			   });
    var currentSocket = socket;
console.log(socket);
    socket.connect();

    send = function(json) {
	socket.send(JSON.stringify(json));
    };

    socket.on('connect', function(){
	send({ join: document.location.pathname });
	$('#loading').hide();
	$('#dashboard').show();
    });
    socket.on('message', function(data){
console.log(data);
	var json;
	try {
	    json = JSON.parse(data);
	} catch (x) {
	    console.error("Cannot parse: " + data);
	    return;
	}

	if (json.shared && json.shared.id !== null) {
	    // Own share confirmed
	    if (fileCache[json.shared.name]) {
		shares[json.shared.id] = new Share(fileCache[json.shared.name], json.shared);
	    } else {
		send({ unshare: { id: json.shared.id } });
	    }
	}
	if (json.share && json.share.id) {
	    // New remote share
	    shares[json.share.id] = new RemoteShare(json.share);
	}
	if (json.transfer) {
	    // TODO: implement long path for error case
	    shares[json.transfer.id].upload(json.transfer.token, json.transfer.by);
	}
	if (json.unshare &&
	    json.unshare.id &&
	    shares.hasOwnProperty(json.unshare.id)) {
	    // already removes itself from shares & the DOM
	    shares[json.unshare.id].remove();
	}
    });

    var reconnect = function() {
console.log({reconnect:arguments});
	$('#dashboard').hide();
	$('#loading').show();

	if (socket === currentSocket)
	    socket = null;
	window.setTimeout(connect, Math.ceil((0.5 + 3 * Math.random()) * 1000));
    };
    socket.on('error',  reconnect);
    socket.on('close', reconnect);

socket.on('close', function() { console.log('close'); });
socket.on('error', function() { console.log('error'); });
}

$(document).ready(function() {
    connect();

    /* New file */
    $('#file').bind('change', fileChosen);
});

<|endoftext|>


<commit_before>Pebble.addEventListener("ready",
    function(e) {
        console.log("Hello world! - Sent from your javascript application.");
    }
);
<commit_msg>Add a functionnal Ajax module<commit_after>Pebble.addEventListener("ready",
    function(e) {
        console.log("Hello world! - Sent from your javascript application.");
        var data = {
            url: "http://api.open-notify.org/iss-now.json",
            type: "GET"
        };
    });

Ajax = (function() {
    var requestObject = new XMLHttpRequest();
    var _formatData = function(data) {
        data.type = data.type || "GET";
        return data;
    };

    var _request = function(data, okCallback, errorCallback) {
        data = _formatData(data);
        requestObject.open(data.type, data.url, true);
        requestObject.onreadystatechange = function(e) {
            if (requestObject.readyState == 4) {
                var response = JSON.parse(requestObject.responseText);
                if (requestObject.status == 200) {
                    console.log(requestObject);
                    okCallback(response);
                } else {

                    console.log(response);
                    errorCallback(response);
                }
            }
        };
        requestObject.send();
    };

    return {
        request: function(data, okCallback, errorCallback) {
            _request(data, okCallback, errorCallback);
        }
    };
}());<|endoftext|>


<commit_before>var utils = require('../utils');
var settings = require('../settings');
var playMenu = {};

var isOpen = false;
var newGameCardSwapped = false;

playMenu.open = function() {
  isOpen = true;
};

playMenu.close = function() {
  isOpen = false;
};

function swapCard() {
  newGameCardSwapped = !newGameCardSwapped;
}

// see game.styl for dimensions
function boardHeight() {
  return utils.getViewportDims().vw * 80 / 100;
}

// see game.styl for dimensions
function cardHeight() {
  return boardHeight() + 144;
}

function renderRadio(label, name, value, settingsProp) {
  var isOn = settingsProp() === value;
  var id = name + value;
  return [
    m('input.radio[type=radio]', {
      name: name,
      id: id,
      'class': value,
      value: value,
      checked: isOn,
      onchange: function(e) {
        settingsProp(e.target.value);
      }
    }),
    m('label', { 'for': id }, label) ];
}

function renderCheckbox(label, name, settingsProp) {
  var isOn = settingsProp();
  return [
    m('label', { 'for': name }, label),
    m('input[type=checkbox]', {
      name: name,
      checked: isOn,
      onchange: function() {
        settingsProp(!isOn);
      }
    })
  ];
}

function renderOption(label, value, storedValue) {
  return m('option', {
    value: value,
    selected: storedValue === value
  }, label);
}

function renderSelect(label, name, options, settingsProp, isDisabled) {
  var storedValue = settingsProp();
  return [
    m('label', { 'for': name }, label),
    m('select', {
      name: name,
      disabled: isDisabled,
      onchange: function(e) { settingsProp(e.target.value); }
    }, options.map(function(e) {
      return renderOption(e[0], e[1], storedValue); })
    )
  ];
}

function renderForm(action, settingsObj) {
  var timeMode = settingsObj.timeMode();
  var hasClock = timeMode === '1';
  var hasCorresp = timeMode === '2';

  var generalFieldset = [
    m('div.select_input',[
      renderSelect('Color:', 'color', [
        ['White', 'white'], ['Black', 'black'], ['Random', 'random']
      ], settingsObj.color),
    ]),
    m('div.select_input', [
      renderSelect('Variant:', 'variant', [
        ['Standard', '1'], ['Chess 960', '2'], ['King of the hill', '4']
      ], settingsObj.variant),
    ])
  ];
  if (settingsObj.level) {
    generalFieldset.push(m('div.select_input', [
      renderSelect('Level:', 'ailevel', [
        ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'],
        ['6', '6'], ['7','7'], ['8','8']
      ], settingsObj.level)
    ]));
  }
  if (settingsObj.mode) {
    generalFieldset.push(m('div.select_input', [
      renderSelect('Mode:', 'mode', [
        ['Casual', '0'], ['Rated', '1']
      ], settingsObj.mode)
    ]));
  }

  var timeFieldset = [
    m('div.select_input', [
      renderSelect('Time mode:', 'timeMode', [
        ['Unlimited', '0'], ['Clock', '1'], ['Correspondance', '2']
      ], settingsObj.timeMode)
    ])
  ];
  if (settingsObj.time && settingsObj.increment && hasClock) {
    timeFieldset.push(
      m('div.select_input.inline',[
        renderSelect('Time:', 'time', [
          ['5', '5'], ['10', '10'], ['30', '30']
        ], settingsObj.time, false)
      ]),
      m('div.select_input.inline',[
        renderSelect('Increment:', 'increment', [
          ['0', '0'], ['1', '1'], ['3', '3']
        ], settingsObj.increment, false)
      ])
    );
  }
  if (settingsObj.timePreset && hasClock) {
    timeFieldset.push(m('div.select_input',[
      renderSelect('Time|increment:', 'timepreset', [
        ['3|0', '3|0'], ['3|2', '3|2'], ['5|0', '5|0'], ['5|3', '5|3'],
        ['10|0', '10|0'], ['30|0']
      ], settingsObj.timePreset, false)
    ]));
  }
  if (hasCorresp) {
    timeFieldset.push(m('div.select_input',[
      renderSelect('Days per turn:', 'days', [
        ['1', '1'], ['2', '2'], ['3', '3'], ['5', '5'], ['7', '7'], ['10', '10'],
        ['14', '14']
      ], settingsObj.days, false)
    ]));
  }

  return m('form.form', {
    onsubmit: function(e) {
      e.preventDefault();
      playMenu.close();
      swapCard();
      action();
    }
  }, [
    m('fieldset', [
      m('div.nice-radio', renderRadio('Human', 'selected', 'human', settings.newGame.selected)),
      m('div.nice-radio', renderRadio('Computer', 'selected', 'computer', settings.newGame.selected))
    ]),
    m('fieldset', generalFieldset),
    m('fieldset#clock', timeFieldset),
    m('button', 'Valider')
  ]);
}

playMenu.view = function(ctrl) {
  var children = [
    m('div.overlay-close',
      { config: utils.ontouchstart(playMenu.close) },
    '+'),
    m('div.card.new-game', {
      class: newGameCardSwapped ? 'back_visible' : '',
      style: { height: cardHeight() + 'px' }
    }, [
      m('div.container_flip', [
        m('div.front', [
          m('div', { style: { height: boardHeight() + 'px' }}, [
            utils.viewOnlyBoard()
          ]),
          m('div.infos',[
            m('div.description',[
              m('h2.title', 'New Game'),
              m('p', 'Lancer une nouvelle partie'),
              m('button', { config: utils.ontouchstart(swapCard) }, '+ Nouvelle partie')
            ])
          ])
        ]),
        m('div.back', [
          settings.newGame.selected() === 'human' ?
            renderForm(ctrl.seekHumanGame, settings.newGame.human) :
            renderForm(ctrl.startAIGame, settings.newGame.ai)
        ])
      ])
    ])
  ];

  return m('div#game_menu.overlay.overlay-effect', {
    class: isOpen ? 'open' : '',
  }, children);
};

module.exports = playMenu;
<commit_msg>remove unused function renderCheckbox<commit_after>var utils = require('../utils');
var settings = require('../settings');
var playMenu = {};

var isOpen = false;
var newGameCardSwapped = false;

playMenu.open = function() {
  isOpen = true;
};

playMenu.close = function() {
  isOpen = false;
};

function swapCard() {
  newGameCardSwapped = !newGameCardSwapped;
}

// see game.styl for dimensions
function boardHeight() {
  return utils.getViewportDims().vw * 80 / 100;
}

// see game.styl for dimensions
function cardHeight() {
  return boardHeight() + 144;
}

function renderRadio(label, name, value, settingsProp) {
  var isOn = settingsProp() === value;
  var id = name + value;
  return [
    m('input.radio[type=radio]', {
      name: name,
      id: id,
      'class': value,
      value: value,
      checked: isOn,
      onchange: function(e) {
        settingsProp(e.target.value);
      }
    }),
    m('label', { 'for': id }, label) ];
}

function renderOption(label, value, storedValue) {
  return m('option', {
    value: value,
    selected: storedValue === value
  }, label);
}

function renderSelect(label, name, options, settingsProp, isDisabled) {
  var storedValue = settingsProp();
  return [
    m('label', { 'for': name }, label),
    m('select', {
      name: name,
      disabled: isDisabled,
      onchange: function(e) { settingsProp(e.target.value); }
    }, options.map(function(e) {
      return renderOption(e[0], e[1], storedValue); })
    )
  ];
}

function renderForm(action, settingsObj) {
  var timeMode = settingsObj.timeMode();
  var hasClock = timeMode === '1';
  var hasCorresp = timeMode === '2';

  var generalFieldset = [
    m('div.select_input',[
      renderSelect('Color:', 'color', [
        ['White', 'white'], ['Black', 'black'], ['Random', 'random']
      ], settingsObj.color),
    ]),
    m('div.select_input', [
      renderSelect('Variant:', 'variant', [
        ['Standard', '1'], ['Chess 960', '2'], ['King of the hill', '4']
      ], settingsObj.variant),
    ])
  ];
  if (settingsObj.level) {
    generalFieldset.push(m('div.select_input', [
      renderSelect('Level:', 'ailevel', [
        ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'],
        ['6', '6'], ['7','7'], ['8','8']
      ], settingsObj.level)
    ]));
  }
  if (settingsObj.mode) {
    generalFieldset.push(m('div.select_input', [
      renderSelect('Mode:', 'mode', [
        ['Casual', '0'], ['Rated', '1']
      ], settingsObj.mode)
    ]));
  }

  var timeFieldset = [
    m('div.select_input', [
      renderSelect('Time mode:', 'timeMode', [
        ['Unlimited', '0'], ['Clock', '1'], ['Correspondance', '2']
      ], settingsObj.timeMode)
    ])
  ];
  if (settingsObj.time && settingsObj.increment && hasClock) {
    timeFieldset.push(
      m('div.select_input.inline',[
        renderSelect('Time:', 'time', [
          ['5', '5'], ['10', '10'], ['30', '30']
        ], settingsObj.time, false)
      ]),
      m('div.select_input.inline',[
        renderSelect('Increment:', 'increment', [
          ['0', '0'], ['1', '1'], ['3', '3']
        ], settingsObj.increment, false)
      ])
    );
  }
  if (settingsObj.timePreset && hasClock) {
    timeFieldset.push(m('div.select_input',[
      renderSelect('Time|increment:', 'timepreset', [
        ['3|0', '3|0'], ['3|2', '3|2'], ['5|0', '5|0'], ['5|3', '5|3'],
        ['10|0', '10|0'], ['30|0']
      ], settingsObj.timePreset, false)
    ]));
  }
  if (hasCorresp) {
    timeFieldset.push(m('div.select_input',[
      renderSelect('Days per turn:', 'days', [
        ['1', '1'], ['2', '2'], ['3', '3'], ['5', '5'], ['7', '7'], ['10', '10'],
        ['14', '14']
      ], settingsObj.days, false)
    ]));
  }

  return m('form.form', {
    onsubmit: function(e) {
      e.preventDefault();
      playMenu.close();
      swapCard();
      action();
    }
  }, [
    m('fieldset', [
      m('div.nice-radio', renderRadio('Human', 'selected', 'human', settings.newGame.selected)),
      m('div.nice-radio', renderRadio('Computer', 'selected', 'computer', settings.newGame.selected))
    ]),
    m('fieldset', generalFieldset),
    m('fieldset#clock', timeFieldset),
    m('button', 'Valider')
  ]);
}

playMenu.view = function(ctrl) {
  var children = [
    m('div.overlay-close',
      { config: utils.ontouchstart(playMenu.close) },
    '+'),
    m('div.card.new-game', {
      class: newGameCardSwapped ? 'back_visible' : '',
      style: { height: cardHeight() + 'px' }
    }, [
      m('div.container_flip', [
        m('div.front', [
          m('div', { style: { height: boardHeight() + 'px' }}, [
            utils.viewOnlyBoard()
          ]),
          m('div.infos',[
            m('div.description',[
              m('h2.title', 'New Game'),
              m('p', 'Lancer une nouvelle partie'),
              m('button', { config: utils.ontouchstart(swapCard) }, '+ Nouvelle partie')
            ])
          ])
        ]),
        m('div.back', [
          settings.newGame.selected() === 'human' ?
            renderForm(ctrl.seekHumanGame, settings.newGame.human) :
            renderForm(ctrl.startAIGame, settings.newGame.ai)
        ])
      ])
    ])
  ];

  return m('div#game_menu.overlay.overlay-effect', {
    class: isOpen ? 'open' : '',
  }, children);
};

module.exports = playMenu;
<|endoftext|>


<commit_before>var utils = require('../utils');
var settings = require('../settings');
var playMenu = {};

var isOpen = false;
var newGameCardSwapped = false;

playMenu.open = function() {
  isOpen = true;
};

playMenu.close = function() {
  isOpen = false;
};

function swapCard() {
  newGameCardSwapped = !newGameCardSwapped;
}

// see game.styl for dimensions
function boardHeight() {
  return utils.getViewportDims().vw * 80 / 100;
}

// see game.styl for dimensions
function cardHeight() {
  return boardHeight() + 144;
}

function renderRadio(label, name, value, settingsProp) {
  var isOn = settingsProp() === value;
  var id = name + value;
  return [
    m('input.radio[type=radio]', {
      name: name,
      id: id,
      'class': value,
      value: value,
      checked: isOn,
      onchange: function(e) {
        settingsProp(e.target.value);
      }
    }),
    m('label', { 'for': id }, label) ];
}

function renderOption(label, value, storedValue) {
  return m('option', {
    value: value,
    selected: storedValue === value
  }, label);
}

function renderSelect(label, name, options, settingsProp, isDisabled) {
  var storedValue = settingsProp();
  return [
    m('label', { 'for': name }, label),
    m('select', {
      name: name,
      disabled: isDisabled,
      onchange: function(e) { settingsProp(e.target.value); }
    }, options.map(function(e) {
      return renderOption(e[0], e[1], storedValue); })
    )
  ];
}

function renderForm(action, settingsObj) {
  var timeMode = settingsObj.timeMode();
  var hasClock = timeMode === '1';
  var hasCorresp = timeMode === '2';

  var generalFieldset = [
    m('div.select_input',[
      renderSelect('Color:', 'color', [
        ['White', 'white'], ['Black', 'black'], ['Random', 'random']
      ], settingsObj.color),
    ]),
    m('div.select_input', [
      renderSelect('Variant:', 'variant', [
        ['Standard', '1'], ['Chess 960', '2'], ['King of the hill', '4']
      ], settingsObj.variant),
    ])
  ];
  if (settingsObj.level) {
    generalFieldset.push(m('div.select_input', [
      renderSelect('Level:', 'ailevel', [
        ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'],
        ['6', '6'], ['7','7'], ['8','8']
      ], settingsObj.level)
    ]));
  }
  if (settingsObj.mode) {
    generalFieldset.push(m('div.select_input', [
      renderSelect('Mode:', 'mode', [
        ['Casual', '0'], ['Rated', '1']
      ], settingsObj.mode)
    ]));
  }

  var timeFieldset = [
    m('div.select_input', [
      renderSelect('Time mode:', 'timeMode', [
        ['Unlimited', '0'], ['Clock', '1'], ['Correspondance', '2']
      ], settingsObj.timeMode)
    ])
  ];
  if (settingsObj.time && settingsObj.increment && hasClock) {
    timeFieldset.push(
      m('div.select_input.inline',[
        renderSelect('Time:', 'time', [
          ['5', '5'], ['10', '10'], ['30', '30']
        ], settingsObj.time, false)
      ]),
      m('div.select_input.inline',[
        renderSelect('Increment:', 'increment', [
          ['0', '0'], ['1', '1'], ['3', '3']
        ], settingsObj.increment, false)
      ])
    );
  }
  if (settingsObj.timePreset && hasClock) {
    timeFieldset.push(m('div.select_input',[
      renderSelect('Time|increment:', 'timepreset', [
        ['3|0', '3|0'], ['3|2', '3|2'], ['5|0', '5|0'], ['5|3', '5|3'],
        ['10|0', '10|0'], ['30|0']
      ], settingsObj.timePreset, false)
    ]));
  }
  if (hasCorresp) {
    timeFieldset.push(m('div.select_input',[
      renderSelect('Days per turn:', 'days', [
        ['1', '1'], ['2', '2'], ['3', '3'], ['5', '5'], ['7', '7'], ['10', '10'],
        ['14', '14']
      ], settingsObj.days, false)
    ]));
  }

  return m('form.form', {
    onsubmit: function(e) {
      e.preventDefault();
      playMenu.close();
      swapCard();
      action();
    }
  }, [
    m('fieldset', [
      m('div.nice-radio', renderRadio('Human', 'selected', 'human', settings.newGame.selected)),
      m('div.nice-radio', renderRadio('Computer', 'selected', 'computer', settings.newGame.selected))
    ]),
    m('fieldset', generalFieldset),
    m('fieldset#clock', timeFieldset),
    m('button', 'Valider')
  ]);
}

playMenu.view = function(ctrl) {
  var children = [
    m('div.overlay-close',
      { config: utils.ontouchstart(playMenu.close) },
    '+'),
    m('div.card.new-game', {
      class: newGameCardSwapped ? 'back_visible' : '',
      style: { height: cardHeight() + 'px' }
    }, [
      m('div.container_flip', [
        m('div.front', [
          m('div', { style: { height: boardHeight() + 'px' }}, [
            utils.viewOnlyBoard()
          ]),
          m('div.infos',[
            m('div.description',[
              m('h2.title', 'New Game'),
              m('p', 'Lancer une nouvelle partie'),
              m('button', { config: utils.ontouchstart(swapCard) }, '+ Nouvelle partie')
            ])
          ])
        ]),
        m('div.back', [
          settings.newGame.selected() === 'human' ?
            renderForm(ctrl.seekHumanGame, settings.newGame.human) :
            renderForm(ctrl.startAIGame, settings.newGame.ai)
        ])
      ])
    ])
  ];

  return m('div#game_menu.overlay.overlay-effect', {
    class: isOpen ? 'open' : '',
  }, children);
};

module.exports = playMenu;
<commit_msg>just being a little pesky prat with code duplication<commit_after>var utils = require('../utils');
var settings = require('../settings');
var playMenu = {};

var isOpen = false;
var newGameCardSwapped = false;

playMenu.open = function() {
  isOpen = true;
};

playMenu.close = function() {
  isOpen = false;
};

function swapCard() {
  newGameCardSwapped = !newGameCardSwapped;
}

// see game.styl for dimensions
function boardHeight() {
  return utils.getViewportDims().vw * 80 / 100;
}

// see game.styl for dimensions
function cardHeight() {
  return boardHeight() + 144;
}

function renderRadio(label, name, value, settingsProp) {
  var isOn = settingsProp() === value;
  var id = name + value;
  return [
    m('input.radio[type=radio]', {
      name: name,
      id: id,
      'class': value,
      value: value,
      checked: isOn,
      onchange: function(e) {
        settingsProp(e.target.value);
      }
    }),
    m('label', { 'for': id }, label) ];
}

function renderOption(label, value, storedValue) {
  return m('option', {
    value: value,
    selected: storedValue === value
  }, label);
}

function renderSelect(label, name, options, settingsProp, isDisabled) {
  var storedValue = settingsProp();
  return [
    m('label', { 'for': name }, label),
    m('select', {
      name: name,
      disabled: isDisabled,
      onchange: function(e) { settingsProp(e.target.value); }
    }, options.map(function(e) {
      return renderOption(e[0], e[1], storedValue); })
    )
  ];
}

function tupleOf(x) {
  return [x, x];
}

function renderForm(action, settingsObj) {
  var timeMode = settingsObj.timeMode();
  var hasClock = timeMode === '1';
  var hasCorresp = timeMode === '2';

  var generalFieldset = [
    m('div.select_input',[
      renderSelect('Color:', 'color', [
        ['White', 'white'], ['Black', 'black'], ['Random', 'random']
      ], settingsObj.color),
    ]),
    m('div.select_input', [
      renderSelect('Variant:', 'variant', [
        ['Standard', '1'], ['Chess 960', '2'], ['King of the hill', '4']
      ], settingsObj.variant),
    ])
  ];
  if (settingsObj.level) {
    generalFieldset.push(m('div.select_input', [
      renderSelect('Level:', 'ailevel', [
        '1', '2', '3', '4', '5', '6', '7', '8'
      ].map(tupleOf), settingsObj.level)
    ]));
  }
  if (settingsObj.mode) {
    generalFieldset.push(m('div.select_input', [
      renderSelect('Mode:', 'mode', [
        ['Casual', '0'], ['Rated', '1']
      ], settingsObj.mode)
    ]));
  }

  var timeFieldset = [
    m('div.select_input', [
      renderSelect('Time mode:', 'timeMode', [
        ['Unlimited', '0'], ['Clock', '1'], ['Correspondance', '2']
      ], settingsObj.timeMode)
    ])
  ];
  if (settingsObj.time && settingsObj.increment && hasClock) {
    timeFieldset.push(
      m('div.select_input.inline', [
        renderSelect('Time:', 'time', [
          '5', '10', '30'
        ].map(tupleOf), settingsObj.time, false)
      ]),
      m('div.select_input.inline', [
        renderSelect('Increment:', 'increment', [
          '0', '1', '2', '3'
        ].map(tupleOf), settingsObj.increment, false)
      ])
    );
  }
  if (settingsObj.timePreset && hasClock) {
    timeFieldset.push(m('div.select_input', [
      renderSelect('Time|increment:', 'timepreset', [
        '3|0', '3|2', '5|0', '5|3', '10|0', '30|0'
      ].map(tupleOf), settingsObj.timePreset, false)
    ]));
  }
  if (hasCorresp) {
    timeFieldset.push(m('div.select_input', [
      renderSelect('Days per turn:', 'days', [
        '1', '2', '3', '5', '7', '10', '14'
      ].map(tupleOf), settingsObj.days, false)
    ]));
  }

  return m('form.form', {
    onsubmit: function(e) {
      e.preventDefault();
      playMenu.close();
      swapCard();
      action();
    }
  }, [
    m('fieldset', [
      m('div.nice-radio', renderRadio('Human', 'selected', 'human', settings.newGame.selected)),
      m('div.nice-radio', renderRadio('Computer', 'selected', 'computer', settings.newGame.selected))
    ]),
    m('fieldset', generalFieldset),
    m('fieldset#clock', timeFieldset),
    m('button', 'Valider')
  ]);
}

playMenu.view = function(ctrl) {
  var children = [
    m('div.overlay-close',
      { config: utils.ontouchstart(playMenu.close) },
    '+'),
    m('div.card.new-game', {
      class: newGameCardSwapped ? 'back_visible' : '',
      style: { height: cardHeight() + 'px' }
    }, [
      m('div.container_flip', [
        m('div.front', [
          m('div', { style: { height: boardHeight() + 'px' }}, [
            utils.viewOnlyBoard()
          ]),
          m('div.infos',[
            m('div.description',[
              m('h2.title', 'New Game'),
              m('p', 'Lancer une nouvelle partie'),
              m('button', { config: utils.ontouchstart(swapCard) }, '+ Nouvelle partie')
            ])
          ])
        ]),
        m('div.back', [
          settings.newGame.selected() === 'human' ?
            renderForm(ctrl.seekHumanGame, settings.newGame.human) :
            renderForm(ctrl.startAIGame, settings.newGame.ai)
        ])
      ])
    ])
  ];

  return m('div#game_menu.overlay.overlay-effect', {
    class: isOpen ? 'open' : '',
  }, children);
};

module.exports = playMenu;
<|endoftext|>


<commit_before>var request = {
    // request
    get: "GET",
    post: "POST"
};

module.exports = request;
<commit_msg>removed duplicate request library<commit_after><|endoftext|>


<commit_before>// Invoke plugins for certain actions.

const { store } = require("./index")
const apiRunnerNode = require("../utils/api-runner-node")

store.subscribe(() => {
  const state = store.getState()
  // console.log("last action", state.lastAction.type)
  if (
    state.lastAction.type === "CREATE_NODE" &&
    state.lastAction.payload.logical !== true
  ) {
    const node = state.nodes[state.lastAction.payload.id]
    apiRunnerNode(`onNodeCreate`, { node })
  }

  if (state.lastAction.type === "UPSERT_PAGE") {
    const page = state.nodes[state.lastAction.payload]
    apiRunnerNode(`onUpsertPage`, { page })
  }
})
<commit_msg>Pass actual page object in<commit_after>// Invoke plugins for certain actions.

const { store } = require("./index")
const apiRunnerNode = require("../utils/api-runner-node")

store.subscribe(() => {
  const state = store.getState()
  // console.log("last action", state.lastAction.type)
  if (
    state.lastAction.type === "CREATE_NODE" &&
    state.lastAction.payload.logical !== true
  ) {
    const node = state.nodes[state.lastAction.payload.id]
    apiRunnerNode(`onNodeCreate`, { node })
  }

  if (state.lastAction.type === "UPSERT_PAGE") {
    const page = state.lastAction.payload
    apiRunnerNode(`onUpsertPage`, { page })
  }
})
<|endoftext|>


<commit_before>'use strict';

var searchResults = function($rootScope){

  /*
  trials structure is created when setTrials is called
  trials is an object, example:
  trials = {
    status1: {
      trialcount: number
      conditions: {
        condition1: [trialObj, trialObj, trialObj, ...],
        condition2: [],
        ...
      }
    },
    status2: {
      trialcount: number
      conditions: {
        condition1: [trialObj, trialObj, trialObj, ...],
        condition2: [],
        ...
      }
    },
    ...
  }
  trialObj have structure
  */

  var trials = {};
  // public api
  return {
    getTrials: function(){
      return trials;
    },
    setTrials: function(inputArray){ // array of trialObj
      for (var i=0; i<inputArray.length; i++){
        var status = inputArray[i].status[0]._;
        var conditions = inputArray[i].condition_summary[0].split('; '); // array of strings
        // check if the status is already in trials, if not, create it
        if (!trials[status]){
          trials[status] = {trialcount: 0, conditions: {}};
        }
        trials[status].trialcount++;
        for (var j=0; j<conditions.length; j++){
          if(!trials[status].conditions[conditions[j]]){
            trials[status].conditions[conditions[j]] = [];
          }
          trials[status].conditions[conditions[j]].push(inputArray[i]);
        }
      }
      console.log('Finished building trial structure');
      $rootScope.$broadcast('dataReady');
    }
  };
};

angular.module('clinicaltrialsApp')
  .factory('searchResults', ['$rootScope', searchResults]);
<commit_msg>Returns null if a search has not been run and trials is empty<commit_after>'use strict';

var searchResults = function($rootScope){

  /*
  trials structure is created when setTrials is called
  trials is an object, example:
  trials = {
    status1: {
      trialcount: number
      conditions: {
        condition1: [trialObj, trialObj, trialObj, ...],
        condition2: [],
        ...
      }
    },
    status2: {
      trialcount: number
      conditions: {
        condition1: [trialObj, trialObj, trialObj, ...],
        condition2: [],
        ...
      }
    },
    ...
  }
  trialObj have structure
  */

  var trials = {};
  // public api
  return {
    getTrials: function(){
      if ($.isEmptyObject(trials)){
        return null;
      } else {
        return trials;
      }
    },
    setTrials: function(inputArray){ // array of trialObj
      trials = {};
      for (var i=0; i<inputArray.length; i++){
        var status = inputArray[i].status[0]._;
        var conditions = inputArray[i].condition_summary[0].split('; '); // array of strings
        // check if the status is already in trials, if not, create it
        if (!trials[status]){
          trials[status] = {trialcount: 0, conditions: {}};
        }
        trials[status].trialcount++;
        for (var j=0; j<conditions.length; j++){
          if(!trials[status].conditions[conditions[j]]){
            trials[status].conditions[conditions[j]] = [];
          }
          trials[status].conditions[conditions[j]].push(inputArray[i]);
        }
      }
      console.log('Finished building trial structure');
      $rootScope.$broadcast('dataReady');
    }
  };
};

angular.module('clinicaltrialsApp')
  .factory('searchResults', ['$rootScope', searchResults]);
<|endoftext|>


<commit_before>import React from 'react';

import NavMore from './components.nav-more';

class Header extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      chatActive: true
    };
  }

  render() {
    let navigation;
    let headerClass;
    let logoClass;
    let backButtonClass;

    if (this.state.chatActive) {
      navigation = <NavChat/>;
      headerClass = 's-header state-chat';
      logoClass = 'logo';
      backButtonClass = 'back-button state-active';
    } else {
      navigation = <NavMain/>;
      headerClass = 's-header';
      logoClass = 'logo state-active';
      backButtonClass = 'back-button';
    }

    return (

        {navigation}

        <NavMore/>

    );
  }

  closeConversation() {
    this.setState({
      chatActive: false
    });
  }
}

class NavMain extends React.Component {
  render() {
    return (

Chats

Contacts

    );
  }
}

class NavChat extends React.Component {
  render() {
    return (

    );
  }
}

export default Header;

// if (document.querySelector('.s-header') && document.querySelector('.js-trigger')) {
//   let trigger = document.querySelector('.js-trigger'),
//       header = document.querySelector('.s-header'),
//       navChat = document.querySelector('.js-nav-main-chat'),
//       logo = document.querySelector('.s-header .icon .logo'),
//       backButton = document.querySelector('.js-back-button');

//   trigger.addEventListener('click', function (e) {
//     e.preventDefault();
//     header.classList.toggle('state-chat');
//     navChat.classList.toggle('state-active');
//     logo.classList.toggle('state-active');
//     backButton.classList.toggle('state-active');
//     this.classList.toggle('state-active');
//   });

//   backButton.addEventListener('click', function (e) {
//     e.preventDefault();
//     trigger.classList.toggle('state-active');
//     header.classList.toggle('state-chat');
//     navChat.classList.toggle('state-active');
//     logo.classList.toggle('state-active');
//     this.classList.toggle('state-active');
//   });
// }<commit_msg>clean code header component<commit_after>import React from 'react';

import NavMore from './components.nav-more';

class Header extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      chatActive: true
    };
  }

  render() {
    let navigation;
    let headerClass;
    let logoClass;
    let backButtonClass;

    if (this.state.chatActive) {
      navigation = <NavChat/>;
      headerClass = 's-header state-chat';
      logoClass = 'logo';
      backButtonClass = 'back-button state-active';
    } else {
      navigation = <NavMain/>;
      headerClass = 's-header';
      logoClass = 'logo state-active';
      backButtonClass = 'back-button';
    }

    return (

        {navigation}

        <NavMore/>

    );
  }

  closeConversation() {
    this.setState({
      chatActive: false
    });
  }
}

class NavMain extends React.Component {
  render() {
    return (

Chats

Contacts

    );
  }
}

class NavChat extends React.Component {
  render() {
    return (

    );
  }
}

export default Header;
<|endoftext|>


<commit_before>"use strict";
// This script will take one or more server-side template directories and inline their contents on a page.  Used to expose templates for client-side rendering.
var fluid  = fluid || require("infusion");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.express.hb.inline");
var fs     = require("fs");

gpii.express.hb.inline.loadTemplates =  function (that, dir, res) {
    var dirContents = fs.readdirSync(dir);
    dirContents.forEach(function (entry) {
        var path = dir + "/" + entry;
        var stats = fs.statSync(path);
        if (stats.isFile()) {
            var matches = that.options.hbsExtensionRegexp.exec(entry);
            if (matches) {
                var templateType = dir.indexOf("partials") !== -1 ? "partial" : "template";
                var key =  templateType + "-" + matches[1];

                // cache file information so that we only reload templates that have been updated
                if (that.cache[key] && stats.mtime.getTime() === that.cache[key].mtime.getTime()) {
                    //fluid.log("Skipping cached " + templateType + " '" + key + "'...");
                }
                else {
                    that.cache[key] = {
                        mtime: stats.mtime,
                        content: fs.readFileSync(path)
                    };
                    that.events.onUpdated.fire(that);
                }
            }
        }
        else if (stats.isDirectory()) {
            // call the function recursively for each directory
            gpii.express.hb.inline.loadTemplates(that, path, res);
        }
    });
};

gpii.express.hb.inline.wrapTemplate = function (that, key, content) {
    // We have to pseudo-escape script tags to avoid them breaking our templates.
    return "<script id=\"" + key + "\" type=\"text/x-handlebars-template\">" + content.toString().replace(that.options.hbsScriptRegexp, "{{!}}$1") + "</script>\n\n";
};

gpii.express.hb.inline.generateCachedHtml = function (that) {
    that.html = "";
    Object.keys(that.cache).forEach(function (key) {
        that.html += that.wrapTemplate(key, that.cache[key].content);
    });
};

gpii.express.hb.inline.getRouter = function (that) {
    return function (req, res) {
        gpii.express.hb.inline.loadTemplates(that, that.options.config.express.views, res);

        res.status(200).send(that.html);
    };
};

fluid.defaults("gpii.express.hb.inline", {
    gradeNames: ["gpii.express.router", "autoInit"],
    path:               "/inline",
    hbsExtensionRegexp: /^(.+)\.(?:hbs|handlebars)$/,
    hbsScriptRegexp:    /(script>)/g,
    members: {
        cache:              {},
        html:               ""
    },
    events: {
        addRoutes: null,
        onUpdated: null
    },
    invokers: {
        "getRouter": {
            funcName: "gpii.express.hb.inline.getRouter",
            args: ["{that}"]
        },
        "wrapTemplate": {
            funcName: "gpii.express.hb.inline.wrapTemplate",
            args: ["{that}", "{arguments}.0", "{arguments}.1"]
        }
    },
    listeners: {
        "onUpdated": {
            funcName: "gpii.express.hb.inline.generateCachedHtml",
            args:     ["{that}"]
        }
    }
});<commit_msg>CTR-176: Working to resolve errors in Windows.  Converted from using manual path assembly to using the (hopefully) windows-friendlier path.resolve() function.<commit_after>"use strict";
// This script will take one or more server-side template directories and inline their contents on a page.  Used to expose templates for client-side rendering.
var fluid  = fluid || require("infusion");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.express.hb.inline");
var fs     = require("fs");
var path   = require("path");

gpii.express.hb.inline.loadTemplates =  function (that, dir, res) {
    var dirContents = fs.readdirSync(dir);
    dirContents.forEach(function (entry) {
        var templatePath = path.resolve(dir, entry);
        var stats = fs.statSync(templatePath);
        if (stats.isFile()) {
            var matches = that.options.hbsExtensionRegexp.exec(entry);
            if (matches) {
                var templateType = dir.indexOf("partials") !== -1 ? "partial" : "template";
                var key =  templateType + "-" + matches[1];

                // cache file information so that we only reload templates that have been updated
                if (that.cache[key] && stats.mtime.getTime() === that.cache[key].mtime.getTime()) {
                    //fluid.log("Skipping cached " + templateType + " '" + key + "'...");
                }
                else {
                    that.cache[key] = {
                        mtime: stats.mtime,
                        content: fs.readFileSync(templatePath)
                    };
                    that.events.onUpdated.fire(that);
                }
            }
        }
        else if (stats.isDirectory()) {
            // call the function recursively for each directory
            gpii.express.hb.inline.loadTemplates(that, templatePath, res);
        }
    });
};

gpii.express.hb.inline.wrapTemplate = function (that, key, content) {
    // We have to pseudo-escape script tags to avoid them breaking our templates.
    return "<script id=\"" + key + "\" type=\"text/x-handlebars-template\">" + content.toString().replace(that.options.hbsScriptRegexp, "{{!}}$1") + "</script>\n\n";
};

gpii.express.hb.inline.generateCachedHtml = function (that) {
    that.html = "";
    Object.keys(that.cache).forEach(function (key) {
        that.html += that.wrapTemplate(key, that.cache[key].content);
    });
};

gpii.express.hb.inline.getRouter = function (that) {
    return function (req, res) {
        gpii.express.hb.inline.loadTemplates(that, that.options.config.express.views, res);

        res.status(200).send(that.html);
    };
};

fluid.defaults("gpii.express.hb.inline", {
    gradeNames: ["gpii.express.router", "autoInit"],
    path:               "/inline",
    hbsExtensionRegexp: /^(.+)\.(?:hbs|handlebars)$/,
    hbsScriptRegexp:    /(script>)/g,
    members: {
        cache:              {},
        html:               ""
    },
    events: {
        addRoutes: null,
        onUpdated: null
    },
    invokers: {
        "getRouter": {
            funcName: "gpii.express.hb.inline.getRouter",
            args: ["{that}"]
        },
        "wrapTemplate": {
            funcName: "gpii.express.hb.inline.wrapTemplate",
            args: ["{that}", "{arguments}.0", "{arguments}.1"]
        }
    },
    listeners: {
        "onUpdated": {
            funcName: "gpii.express.hb.inline.generateCachedHtml",
            args:     ["{that}"]
        }
    }
});<|endoftext|>