<commit_before>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

function processEvent(event) {
    var sender = event.sender.id.toString();

    if ((event.message && event.message.text) || (event.postback && event.postback.payload)) {
        var text = event.message ? event.message.text : event.postback.payload;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("Text", text);

        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });

        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                //asd
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                let action = response.result.action;
                /*console.log(responseText);
                console.log(responseData);
                console.log(action);*/
                if (isDefined(responseData) && isDefined(responseData.facebook)) {
                    if (!Array.isArray(responseData.facebook)) {
                        try {
                            console.log('Response as formatted message');
                            sendFBMessage(sender, responseData.facebook);
                        } catch (err) {
                            sendFBMessage(sender, {text: err.message});
                        }
                    } else {
                        responseData.facebook.forEach((facebookMessage) => {
                            try {
                                if (facebookMessage.sender_action) {
                                    console.log('Response as sender action');
                                    sendFBSenderAction(sender, facebookMessage.sender_action);
                                }
                                else {
                                    console.log('Response as formatted message');
                                    sendFBMessage(sender, facebookMessage);
                                }
                            } catch (err) {
                                sendFBMessage(sender, {text: err.message});
                            }
                        });
                    }
                //} else if (isDefined(responseText)) {
                } else if (isDefined(action) && isDefined(responseText)) {
                    console.log('Response as text message');
                    // facebook API limit for text length is 320,
                    // so we must split message if needed
                    var splittedText = splitResponse(responseText);
                    /*switch (action){
                        case 'show_prod':
                            console.log('generic');
                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                            sendFBMessage(sender, generic_message, null);
                            break;
                        default:
                            console.log('default');
                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                    }*/
                    async.eachSeries(splittedText, (textPart, callback) => {
                        sendFBMessage(sender, {text: textPart}, callback);
                    });
                }

            }
        });

        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320) {
        return [str];
    }

    return chunkString(str, 300);
}

function chunkString(s, len) {
    var curr = len, prev = 0;

    var output = [];

    while (s[curr]) {
        if (s[curr++] == ' ') {
            output.push(s.substring(prev, curr));
            prev = curr;
            curr += len;
        }
        else {
            var currReverse = curr;
            do {
                if (s.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(s.substring(prev, currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while (currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    //console.log(output);
    //output = ['Length of param message[text] must be less than or equal to 320'];
    return output;
}

/*const generic_message = {
    attachment: {
        type: "template",
        payload: {
            template_type: "generic",
            elements: [{
                title: "rift",
                subtitle: "Next-generation virtual reality",
                item_url: "https://www.oculus.com/en-us/rift/",
                image_url: "http://messengerdemo.parseapp.com/img/rift.png",
                buttons: [{
                    type: "web_url",
                    url: "https://www.oculus.com/en-us/rift/",
                    title: "Open Web URL"
                }, {
                    type: "postback",
                    title: "Call Postback",
                    payload: "Payload for first bubble"
                }]
            }, {
                title: "touch",
                subtitle: "Your Hands, Now in VR",
                item_url: "https://www.oculus.com/en-us/touch/",
                image_url: "http://messengerdemo.parseapp.com/img/touch.png",
                buttons: [{
                    type: "web_url",
                    url: "https://www.oculus.com/en-us/touch/",
                    title: "Open Web URL"
                }, {
                    type: "postback",
                    title: "Call Postback",
                    payload: "Payload for second bubble"
                }]
            }]
        }
    }
};*/

function sendFBMessage(sender, messageData, callback) {
    //console.log(sender);
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: messageData
            //message: generic_message
        }
    }, (error, response, body) => {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }

        if (callback) {
            callback();
        }
    });
}

function sendFBSenderAction(sender, action, callback) {
    setTimeout(() => {
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token: FB_PAGE_ACCESS_TOKEN},
            method: 'POST',
            json: {
                recipient: {id: sender},
                sender_action: action
            }
        }, (error, response, body) => {
            if (error) {
                console.log('Error sending action: ', error);
            } else if (response.body.error) {
                console.log('Error: ', response.body.error);
            }
            if (callback) {
                callback();
            }
        });
    }, 1000);
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        (error, response, body) => {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();

app.use(bodyParser.text({type: 'application/json'}));

app.get('/webhook/', (req, res) => {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(() => {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);
        var asd = data;
        //console.log(asd);
        if (data.entry) {
            let entries = data.entry;
            entries.forEach((entry) => {
                let messaging_events = entry.messaging;
                if (messaging_events) {
                    messaging_events.forEach((event) => {
                        //console.log(event);
                        if (event.message && !event.message.is_echo ||
                            event.postback && event.postback.payload) {
                            processEvent(event);
                        }
                    });
                }
            });
        }

        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

app.post('/webhook_apiai/', (req, res) => {

    const generic_message = {
        attachment: {
            type: "template",
            payload: {
                template_type: "generic",
                elements: [{
                    title: "Fresh Pizza",
                    subtitle: "Be carefull and don't eat your fingers!!!",
                    item_url: "https://en.wikipedia.org/wiki/Pizza",
                    //image_url: "http://www.cbc.ca/inthekitchen/assets_c/2012/11/MargheritaPizza21-thumb-596x350-247022.jpg",
                    buttons: [{
                        type: "web_url",
                        url: "https://en.wikipedia.org/wiki/Pizza",
                        title: "Open Web URL"
                    }/*, {
                     type: "postback",
                     title: "Call Postback",
                     payload: "Payload for first bubble"
                     }*/]
                }]
            }
        }
    };

    try {
        var data = JSONbig.parse(req.body);
        //console.log(data);
        switch(data.result.action){
            case 'show_prod':
                switch(data.result.parameters.pizza_type){
                    case 'Margherita':
                        generic_message.attachment.payload.elements[0].title = data.result.parameters.pizza_type;
                        generic_message.attachment.payload.elements[0].image_url = "http://www.cbc.ca/inthekitchen/assets_c/2012/11/MargheritaPizza21-thumb-596x350-247022.jpg";
                }
            case 'show_weather':
                if(data.result.parameters['geo-city']){
                    var city = data.result.parameters['geo-city'];
                    var base_url = "https://query.yahooapis.com/v1/public/yql?" + "q=select+%2A+from+weather.forecast+where+woeid+in+%28select+woeid+from+geo.places%281%29+where+text%3D%27"+city+"%27%29" + "&format=json";
                    request({
                        url: base_url,
                        method: 'GET', //Specify the method
                    }, function(error, response, body){
                        if(error) {
                            console.log(error);
                        } else {
                            console.log('here');
                            //console.log(response.statusCode, body);
                            var query = JSON.parse(body).query;
                            var results = query.results;
                            var channel = results.channel;
                            var item = channel.item;
                            var location = channel.location;
                            var units = channel.units;
                            var condition = item.condition;
                            //console.log(channel)
                            var string = "Today in " + location.city + ": " + condition.text + ", the temperature is " + condition.temp + " " + units.temperature
                            generic_message.attachment.payload.elements[0].title = 'Weather in' + city;
                            generic_message.attachment.payload.elements[0].subtitle = string;
                            generic_message.attachment.payload.elements[0].item_url = channel.link;
                            generic_message.attachment.payload.elements[0].image_url = channel.image.url;
                            generic_message.attachment.payload.elements[0].buttons[0].url = channel.link;
                        }
                    });
                }
        }
        return res.status(200).json({
            data: {
                facebook: generic_message
            }
        })
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }
});

app.listen(REST_PORT, () => {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();
<commit_msg>'webhook_test'<commit_after>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

function processEvent(event) {
    var sender = event.sender.id.toString();

    if ((event.message && event.message.text) || (event.postback && event.postback.payload)) {
        var text = event.message ? event.message.text : event.postback.payload;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("Text", text);

        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });

        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                //asd
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                let action = response.result.action;
                /*console.log(responseText);
                console.log(responseData);
                console.log(action);*/
                if (isDefined(responseData) && isDefined(responseData.facebook)) {
                    if (!Array.isArray(responseData.facebook)) {
                        try {
                            console.log('Response as formatted message');
                            sendFBMessage(sender, responseData.facebook);
                        } catch (err) {
                            sendFBMessage(sender, {text: err.message});
                        }
                    } else {
                        responseData.facebook.forEach((facebookMessage) => {
                            try {
                                if (facebookMessage.sender_action) {
                                    console.log('Response as sender action');
                                    sendFBSenderAction(sender, facebookMessage.sender_action);
                                }
                                else {
                                    console.log('Response as formatted message');
                                    sendFBMessage(sender, facebookMessage);
                                }
                            } catch (err) {
                                sendFBMessage(sender, {text: err.message});
                            }
                        });
                    }
                //} else if (isDefined(responseText)) {
                } else if (isDefined(action) && isDefined(responseText)) {
                    console.log('Response as text message');
                    // facebook API limit for text length is 320,
                    // so we must split message if needed
                    var splittedText = splitResponse(responseText);
                    /*switch (action){
                        case 'show_prod':
                            console.log('generic');
                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                            sendFBMessage(sender, generic_message, null);
                            break;
                        default:
                            console.log('default');
                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                    }*/
                    async.eachSeries(splittedText, (textPart, callback) => {
                        sendFBMessage(sender, {text: textPart}, callback);
                    });
                }

            }
        });

        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320) {
        return [str];
    }

    return chunkString(str, 300);
}

function chunkString(s, len) {
    var curr = len, prev = 0;

    var output = [];

    while (s[curr]) {
        if (s[curr++] == ' ') {
            output.push(s.substring(prev, curr));
            prev = curr;
            curr += len;
        }
        else {
            var currReverse = curr;
            do {
                if (s.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(s.substring(prev, currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while (currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    //console.log(output);
    //output = ['Length of param message[text] must be less than or equal to 320'];
    return output;
}

/*const generic_message = {
    attachment: {
        type: "template",
        payload: {
            template_type: "generic",
            elements: [{
                title: "rift",
                subtitle: "Next-generation virtual reality",
                item_url: "https://www.oculus.com/en-us/rift/",
                image_url: "http://messengerdemo.parseapp.com/img/rift.png",
                buttons: [{
                    type: "web_url",
                    url: "https://www.oculus.com/en-us/rift/",
                    title: "Open Web URL"
                }, {
                    type: "postback",
                    title: "Call Postback",
                    payload: "Payload for first bubble"
                }]
            }, {
                title: "touch",
                subtitle: "Your Hands, Now in VR",
                item_url: "https://www.oculus.com/en-us/touch/",
                image_url: "http://messengerdemo.parseapp.com/img/touch.png",
                buttons: [{
                    type: "web_url",
                    url: "https://www.oculus.com/en-us/touch/",
                    title: "Open Web URL"
                }, {
                    type: "postback",
                    title: "Call Postback",
                    payload: "Payload for second bubble"
                }]
            }]
        }
    }
};*/

function sendFBMessage(sender, messageData, callback) {
    //console.log(sender);
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: messageData
            //message: generic_message
        }
    }, (error, response, body) => {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }

        if (callback) {
            callback();
        }
    });
}

function sendFBSenderAction(sender, action, callback) {
    setTimeout(() => {
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token: FB_PAGE_ACCESS_TOKEN},
            method: 'POST',
            json: {
                recipient: {id: sender},
                sender_action: action
            }
        }, (error, response, body) => {
            if (error) {
                console.log('Error sending action: ', error);
            } else if (response.body.error) {
                console.log('Error: ', response.body.error);
            }
            if (callback) {
                callback();
            }
        });
    }, 1000);
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        (error, response, body) => {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();

app.use(bodyParser.text({type: 'application/json'}));

app.get('/webhook/', (req, res) => {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(() => {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);
        var asd = data;
        //console.log(asd);
        if (data.entry) {
            let entries = data.entry;
            entries.forEach((entry) => {
                let messaging_events = entry.messaging;
                if (messaging_events) {
                    messaging_events.forEach((event) => {
                        //console.log(event);
                        if (event.message && !event.message.is_echo ||
                            event.postback && event.postback.payload) {
                            processEvent(event);
                        }
                    });
                }
            });
        }

        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

app.post('/webhook_apiai/', (req, res) => {

    const generic_message = {
        attachment: {
            type: "template",
            payload: {
                template_type: "generic",
                elements: [{
                    title: "Fresh Pizza",
                    subtitle: "Be carefull and don't eat your fingers!!!",
                    item_url: "https://en.wikipedia.org/wiki/Pizza",
                    //image_url: "http://www.cbc.ca/inthekitchen/assets_c/2012/11/MargheritaPizza21-thumb-596x350-247022.jpg",
                    buttons: [{
                        type: "web_url",
                        url: "https://en.wikipedia.org/wiki/Pizza",
                        title: "Open Web URL"
                    }/*, {
                     type: "postback",
                     title: "Call Postback",
                     payload: "Payload for first bubble"
                     }*/]
                }]
            }
        }
    };

    try {
        var data = JSONbig.parse(req.body);
        //console.log(data);
        switch(data.result.action){
            case 'show_prod':
                switch(data.result.parameters.pizza_type){
                    case 'Margherita':
                        generic_message.attachment.payload.elements[0].title = data.result.parameters.pizza_type;
                        generic_message.attachment.payload.elements[0].image_url = "http://www.cbc.ca/inthekitchen/assets_c/2012/11/MargheritaPizza21-thumb-596x350-247022.jpg";
                }
            case 'show_weather':
                if(data.result.parameters['geo-city'].length > 0){
                    var city = data.result.parameters['geo-city'];
                    var base_url = "https://query.yahooapis.com/v1/public/yql?" + "q=select+%2A+from+weather.forecast+where+woeid+in+%28select+woeid+from+geo.places%281%29+where+text%3D%27"+city+"%27%29" + "&format=json";
                    request({
                        url: base_url,
                        method: 'GET', //Specify the method
                    }, function(error, response, body){
                        if(error) {
                            console.log(error);
                        } else {
                            console.log('here');
                            //console.log(response.statusCode, body);
                            var query = JSON.parse(body).query;
                            var results = query.results;
                            var channel = results.channel;
                            var item = channel.item;
                            var location = channel.location;
                            var units = channel.units;
                            var condition = item.condition;
                            //console.log(channel)
                            var string = "Today in " + location.city + ": " + condition.text + ", the temperature is " + condition.temp + " " + units.temperature
                            generic_message.attachment.payload.elements[0].title = 'Weather in' + city;
                            generic_message.attachment.payload.elements[0].subtitle = string;
                            generic_message.attachment.payload.elements[0].item_url = channel.link;
                            generic_message.attachment.payload.elements[0].image_url = channel.image.url;
                            generic_message.attachment.payload.elements[0].buttons[0].url = channel.link;
                        }
                    });
                }
        }
        return res.status(200).json({
            data: {
                facebook: generic_message
            }
        })
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }
});

app.listen(REST_PORT, () => {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();
<|endoftext|>


<commit_before>import React, { useState, useEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import clsx from 'clsx'
import { makeStyles, useTheme } from '@material-ui/core/styles'
import useMediaQuery from '@material-ui/core/useMediaQuery'
import Drawer from '@material-ui/core/Drawer'
import Hidden from '@material-ui/core/Hidden'

import AppHeader from '../../_common/AppHeader'
import AppFooter from '../../_common/AppFooter'
import AppSidebar from '../../_common/AppSidebar'

const DashboardLayout = (
  { header, footer, sidebar, children } = {
    header: AppHeader,
    footer: AppFooter,
    sidebar: AppSidebar,
  },
) => {
  const refHeaderContainer = useRef(null)

  const classes = useStyles()
  const theme = useTheme()
  const isDesktop = useMediaQuery(theme.breakpoints.up('md'))
  const isMobile = !isDesktop

  const [headerHeight, setHeaderHeight] = useState(0)
  const [isSidebarOpenMobile, setIsSidebarOpenMobile] = useState(false)
  const [isSidebarOpenDesktop, setIsSidebarOpenDesktop] = useState(true)
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false)

  useEffect(() => {
    // code to run on component mount
    setHeaderHeight(refHeaderContainer.current.offsetHeight)
  }, [])

  const contentOffset = (() => {
    if ((isDesktop && !isSidebarOpenDesktop) || isMobile) {
      return 0
    } else if (isDesktop && isSidebarCollapsed) {
      return theme.sidebar.widthCollapsed
    } else {
      return theme.sidebar.width
    }
  })()

  const HeaderComponent = header
  const SidebarComponent = sidebar
  const FooterComponent = footer

  function handleSidebarToggleOpenMobile() {
    setIsSidebarOpenMobile(!isSidebarOpenMobile)
  }

  function handleSidebarToggle() {
    // Open/close on mobile
    if (isMobile) {
      setIsSidebarOpenMobile(!isSidebarOpenMobile)
    }
    // Collapse/uncollapse on desktop
    else {
      setIsSidebarCollapsed(!isSidebarCollapsed)
    }
  }

  function handleSidebarToggleCollapse() {
    setIsSidebarCollapsed(!isSidebarCollapsed)
  }

  return (

      <div
        ref={refHeaderContainer}
        className={clsx(classes.headerContainer)}
        style={{
          width: `calc(100% - ${contentOffset}px)`,
        }}
      >
        {HeaderComponent && <HeaderComponent onToggleClick={handleSidebarToggle} />}

        {/* Mobile sidebar */}
        <Hidden mdUp implementation="css">
          <Drawer
            variant="temporary"
            open={isSidebarOpenMobile}
            onClose={handleSidebarToggleOpenMobile}
            classes={{
              paper: clsx(classes.drawer), //  classes.drawerMobile
            }}
            ModalProps={{
              keepMounted: true, // Better open performance on mobile.
            }}
          >
            {SidebarComponent && <SidebarComponent />}
          </Drawer>
        </Hidden>
        {/* Desktop sidebar */}
        <Hidden smDown implementation="css">
          <Drawer
            classes={{
              paper: clsx(classes.drawer),
            }}
            variant="permanent"
          >
            {SidebarComponent && <SidebarComponent isCollapsed={isSidebarCollapsed} />}
          </Drawer>
        </Hidden>

{children}

          {FooterComponent && <FooterComponent />}

  )
}

DashboardLayout.defaultProps = {
  header: AppHeader,
  sidebar: AppSidebar,
  footer: AppFooter,
}

DashboardLayout.propTypes = {
  header: PropTypes.elementType,
  sidebar: PropTypes.elementType,
  footer: PropTypes.elementType,
}

const useStyles = makeStyles(theme => ({
  dashboardContainer: {
    display: 'flex',
    background: '#f5f5f5',
  },
  headerContainer: {
    top: 0,
    left: 'auto',
    right: 0,
    display: 'flex',
    alignItems: 'stretch',
    position: 'absolute',
    zIndex: theme.zIndex.drawer + 1,
    // transition: theme.transitions.create(['width', 'margin'], {
    //   easing: theme.transitions.easing.sharp,
    //   duration: theme.transitions.duration.leavingScreen,
    // }),
  },
  sidebarContainer: {
    display: 'flex',
    alignItems: 'stretch',
    position: 'relative',
    top: 0,
    bottom: 0,
    flexDirection: 'row',
    width: theme.sidebar.width,
    // [theme.breakpoints.up('md')]: {
    //   width: theme.sidebar.width,
    //   flexShrink: 0,
    // },
    // transition: theme.transitions.create('width', {
    //   easing: theme.transitions.easing.sharp,
    //   duration: theme.transitions.duration.leavingScreen,
    // }),
  },
  sidebarContainerMobile: {
    width: 0,
  },
  sidebarContainerCollapsed: {
    width: theme.sidebar.widthCollapsed,
  },
  drawer: {
    width: '100%',
    position: 'absolute',
    [theme.breakpoints.down('sm')]: {
      width: theme.sidebar.width,
      flexShrink: 0,
    },
  },
  mainContainer: {
    flexGrow: 1,
    height: '100vh',
    overflow: 'auto',
    flexDirection: 'column',
    display: 'flex',
  },
  contentContainer: {
    display: 'flex',
    position: 'relative',
    flex: 1,
  },
  footerContainer: {
    position: 'relative',
  },
}))

export default DashboardLayout
<commit_msg>Enable sidebar transitions<commit_after>import React, { useState, useEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import clsx from 'clsx'
import { makeStyles, useTheme } from '@material-ui/core/styles'
import useMediaQuery from '@material-ui/core/useMediaQuery'
import Drawer from '@material-ui/core/Drawer'
import Hidden from '@material-ui/core/Hidden'

import AppHeader from '../../_common/AppHeader'
import AppFooter from '../../_common/AppFooter'
import AppSidebar from '../../_common/AppSidebar'

const DashboardLayout = (
  { header, footer, sidebar, children } = {
    header: AppHeader,
    footer: AppFooter,
    sidebar: AppSidebar,
  },
) => {
  const refHeaderContainer = useRef(null)

  const classes = useStyles()
  const theme = useTheme()
  const isDesktop = useMediaQuery(theme.breakpoints.up('md'))
  const isMobile = !isDesktop

  const [headerHeight, setHeaderHeight] = useState(0)
  const [isSidebarOpenMobile, setIsSidebarOpenMobile] = useState(false)
  const [isSidebarOpenDesktop, setIsSidebarOpenDesktop] = useState(true)
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false)

  useEffect(() => {
    // code to run on component mount
    setHeaderHeight(refHeaderContainer.current.offsetHeight)
  }, [])

  const contentOffset = (() => {
    if ((isDesktop && !isSidebarOpenDesktop) || isMobile) {
      return 0
    } else if (isDesktop && isSidebarCollapsed) {
      return theme.sidebar.widthCollapsed
    } else {
      return theme.sidebar.width
    }
  })()

  const HeaderComponent = header
  const SidebarComponent = sidebar
  const FooterComponent = footer

  function handleSidebarToggleOpenMobile() {
    setIsSidebarOpenMobile(!isSidebarOpenMobile)
  }

  function handleSidebarToggle() {
    // Open/close on mobile
    if (isMobile) {
      setIsSidebarOpenMobile(!isSidebarOpenMobile)
    }
    // Collapse/uncollapse on desktop
    else {
      setIsSidebarCollapsed(!isSidebarCollapsed)
    }
  }

  function handleSidebarToggleCollapse() {
    setIsSidebarCollapsed(!isSidebarCollapsed)
  }

  return (

      <div
        ref={refHeaderContainer}
        className={clsx(classes.headerContainer)}
        style={{
          width: `calc(100% - ${contentOffset}px)`,
        }}
      >
        {HeaderComponent && <HeaderComponent onToggleClick={handleSidebarToggle} />}

        {/* Mobile sidebar */}
        <Hidden mdUp implementation="css">
          <Drawer
            variant="temporary"
            open={isSidebarOpenMobile}
            onClose={handleSidebarToggleOpenMobile}
            classes={{
              paper: clsx(classes.drawer), //  classes.drawerMobile
            }}
            ModalProps={{
              keepMounted: true, // Better open performance on mobile.
            }}
          >
            {SidebarComponent && <SidebarComponent />}
          </Drawer>
        </Hidden>
        {/* Desktop sidebar */}
        <Hidden smDown implementation="css">
          <Drawer
            classes={{
              paper: clsx(classes.drawer),
            }}
            variant="permanent"
          >
            {SidebarComponent && <SidebarComponent isCollapsed={isSidebarCollapsed} />}
          </Drawer>
        </Hidden>

{children}

          {FooterComponent && <FooterComponent />}

  )
}

DashboardLayout.defaultProps = {
  header: AppHeader,
  sidebar: AppSidebar,
  footer: AppFooter,
}

DashboardLayout.propTypes = {
  header: PropTypes.elementType,
  sidebar: PropTypes.elementType,
  footer: PropTypes.elementType,
}

const useStyles = makeStyles(theme => ({
  dashboardContainer: {
    display: 'flex',
    background: '#f5f5f5',
  },
  headerContainer: {
    top: 0,
    left: 'auto',
    right: 0,
    display: 'flex',
    alignItems: 'stretch',
    position: 'absolute',
    zIndex: theme.zIndex.drawer + 1,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  sidebarContainer: {
    display: 'flex',
    alignItems: 'stretch',
    position: 'relative',
    top: 0,
    bottom: 0,
    flexDirection: 'row',
    width: theme.sidebar.width,
    // [theme.breakpoints.up('md')]: {
    //   width: theme.sidebar.width,
    //   flexShrink: 0,
    // },
    transition: theme.transitions.create('width', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  sidebarContainerMobile: {
    width: 0,
  },
  sidebarContainerCollapsed: {
    width: theme.sidebar.widthCollapsed,
  },
  drawer: {
    width: '100%',
    position: 'absolute',
    [theme.breakpoints.down('sm')]: {
      width: theme.sidebar.width,
      flexShrink: 0,
    },
  },
  mainContainer: {
    flexGrow: 1,
    height: '100vh',
    overflow: 'auto',
    flexDirection: 'column',
    display: 'flex',
  },
  contentContainer: {
    display: 'flex',
    position: 'relative',
    flex: 1,
  },
  footerContainer: {
    position: 'relative',
  },
}))

export default DashboardLayout
<|endoftext|>


<commit_before>const css = require('./app.scss');
import {TweenMax, Power2, TimelineLite} from "gsap";
import scrollTo from '../node_modules/gsap/ScrollToPlugin';
import ScrollMagic from 'scrollmagic';
import 'imports-loader?define=>false!scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js';
import 'imports-loader?define=>false!scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js';

import React from 'react';
import ReactDOM from 'react-dom';
import Intro from './components/intro/Intro';
import Geography from './components/geography/Geography';
import Cities from './components/cities/Cities';
import Sights from './components/sights/Sights';
import Hotels from './components/hotels/Hotels';
import Cuisine from './components/cuisine/Cuisine';
import Language from './components/language/Language';
import Footer from './components/footer/Footer';

ReactDOM.render(

        <Intro />
        <Geography />
        <Cities />
        <Sights />
        <Hotels />
        <Cuisine />
        <Language />

,
    document.getElementById('root')
);

/*======================= Begin ScrollMagic Animations =======================*/

/*----- h1/h2 rotations -----*/
$(document).ready(function(){

    var hosGeldiniz = $('#hos-geldiniz');
    var welcome = $('#welcome');

    TweenLite.from(hosGeldiniz, 0.7, {delay: 0.5, y: -30, opacity: 0, rotation: -10});

    TweenLite.from(welcome, 0.7, {delay: 0.5, y: 30, opacity: 0, rotation: 10});

    TweenMax.staggerFrom("#top-nav li", 0.7, { ease:  Power0.easeNone, delay: 1, opacity: 0, y:25, rotation: 10}, 0.15);

    var controller = new ScrollMagic.Controller();
    var divFadeController = new ScrollMagic.Controller();

    var pinTopNavScene = new ScrollMagic.Scene({
        triggerElement: '#top-nav',
        triggerHook: 0,
        duration: '60%'
    })
    .setPin('#top-nav')
    .addTo(controller);

    var bottomNavTween = TweenMax.staggerFrom("#bottom-nav li", 0.7, { ease:  Power0.easeNone, delay: 0.3, opacity: 0, y:-25, rotation: 10}, 0.15);

    var bottomNavScene = new ScrollMagic.Scene({
        triggerElement: '#bottom-nav',
        triggerHook: .95,
        reverse: false
    })

    .setTween(bottomNavTween)
    .addIndicators({
        name:"bottom-nav",
        colorTrigger: 'green',
        colorStart: '#FFF'
    })
    .addTo(controller);

    /*----- header animations -----*/
    $('.scrollmagic-header').each(function(){
        var headerScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.8,
            reverse: false
        })
        .setClassToggle(this, 'fade-in')
        /*
        .addIndicators({
            name: 'fade scene',
            colorTrigger: 'black',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })

    /* ----- background change scenes  -----*/
    var threeChangeScene = new ScrollMagic.Scene({
        triggerElement: '.Three',
        triggerHook: 0.6,
        offset: 700,
        reverse: true
    })
    .setClassToggle('.Three', 'Three-background-change')
    .addIndicators({
            name: 'background change scene',
            colorTrigger: 'orange',
            colorStart: 'white'
        })
    .addTo(controller);

    var threeChangeFadeoutHeaderScene = new ScrollMagic.Scene({
        triggerElement: '.Three',
        triggerHook: 0.6,
        offset: 700,
        reverse: true
    })
    .setClassToggle('#uzungol', 'fadeout')
    .addIndicators({
            name: 'background change scene',
            colorTrigger: 'orange',
            colorStart: 'white'
        })
    .addTo(controller);

    /*----- div fadeout animations -----*/
    var oneFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.One',
        triggerHook: 0.1,
        offset: 850,
        reverse: true
    })
    .setClassToggle('.One', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    var fourFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Four',
        triggerHook: 0.1,
        offset: 700,
        reverse: true
    })
    .setClassToggle('.Four', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    /*

    var tenFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Ten',
        triggerHook: 0.1,
        offset: 800,
        reverse: true
    })
    .setClassToggle('.Ten', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);*/

    var thirteenFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Thirteen',
        triggerHook: 0.1,
        offset: 1200,
        reverse: true
    })
    .setClassToggle('.Thirteen', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    var fifteenFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Fifteen',
        triggerHook: 0.1,
        offset: 1300,
        reverse: true
    })
    .setClassToggle('.Fifteen', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    var eighteenFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Eighteen',
        triggerHook: 0.1,
        offset: 700,
        reverse: true
    })
    .setClassToggle('.Eighteen', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    /*----- chevron animations -----*/
    $('.scrollmagic-chevron').each(function(){
        var chevronScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.8,
            reverse: false
        })
        .setClassToggle(this, 'horizontal-fade')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })

    /*----- information square animations -----*/
    $('.scrollmagic-info-squares').each(function(){
        var chevronScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.8,
            reverse: false
        })
        .setClassToggle(this, 'horizontal-fade')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })

    /*----- description animations -----*/
    $('.scrollmagic-desc').each(function(){
        var descScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.85,
            reverse: false
        })
        .setClassToggle(this, 'horizontal-fade')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })

    /*----- vocabulary animations -----*/
    $('.Twenty-one ul li').each(function(){
        var vocabScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.95,
            reverse: false
        })
        .setClassToggle(this, 'vocab-fadein')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })
/*======================= End ScrollMagic Animations =======================*/
});

$(window).scroll(function(){
    var wScroll = $(this).scrollTop();
    console.log(wScroll);
    var largeDesktop = window.matchMedia( "(min-width: 0px)" );

    if(largeDesktop.matches){

        $('.One-inner').css({
            'background-position':  '50% ' + (50 + wScroll/35) + '%'
        })

        $('#hos-geldiniz').css({
            'transform': 'translateX('  + wScroll/10 + 'px) translateY('  + wScroll/4 + 'px)'

        })

        $('#welcome').css({
            'transform': 'translateX('  + wScroll/-10 + 'px) translateY('  + wScroll/4 + 'px)'
        })

        /*
        if(wScroll > 300){
            $('.One').css({
                'background': 'transparent'
            })
        }
        */

        $('.Three-inner').css({
            'background-position':  '50% ' + (50 + wScroll/45) + '%'
        })

        $('.Three').css({
            'background-position':  '50% ' + (50 + wScroll/45) + '%'
        })

        $('#ataturk').css({
            'opacity': Math.pow((wScroll/3000),200)
        })

        $('#founder').css({
            'opacity': Math.pow((wScroll/3000),200)
        })

        $('.Four').css({
            'background-position':  '50% ' + (50 + -wScroll/90) + '%'
        })

        $('.Four-inner-1').css({
            'opacity': 1 - Math.pow((wScroll/3000),80)
        })

        $('.Twelve-inner').css({
            'opacity': 1 - Math.pow((wScroll/13600),180)
        })

        $('.Twelve').css({
            'opacity': 1 - Math.pow((wScroll/15700),20)
        })

        $('.Thirteen-inner').css({
            'opacity': 1 - Math.pow((wScroll/14800),250)
        })

        $('.Fourteen > .flex-container > .flex-item:nth-child(1)').on('click', function(){
            window.location = "https://www.trivago.com/istanbul-32123/hotel";
        });

        $('.Fourteen > .flex-container > .flex-item:nth-child(2)').on('click', function(){
            window.location = "https://www.trivago.com/izmir-32103/hotel";
        });

        $('.Fourteen > .flex-container > .flex-item:nth-child(3)').on('click', function(){
            window.location = "https://www.trivago.com/antalya-32134/hotel";
        });

        $('.Fourteen > .flex-container > .flex-item:nth-child(4)').on('click', function(){
            window.location = "https://www.trivago.com/ankara-32205/hotel";
        });

        $('.Fourteen .flex-item:nth-child(5)').on('click', function(){
            window.location = "https://www.trivago.com/nevsehir-509044/hotel";
        });

        $('.Fourteen .flex-item:nth-child(6)').on('click', function(){
            window.location = "https://www.trivago.com/trabzon-32190/hotel/novotel-trabzon-950093";
        });

        $('.Fourteen .flex-item:nth-child(7)').on('click', function(){
            window.location = "https://www.trivago.com/bursa-509192/hotel";
        });

        $('.Fourteen .flex-item:nth-child(8)').on('click', function(){
            window.location = ("https://www.trivago.com/konya-509022/hotel");

        });

        $('.Fifteen-inner').css({
            'opacity': 1 - Math.pow((wScroll/16900),400)
        })

        $('.Seventeen-inner').css({
            'opacity': 1 - Math.pow((wScroll/19000),400)
        })

        $('.Eighteen-inner').css({
            'opacity': 1 - Math.pow((wScroll/20400),400)
        })

        $('.Eighteen').css({
            'opacity': 1 - Math.pow((wScroll/21200),400)
        })

        $('.Twenty-one').css({
            'opacity': 1 - Math.pow((wScroll/23700),400)
        })
    }
})
<commit_msg>More jQuery animations converted to scrollmagic<commit_after>const css = require('./app.scss');
import {TweenMax, Power2, TimelineLite} from "gsap";
import scrollTo from '../node_modules/gsap/ScrollToPlugin';
import ScrollMagic from 'scrollmagic';
import 'imports-loader?define=>false!scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js';
import 'imports-loader?define=>false!scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js';

import React from 'react';
import ReactDOM from 'react-dom';
import Intro from './components/intro/Intro';
import Geography from './components/geography/Geography';
import Cities from './components/cities/Cities';
import Sights from './components/sights/Sights';
import Hotels from './components/hotels/Hotels';
import Cuisine from './components/cuisine/Cuisine';
import Language from './components/language/Language';
import Footer from './components/footer/Footer';

ReactDOM.render(

        <Intro />
        <Geography />
        <Cities />
        <Sights />
        <Hotels />
        <Cuisine />
        <Language />

,
    document.getElementById('root')
);

/*======================= Begin ScrollMagic Animations =======================*/

/*----- h1/h2 rotations -----*/
$(document).ready(function(){

    var hosGeldiniz = $('#hos-geldiniz');
    var welcome = $('#welcome');

    TweenLite.from(hosGeldiniz, 0.7, {delay: 0.5, y: -30, opacity: 0, rotation: -10});

    TweenLite.from(welcome, 0.7, {delay: 0.5, y: 30, opacity: 0, rotation: 10});

    TweenMax.staggerFrom("#top-nav li", 0.7, { ease:  Power0.easeNone, delay: 1, opacity: 0, y:25, rotation: 10}, 0.15);

    var controller = new ScrollMagic.Controller();
    var divFadeController = new ScrollMagic.Controller();

    var pinTopNavScene = new ScrollMagic.Scene({
        triggerElement: '#top-nav',
        triggerHook: 0,
        duration: '60%'
    })
    .setPin('#top-nav')
    .addTo(controller);

    var bottomNavTween = TweenMax.staggerFrom("#bottom-nav li", 0.7, { ease:  Power0.easeNone, delay: 0.3, opacity: 0, y:-25, rotation: 10}, 0.15);

    var bottomNavScene = new ScrollMagic.Scene({
        triggerElement: '#bottom-nav',
        triggerHook: .95,
        reverse: false
    })

    .setTween(bottomNavTween)
    .addIndicators({
        name:"bottom-nav",
        colorTrigger: 'green',
        colorStart: '#FFF'
    })
    .addTo(controller);

    /*----- header animations -----*/
    $('.scrollmagic-header').each(function(){
        var headerScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.8,
            reverse: false
        })
        .setClassToggle(this, 'fade-in')
        /*
        .addIndicators({
            name: 'fade scene',
            colorTrigger: 'black',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })

    /* ----- background change scenes  -----*/
    $('.scrollmagic-inner-fadeout').each(function(){
        var chevronScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.55,
            offset: 700,
            reverse: true
        })
        .setClassToggle(this, 'fadeout')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })
    /*
    var threeChangeScene = new ScrollMagic.Scene({
        triggerElement: '.Three-inner',
        triggerHook: 0.65,
        offset: 700,
        reverse: true
    })
    .setClassToggle('.Three-inner', 'fadeout')
    .addIndicators({
            name: 'background fadeout scene',
            colorTrigger: 'orange',
            colorStart: 'white'
        })
    .addTo(controller); */

    /*----- div fadeout animations -----*/
    var oneFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.One',
        triggerHook: 0.1,
        offset: 850,
        reverse: true
    })
    .setClassToggle('.One', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    var fourFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Four',
        triggerHook: 0.1,
        offset: 700,
        reverse: true
    })
    .setClassToggle('.Four', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    var tenFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Ten',
        triggerHook: 0.1,
        offset: 850,
        reverse: true
    })
    .setClassToggle('.Ten', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    var thirteenFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Thirteen',
        triggerHook: 0.1,
        offset: 1200,
        reverse: true
    })
    .setClassToggle('.Thirteen', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    var fifteenFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Fifteen',
        triggerHook: 0.1,
        offset: 1300,
        reverse: true
    })
    .setClassToggle('.Fifteen', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    var eighteenFadeoutScene = new ScrollMagic.Scene({
        triggerElement: '.Eighteen',
        triggerHook: 0.1,
        offset: 1300,
        reverse: true
    })
    .setClassToggle('.Eighteen', 'fadeout')

    .addIndicators({
        name: 'div fadeout',
        colorTrigger: 'yellow',
        colorStart: '#75C695'
    })
    .addTo(controller);

    /*----- chevron animations -----*/
    $('.scrollmagic-chevron').each(function(){
        var chevronScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.8,
            reverse: false
        })
        .setClassToggle(this, 'horizontal-fade')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })

    /*----- information square animations -----*/
    $('.scrollmagic-info-squares').each(function(){
        var chevronScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.8,
            reverse: false
        })
        .setClassToggle(this, 'horizontal-fade')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })

    /*----- description animations -----*/
    $('.scrollmagic-desc').each(function(){
        var descScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.85,
            reverse: false
        })
        .setClassToggle(this, 'horizontal-fade')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })

    /*----- vocabulary animations -----*/
    $('.Twenty-one ul li').each(function(){
        var vocabScene = new ScrollMagic.Scene({
            triggerElement: this,
            triggerHook: 0.95,
            reverse: false
        })
        .setClassToggle(this, 'vocab-fadein')
        /*
        .addIndicators({
            name: 'horizontal fade',
            colorTrigger: 'yellow',
            colorStart: '#75C695'
        })*/
        .addTo(controller);
    })
/*======================= End ScrollMagic Animations =======================*/
});

$(window).scroll(function(){
    var wScroll = $(this).scrollTop();
    console.log(wScroll);
    var largeDesktop = window.matchMedia( "(min-width: 0px)" );

    if(largeDesktop.matches){

        $('.One-inner').css({
            'background-position':  '50% ' + (50 + wScroll/35) + '%',
            'filter': 'contrast(' + (100 - wScroll/8) + '%) brightness(' + (100 + wScroll/15) + '%)'

        })

        $('#hos-geldiniz').css({
            'transform': 'translateX('  + wScroll/10 + 'px) translateY('  + wScroll/4 + 'px)'
        })

        $('#welcome').css({
            'transform': 'translateX('  + wScroll/-10 + 'px) translateY('  + wScroll/4 + 'px)'
        })

        $('.Three-inner').css({
            'background-position':  '50% ' + (50 + wScroll/45) + '%'
        })

        $('.Three').css({
            'background-position':  '50% ' + (50 + wScroll/45) + '%'
        })

        $('#ataturk').css({
            'opacity': Math.pow((wScroll/3000),200)
        })

        $('#founder').css({
            'opacity': Math.pow((wScroll/3000),200)
        })

        $('.Four').css({
            'background-position':  '50% ' + (50 + -wScroll/90) + '%'
        })

        $('.Four-inner-1').css({
            'opacity': 1 - Math.pow((wScroll/3000),80)
        })

        $('.Fourteen > .flex-container > .flex-item:nth-child(1)').on('click', function(){
            window.location = "https://www.trivago.com/istanbul-32123/hotel";
        });

        $('.Fourteen > .flex-container > .flex-item:nth-child(2)').on('click', function(){
            window.location = "https://www.trivago.com/izmir-32103/hotel";
        });

        $('.Fourteen > .flex-container > .flex-item:nth-child(3)').on('click', function(){
            window.location = "https://www.trivago.com/antalya-32134/hotel";
        });

        $('.Fourteen > .flex-container > .flex-item:nth-child(4)').on('click', function(){
            window.location = "https://www.trivago.com/ankara-32205/hotel";
        });

        $('.Fourteen .flex-item:nth-child(5)').on('click', function(){
            window.location = "https://www.trivago.com/nevsehir-509044/hotel";
        });

        $('.Fourteen .flex-item:nth-child(6)').on('click', function(){
            window.location = "https://www.trivago.com/trabzon-32190/hotel/novotel-trabzon-950093";
        });

        $('.Fourteen .flex-item:nth-child(7)').on('click', function(){
            window.location = "https://www.trivago.com/bursa-509192/hotel";
        });

        $('.Fourteen .flex-item:nth-child(8)').on('click', function(){
            window.location = ("https://www.trivago.com/konya-509022/hotel");

        });
    }
})
<|endoftext|>


<commit_before>import { search } from './component/search'
import { song } from './component/song'
import { lrc } from './component/lrc'
import { getArtistAlbums } from './component/getArtistAlbums'
import { getAlbums } from './component/getAlbums'

let api = {
  search: search,
  song: song,
  lrc: lrc,
  getArtistAlbums: getArtistAlbums,
  getAlbums: getAlbums

}
export {api}
<commit_msg>Add getPlaylists<commit_after>import { search } from './component/search'
import { song } from './component/song'
import { lrc } from './component/lrc'
import { getArtistAlbums } from './component/getArtistAlbums'
import { getAlbums } from './component/getAlbums'
import { getPlaylists } from './component/getPlaylists'

let api = {
  search: search,
  song: song,
  lrc: lrc,
  getArtistAlbums: getArtistAlbums,
  getAlbums: getAlbums,
  getPlaylists: getPlaylists

}
export {api}
<|endoftext|>


<commit_before>const QuestionBodyAdapter = {
  uploadByQuestionId: (lectureId, questionState) => {
    const {
      TitleInputValue,
      checkedQuizIndex,
      secsOfQuiz
    } = questionState;

    return Promise.resolve({
      lecture_id: lectureId,
      content: TitleInputValue,
      correct_answer: checkedQuizIndex.toString(),
      question_at: parseInt(secsOfQuiz)
    });
  }
};

const ChoiceBodyAdapter = {
  upload: (questionId, singleChoiceValues) => {
    const {
      choiceTextValue
    } = singleChoiceValues;

    return Promise.resolve({
      question_id: questionId,
      answer: choiceTextValue
    });
  }
};

const AnswerBodyAdapter = {
  uploadByQuestionId: (questionId, indexOfSelectedChoice) => Promise.resolve({
    question_id: parseInt(questionId),
    answer: indexOfSelectedChoice
  })
};

const LectureBodyAdapter = {
  upload: ({
    questionState,
    title,
    description,
    subject,
    textbook,
    videoURL,
    thumbURL
  }) => Promise.resolve({
    title,
    subject,
    content: description,
    textbook_range: textbook,
    url: videoURL,
    thumbnail_url: thumbURL,
    duration: questionState.duration
  })
};

export {
  QuestionBodyAdapter,
  ChoiceBodyAdapter,
  AnswerBodyAdapter,
  LectureBodyAdapter
};
<commit_msg>정답 저장 수정.<commit_after>const QuestionBodyAdapter = {
  uploadByQuestionId: (lectureId, questionState) => {
    const {
      SingleChoiceValues,
      TitleInputValue,
      checkedQuizIndex,
      secsOfQuiz
    } = questionState;
    console.log(questionState);
    return Promise.resolve({
      lecture_id: lectureId,
      content: TitleInputValue,
      correct_answer: SingleChoiceValues[checkedQuizIndex].choiceTextValue,
      question_at: parseInt(secsOfQuiz)
    });
  }
};

const ChoiceBodyAdapter = {
  upload: (questionId, singleChoiceValues) => {
    const {
      choiceTextValue
    } = singleChoiceValues;

    return Promise.resolve({
      question_id: questionId,
      answer: choiceTextValue
    });
  }
};

const AnswerBodyAdapter = {
  uploadByQuestionId: (questionId, indexOfSelectedChoice) => Promise.resolve({
    question_id: parseInt(questionId),
    answer: indexOfSelectedChoice
  })
};

const LectureBodyAdapter = {
  upload: ({
    questionState,
    title,
    description,
    subject,
    textbook,
    videoURL,
    thumbURL
  }) => Promise.resolve({
    title,
    subject,
    content: description,
    textbook_range: textbook,
    url: videoURL,
    thumbnail_url: thumbURL,
    duration: questionState.duration
  })
};

export {
  QuestionBodyAdapter,
  ChoiceBodyAdapter,
  AnswerBodyAdapter,
  LectureBodyAdapter
};
<|endoftext|>


<commit_before>var linus = linus || {};
linus.canadapost = linus.canadapost || {};

linus.canadapost.d2po = linus.canadapost.d2po || (function($, Common)
{
    'use strict';

    var loaded = false;
    var apiKey = null;
    var map;

    var markers = [];
    var offices;

    function setApiKey(key)
    {
        apiKey = key;
    }

    function getApiKey()
    {
        return apiKey;
    }

    function lazyLoadGoogleMapsLibrary()
    {
        if (getApiKey() == null) {
            throw Exception('No GMaps Api key provided. Terminating.');
        }

        var promise = null;

        //Make sure we only load the GMaps library once.
        if (!loaded) {
            promise = $.when(
                $.ajax({
                    url: "https://maps.googleapis.com/maps/api/js?key=" + getApiKey(),
                    dataType: 'script',
                    cache: true,
                    crossDomain: true
                })
            ).then(function () {
                loaded = true;
            });
        } else {
            promise = $.when();
        }

        return promise;
    }

    /**
     * Load the office location data from Canada Post
     * @param epicenter
     * @returns {*}
     */
    function getPostOfficeData(epicenter)
    {
        return $.ajax('/canadapost/office/nearest?postal_code='+epicenter.postalCode+'&city='+epicenter.city+'&province='+epicenter.province, {
            method: 'GET',
            dataType: 'json'
        });
    }

    //Get the lat/long coordinates for the postal code
    function getPostalCodeCoordinates(postalCode, callback)
    {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({address: postalCode}, callback);
    }

    /**
     * Load the google maps library, then center on the give area code
     * @param $target
     * @param epicenter
     * @returns {*}
     */
    function createMap($target, epicenter)
    {
        return lazyLoadGoogleMapsLibrary()
            .then(function () {
                getPostalCodeCoordinates(epicenter.postalCode, function(results, status){
                    if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
                        map = new google.maps.Map($target[0], {
                            center: results[0].geometry.location
                        });
                    }
                });
            });
    }

    /**
     * Load the post office data from Canada Post, and inject it as map markers.
     * @param epicenter
     */
    function displayOfficeMarkers(epicenter)
    {
        getPostOfficeData(epicenter).done(function(response){
            offices = response.payload;
            var $mapDiv = $(map.getDiv());

            $mapDiv.trigger('onOfficesLoaded', [response.payload]);

            var markerBounds = new google.maps.LatLngBounds();

            $.each(response.payload, function(index, office){
                var location = new google.maps.LatLng(
                    office.address.latitude,
                    office.address.longitude
                );

                var marker = new google.maps.Marker({
                    position: location,
                    title: office.name,
                    map: map,
                    animation: google.maps.Animation.DROP
                });

                markerBounds.extend(location);

                var infowindow = new google.maps.InfoWindow({
                    content: office.name + '
' + office.address['office-address']
                });

                marker.addListener('click', function() {
                    infowindow.open(map, marker);
                    $mapDiv.trigger('onOfficeMarkerClick', [office]);
                });

                markers.push(marker);
            });

            map.fitBounds(markerBounds);
        });
    }

    /**
     * Zoom and center on a specific location, generally to show an office
     * at a sane default zoom level.
     * @param latitude
     * @param longitude
     */
    function recenterAndZoom(latitude, longitude)
    {
        var markerBounds = new google.maps.LatLngBounds();
        var location = new google.maps.LatLng(
            latitude,
            longitude
        );
        markerBounds.extend(location);
        map.fitBounds(markerBounds);
        map.setZoom(16);
    }

    /**
     * Resets the zoom and map bounds to contain all displayed post offices.
     */
    function resetZoom()
    {
        var markerBounds = new google.maps.LatLngBounds();
        $.each(offices, function(index, office) {
            var location = new google.maps.LatLng(
                office.address.latitude,
                office.address.longitude
            );

            markerBounds.extend(location);
        });
        map.fitBounds(markerBounds);
    }

    /**
     * Wrap map creation (if not already created) and adding markers
     */
    function render(target, epicenter, apiKey)
    {
        var $target = $(target);

        if (typeof apiKey == 'undefined' || apiKey == null) {
           apiKey = linus.common.getCspData('gmaps_api_key');
        }

        setApiKey(apiKey);

        $.when(createMap($target, epicenter))
            .then(function(){
                displayOfficeMarkers(epicenter);
            });
    }

    /**
     * Get the current map object
     */
    function getMap()
    {
        return map;
    }

    return {
        getMap: getMap,
        recenterAndZoom: recenterAndZoom,
        render: render,
        resetZoom: resetZoom
    };
})(jQuery, linus.common);
<commit_msg>Add more office info to window.<commit_after>var linus = linus || {};
linus.canadapost = linus.canadapost || {};

linus.canadapost.d2po = linus.canadapost.d2po || (function($, Common)
{
    'use strict';

    var loaded = false;
    var apiKey = null;
    var map;

    var markers = [];
    var offices;

    function setApiKey(key)
    {
        apiKey = key;
    }

    function getApiKey()
    {
        return apiKey;
    }

    function lazyLoadGoogleMapsLibrary()
    {
        if (getApiKey() == null) {
            throw Exception('No GMaps Api key provided. Terminating.');
        }

        var promise = null;

        //Make sure we only load the GMaps library once.
        if (!loaded) {
            promise = $.when(
                $.ajax({
                    url: "https://maps.googleapis.com/maps/api/js?key=" + getApiKey(),
                    dataType: 'script',
                    cache: true,
                    crossDomain: true
                })
            ).then(function () {
                loaded = true;
            });
        } else {
            promise = $.when();
        }

        return promise;
    }

    /**
     * Load the office location data from Canada Post
     * @param epicenter
     * @returns {*}
     */
    function getPostOfficeData(epicenter)
    {
        return $.ajax('/canadapost/office/nearest?postal_code='+epicenter.postalCode+'&city='+epicenter.city+'&province='+epicenter.province, {
            method: 'GET',
            dataType: 'json'
        });
    }

    //Get the lat/long coordinates for the postal code
    function getPostalCodeCoordinates(postalCode, callback)
    {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({address: postalCode}, callback);
    }

    /**
     * Load the google maps library, then center on the give area code
     * @param $target
     * @param epicenter
     * @returns {*}
     */
    function createMap($target, epicenter)
    {
        return lazyLoadGoogleMapsLibrary()
            .then(function () {
                getPostalCodeCoordinates(epicenter.postalCode, function(results, status){
                    if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
                        map = new google.maps.Map($target[0], {
                            center: results[0].geometry.location
                        });
                    }
                });
            });
    }

    /**
     * Load the post office data from Canada Post, and inject it as map markers.
     * @param epicenter
     */
    function displayOfficeMarkers(epicenter)
    {
        getPostOfficeData(epicenter).done(function(response){
            offices = response.payload;
            var $mapDiv = $(map.getDiv());

            $mapDiv.trigger('onOfficesLoaded', [response.payload]);

            var markerBounds = new google.maps.LatLngBounds();

            $.each(response.payload, function(index, office){
                var location = new google.maps.LatLng(
                    office.address.latitude,
                    office.address.longitude
                );

                var marker = new google.maps.Marker({
                    position: location,
                    title: office.name,
                    map: map,
                    animation: google.maps.Animation.DROP
                });

                markerBounds.extend(location);

                var infowindow = new google.maps.InfoWindow({
                    content: office.name + '
' + office.address['office-address'] + '
' + office.address.city  + ', ' + office.address['postal-code']
                });

                marker.addListener('click', function() {
                    infowindow.open(map, marker);
                    $mapDiv.trigger('onOfficeMarkerClick', [office]);
                });

                markers.push(marker);
            });

            map.fitBounds(markerBounds);
        });
    }

    /**
     * Zoom and center on a specific location, generally to show an office
     * at a sane default zoom level.
     * @param latitude
     * @param longitude
     */
    function recenterAndZoom(latitude, longitude)
    {
        var markerBounds = new google.maps.LatLngBounds();
        var location = new google.maps.LatLng(
            latitude,
            longitude
        );
        markerBounds.extend(location);
        map.fitBounds(markerBounds);
        map.setZoom(16);
    }

    /**
     * Resets the zoom and map bounds to contain all displayed post offices.
     */
    function resetZoom()
    {
        var markerBounds = new google.maps.LatLngBounds();
        $.each(offices, function(index, office) {
            var location = new google.maps.LatLng(
                office.address.latitude,
                office.address.longitude
            );

            markerBounds.extend(location);
        });
        map.fitBounds(markerBounds);
    }

    /**
     * Wrap map creation (if not already created) and adding markers
     */
    function render(target, epicenter, apiKey)
    {
        var $target = $(target);

        if (typeof apiKey == 'undefined' || apiKey == null) {
           apiKey = linus.common.getCspData('gmaps_api_key');
        }

        setApiKey(apiKey);

        $.when(createMap($target, epicenter))
            .then(function(){
                displayOfficeMarkers(epicenter);
            });
    }

    /**
     * Get the current map object
     */
    function getMap()
    {
        return map;
    }

    return {
        getMap: getMap,
        recenterAndZoom: recenterAndZoom,
        render: render,
        resetZoom: resetZoom
    };
})(jQuery, linus.common);
<|endoftext|>


<commit_before>window.Rendxx = window.Rendxx || {};
window.Rendxx.Game = window.Rendxx.Game || {};
window.Rendxx.Game.Ghost = window.Rendxx.Game.Ghost || {};
window.Rendxx.Game.Ghost.Renderer = window.Rendxx.Game.Ghost.Renderer || {};

/**
 * Setup map, including light, wall and other stuff
 */
(function (RENDERER) {
    var Data = RENDERER.Data;

    /**
     * Create walls, desks, chairs and doors
     */
    var SetupWall = function (scene) {
        var ground, ceiling, walls;

        /*create ground*/
        var planeGeometry = new THREE.PlaneGeometry(100, 100, 100);
        var planeMaterial = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
        ground = new THREE.Mesh(planeGeometry, planeMaterial);
        ground.rotation.x = -.5 * Math.PI;
        ground.receiveShadow = true;
        scene.add(ground);

        /*create ceiling*/
        var planeGeometry = new THREE.PlaneGeometry(100, 100, 100);
        var planeMaterial = new THREE.MeshBasicMaterial({ color: 0xeeeeee });
        ceiling = new THREE.Mesh(planeGeometry, planeMaterial);
        ceiling.rotation.x = .5 * Math.PI;
        ceiling.position.y = 7.5;
        scene.add(ceiling);

        /*add wall*/
        walls = [];
        var createWall = function (z, x, len, wid, rotate, deep) {
            var cubeGeometry = new THREE.BoxGeometry(len, deep || 8, wid);
            var cubeMaterial = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
            var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

            cube.rotation.y = rotate / 180 * Math.PI;
            cube.position.x = x;
            cube.position.y = 3.5;
            cube.position.z = z
            cube.castShadow = true;
            cube.receiveShadow = true;
            scene.add(cube);

            walls.push(cube);

            var cubeGeometry2 = new THREE.BoxGeometry(len, 1, wid);
            var cubeMaterial2 = new THREE.MeshBasicMaterial({ color: 0x333333 });
            var cube2 = new THREE.Mesh(cubeGeometry2, cubeMaterial2);

            cube2.rotation.y = rotate / 180 * Math.PI;
            cube2.position.x = x;
            cube2.position.y = 8;
            cube2.position.z = z
            scene.add(cube2);

            walls.push(cube2);
        }
        createWall(0, 10, 20, 2, 90);
        createWall(11, 7, 8, 2, 0);
        createWall(4, 4, 12, 2, 90);
        createWall(-11, 3, 16, 2, 0);
        createWall(-3, 0, 10, 2, 0);

        return {
            ground: ground,
            wall: walls
        };
    };

    /**
     * Create items
     */
    var SetupItem = function (scene) {

    };

    /**
     * Create game map
     */
    var SetupMap = function (entity, mapData) {
        var wall = SetupWall(entity.env.scene);
        var light = SetupLight(entity.env.scene);
        var item = SetupItem(entity.env.scene);

        return {
            light: light,
            wall: wall,
            item: item
        };
    };

    var Map = function (entity) {
        // private data ----------------------------
        var that = this;

        // public data -----------------------------
        this.wall = null;
        this.light = null;
        this.item = null;
        this.ground = null;

        // public method ---------------------------
        /**
         * Reset map with given data
         */
        this.reset = function (data) {
            if (data == null) throw new Error('Data missing');
            setupGround(entity.env.scene, data.grid);
            setupWall(entity.env.scene, data.wall, data.stuff);
            setupItem(entity.env.scene, data.item);
        };

        // private method

        var setupLight = function (scene) {
            if (that.light != null) {
                for (var i = 0, l = that.light.length; i < l; i++) scene.remove(that.light[i]);
                that.light = null;
            }

            that.lights = [
                new THREE.AmbientLight(),
                new THREE.SpotLight()
            ];

            var lightTarget = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshPhongMaterial({ color: 0xff3300 }));
            scene.add(lightTarget);

            // Ambient
            that.lights[0].color.setHex(Data.light.ambient.ambColor);
            scene.add(that.lights[0]);

            // Spot
            that.lights[1].castShadow = true;
            that.lights[1].position.set(Data.light.spot.lightX, Data.light.spot.lightY, Data.light.spot.lightZ);
            that.lights[1].intensity = Data.light.spot.intensity;
            that.lights[1].shadowCameraNear = Data.light.spot.shadowCameraNear;
            that.lights[1].shadowCameraFar = Data.light.spot.shadowCameraFar;
            that.lights[1].shadowCameraVisible = Data.light.spot.shadowCameraVisible;
            that.lights[1].shadowBias = Data.light.spot.shadowBias;
            that.lights[1].shadowDarkness = Data.light.spot.shadowDarkness;
            scene.add(that.lights[1]);
        };

        var setupGround = function (scene, grid) {
            if (that.ground != null) {
                for (var i = 0, l = that.ground.length; i < l; i++) scene.remove(that.ground[i]);
                that.ground = null;
            }

            /*create ground*/
            var planeGeometry = new THREE.PlaneGeometry(grid.width * Data.grid.size, grid.height * Data.grid.size);
            var planeMaterial = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
            var ground = new THREE.Mesh(planeGeometry, planeMaterial);
            ground.rotation.x = -.5 * Math.PI;
            ground.receiveShadow = true;
            scene.add(ground);

            /*create ceiling*/
            var planeGeometry = new THREE.PlaneGeometry(grid.width * Data.grid.size, grid.height * Data.grid.size);
            var planeMaterial = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
            var ceiling = new THREE.Mesh(planeGeometry, planeMaterial);
            ceiling.rotation.x = .5 * Math.PI;
            ceiling.position.y = 7.5;
            scene.add(ceiling);

            that.ground = [
                ground,
                ceiling
            ];
        };

        var setupWall = function (scene, wall, stuff) {
            if (that.wall != null) {
                for (var i = 0, l = that.wall.length; i < l; i++) scene.remove(that.wall[i]);
                that.wall = null;
            }
        };

        var setupItem = function (item) {
            if (that.item != null) {
                for (var i = 0, l = that.item.length; i < l; i++) scene.remove(that.item[i]);
                that.item = null;
            }
            if (item == null || item.length == 0) return;
        };

        // Add stuff
        var addWall = function (x, y, rotation, len) {

        };

        var addStyff = function (dat) {

        };

        var _init = function () {
            setupLight(entity.env.scene);
        };

        _init();
    };

    /**
     * Game map
     * @param {game entity} entity - Game entity
     * @param {object} mapData - data used to setup a map
     */
    RENDERER.Map = Map;
})(window.Rendxx.Game.Ghost.Renderer);<commit_msg>Working on map<commit_after>window.Rendxx = window.Rendxx || {};
window.Rendxx.Game = window.Rendxx.Game || {};
window.Rendxx.Game.Ghost = window.Rendxx.Game.Ghost || {};
window.Rendxx.Game.Ghost.Renderer = window.Rendxx.Game.Ghost.Renderer || {};

/**
 * Setup map, including light, wall and other stuff
 */
(function (RENDERER) {
    var Data = RENDERER.Data;

    /**
     * Create walls, desks, chairs and doors
     */
    var SetupWall = function (scene) {
        var ground, ceiling, walls;

        /*create ground*/
        var planeGeometry = new THREE.PlaneGeometry(100, 100, 100);
        var planeMaterial = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
        ground = new THREE.Mesh(planeGeometry, planeMaterial);
        ground.rotation.x = -.5 * Math.PI;
        ground.receiveShadow = true;
        scene.add(ground);

        /*create ceiling*/
        var planeGeometry = new THREE.PlaneGeometry(100, 100, 100);
        var planeMaterial = new THREE.MeshBasicMaterial({ color: 0xeeeeee });
        ceiling = new THREE.Mesh(planeGeometry, planeMaterial);
        ceiling.rotation.x = .5 * Math.PI;
        ceiling.position.y = 7.5;
        scene.add(ceiling);

        /*add wall*/
        walls = [];
        var createWall = function (z, x, len, wid, rotate, deep) {
            var cubeGeometry = new THREE.BoxGeometry(len, deep || 8, wid);
            var cubeMaterial = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
            var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

            cube.rotation.y = rotate / 180 * Math.PI;
            cube.position.x = x;
            cube.position.y = 3.5;
            cube.position.z = z
            cube.castShadow = true;
            cube.receiveShadow = true;
            scene.add(cube);

            walls.push(cube);

            var cubeGeometry2 = new THREE.BoxGeometry(len, 1, wid);
            var cubeMaterial2 = new THREE.MeshBasicMaterial({ color: 0x333333 });
            var cube2 = new THREE.Mesh(cubeGeometry2, cubeMaterial2);

            cube2.rotation.y = rotate / 180 * Math.PI;
            cube2.position.x = x;
            cube2.position.y = 8;
            cube2.position.z = z
            scene.add(cube2);

            walls.push(cube2);
        }
        createWall(0, 10, 20, 2, 90);
        createWall(11, 7, 8, 2, 0);
        createWall(4, 4, 12, 2, 90);
        createWall(-11, 3, 16, 2, 0);
        createWall(-3, 0, 10, 2, 0);

        return {
            ground: ground,
            wall: walls
        };
    };

    /**
     * Create items
     */
    var SetupItem = function (scene) {

    };

    /**
     * Create game map
     */
    var SetupMap = function (entity, mapData) {
        var wall = SetupWall(entity.env.scene);
        var light = SetupLight(entity.env.scene);
        var item = SetupItem(entity.env.scene);

        return {
            light: light,
            wall: wall,
            item: item
        };
    };

    var Map = function (entity) {
        // private data ----------------------------
        var that = this;

        // public data -----------------------------
        this.wall = null;
        this.light = null;
        this.item = null;
        this.ground = null;

        // public method ---------------------------
        /**
         * Reset map with given data
         */
        this.reset = function (data) {
            if (data == null) throw new Error('Data missing');
            setupGround(entity.env.scene, data.grid);
            setupWall(entity.env.scene, data.wall, data.stuff);
            setupItem(entity.env.scene, data.item);
        };

        // private method

        var setupLight = function (scene) {
            if (that.light != null) {
                for (var i = 0, l = that.light.length; i < l; i++) scene.remove(that.light[i]);
                that.light = null;
            }

            that.lights = [
                new THREE.AmbientLight(),
                new THREE.SpotLight()
            ];

            var lightTarget = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshPhongMaterial({ color: 0xff3300 }));
            scene.add(lightTarget);

            // Ambient
            that.lights[0].color.setHex(Data.light.ambient.ambColor);
            scene.add(that.lights[0]);

            // Spot
            that.lights[1].castShadow = true;
            that.lights[1].position.set(Data.light.spot.lightX, Data.light.spot.lightY, Data.light.spot.lightZ);
            that.lights[1].intensity = Data.light.spot.intensity;
            that.lights[1].shadowCameraNear = Data.light.spot.shadowCameraNear;
            that.lights[1].shadowCameraFar = Data.light.spot.shadowCameraFar;
            that.lights[1].shadowCameraVisible = Data.light.spot.shadowCameraVisible;
            that.lights[1].shadowBias = Data.light.spot.shadowBias;
            that.lights[1].shadowDarkness = Data.light.spot.shadowDarkness;
            scene.add(that.lights[1]);
        };

        var setupGround = function (scene, grid) {
            if (that.ground != null) {
                for (var i = 0, l = that.ground.length; i < l; i++) scene.remove(that.ground[i]);
                that.ground = null;
            }

            /*create ground*/
            var planeGeometry = new THREE.PlaneGeometry(grid.width * Data.grid.size, grid.height * Data.grid.size);
            var planeMaterial = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
            var ground = new THREE.Mesh(planeGeometry, planeMaterial);
            ground.rotation.x = -.5 * Math.PI;
            ground.receiveShadow = true;
            scene.add(ground);

            /*create ceiling*/
            var planeGeometry = new THREE.PlaneGeometry(grid.width * Data.grid.size, grid.height * Data.grid.size);
            var planeMaterial = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
            var ceiling = new THREE.Mesh(planeGeometry, planeMaterial);
            ceiling.rotation.x = .5 * Math.PI;
            ceiling.position.y = 7.5;
            scene.add(ceiling);

            that.ground = [
                ground,
                ceiling
            ];
        };

        var setupWall = function (scene, wall, stuff) {
            if (that.wall != null) {
                for (var i = 0, l = that.wall.length; i < l; i++) scene.remove(that.wall[i]);
                that.wall = null;
            }
            that.wall = [];
            for (var i = 0, l = wall.length; i < l; i++) {
                that.wall.push(createWall(wall[i]));
            }
        };

        var setupItem = function (item) {
            if (that.item != null) {
                for (var i = 0, l = that.item.length; i < l; i++) scene.remove(that.item[i]);
                that.item = null;
            }
            if (item == null || item.length == 0) return;
            that.item = [];
            for (var i = 0, l = item.length; i < l; i++) {
                that.item.push(createStyff(item[i]));
            }
        };

        // Add stuff
        var createWall = function (dat) {
            var x = (dat.left + dat.right + 1) / 2 * Data.grid.size;
            var y = (dat.top + dat.bottom + 1) / 2 * Data.grid.size;
            var r = dat.rotation - 2;
            var len = dat.len * Data.grid.size;

            var geometry = new THREE.PlaneGeometry(len * Data.grid.size, 2 * Data.grid.size, len, 2);
            var material = new THREE.MeshPhongMaterial({ color: 0xeeeeee });
            var mesh = new THREE.Mesh(geometry, material);

            mesh.rotation.y = r / 2 * Math.PI;
            mesh.position.x = x;
            mesh.position.y = Data.grid.size;
            mesh.position.z = z
            mesh.castShadow = true;
            mesh.receiveShadow = true;
            scene.add(mesh);
            return mesh;
        };

        var createStyff = function (dat) {
            var id = dat.id;
            var x = (dat.left + dat.right + 1) / 2 * Data.grid.size;
            var y = (dat.top + dat.bottom + 1) / 2 * Data.grid.size;
            var r = dat.rotation;
            var w = (dat.right - dat.left + 1) * Data.grid.size;
            var h = (dat.bottom - dat.top + 1) * Data.grid.size;
            var mesh = null;

            switch (dat.id) {
                case 1: // wall top
                    var geometry = new THREE.BoxGeometry(w, 1, 2 * Data.grid.size);
                    var material = new THREE.MeshBasicMaterial({ color: 0x333333 });
                    var mesh = new THREE.Mesh(geometry, material);

                    mesh.rotation.y = r / 180 * Math.PI;
                    mesh.position.x = x;
                    mesh.position.y = Data.grid.size;
                    mesh.position.z = y
                    scene.add(mesh);
                    break;
                case 2: // door
                    var geometry = new THREE.BoxGeometry(w, 1, 2 * Data.grid.size);
                    var material = new THREE.MeshBasicMaterial({ color: 0x333333 });
                    var mesh = new THREE.Mesh(geometry, material);

                    mesh.rotation.y = r / 180 * Math.PI;
                    mesh.position.x = x;
                    mesh.position.y = Data.grid.size;
                    mesh.position.z = y
                    scene.add(mesh);
                    break;
                case 3: // table 1
                    break;
                case 4: // table 2
                    break;
                case 5: // table 3
                    break;
                case 6: // table 4
                    break;
                case 7: // cabinet 1
                    break;
                case 8: // cabinet 2
                    break;
                case 9: // cabinet 3
                    break;
                case 10: // chair
                    break;
            }
            return mesh;
        };

        var _init = function () {
            setupLight(entity.env.scene);
        };

        _init();
    };

    /**
     * Game map
     * @param {game entity} entity - Game entity
     * @param {object} mapData - data used to setup a map
     */
    RENDERER.Map = Map;
})(window.Rendxx.Game.Ghost.Renderer);<|endoftext|>


<commit_before>import React, { Component } from 'react'
import codePush from 'react-native-code-push'
import OneSignal from 'react-native-onesignal'

import { Router, Scene, Actions } from 'react-native-mobx'
import { Provider } from 'mobx-react/native'

import LoginScreen from './views/login_screen'
import HomeScreen from './views/home_screen'
import SettingScreen from './views/setting_screen'
import ChatScreen from './views/chat_screen'

import appStore from './store/AppStore'

class App extends Component {
  componentDidMount() {
    console.log("-------xxxx------ App - componentDidMount ------xxxx-------")
    OneSignal.inFocusDisplaying(0)
    OneSignal.configure({
      onNotificationReceived: function(notification) {
        //console.log('NOTIFICATION RECEIVED: ', notification)
        if (notification.payload.additionalData.new_message && appStore.current_puid != notification.payload.additionalData.puid) {
          console.log("       appStore.new_messages + 1 : " + appStore.current_puid)
          appStore.new_messages = appStore.new_messages + 1
        }
      },
      onNotificationOpened: function(openResult) {
        console.log(openResult);
        console.log('MESSAGE: ', openResult.notification.payload.body)
        console.log('CURRENT PUID:' + appStore.current_pui)
        console.log('ISACTIVE: ', openResult.notification.isAppInFocus)
        console.log('DATA: ', openResult.notification.payload.additionalData)
        if (!openResult.notification.isAppInFocus) {
          if (openResult.notification.payload.additionalData) {
            if (appStore.current_puid != openResult.notification.payload.additionalData.puid) {
              Actions.login({ type: 'replace', postProps:openResult.notification.payload.additionalData })
            }
          }
          else {
            Actions.login({ type: 'replace', postProps:null })
          }
        }
      }
    })
  }
  render() {
    console.disableYellowBox = true
    return (
      <Provider appStore={appStore}>
        <Router>
          <Scene
            key="login"
            component={LoginScreen}
            duration={1}
            hideNavBar
            initial
          />
          <Scene
            key="home"
            component={HomeScreen}
            duration={1}
            hideNavBar
          />
          <Scene
            key="chat"
            component={ChatScreen}
            //direction="vertical"
            hideNavBar={false}
            panHandlers={null}
            duration={0}
          />
          <Scene
            key="setting"
            component={SettingScreen}
            hideNavBar={false}
            title="Edit your profile"
            panHandlers={null}
            duration={0}
          />
        </Router>
      </Provider>
    )
  }
}

//export default App
//export default App = codePush({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE })(App)
export default App = codePush()(App)
<commit_msg>test commit<commit_after>import React, { Component } from 'react'
import codePush from 'react-native-code-push'
import OneSignal from 'react-native-onesignal'

import { Router, Scene, Actions } from 'react-native-mobx'
import { Provider } from 'mobx-react/native'

import LoginScreen from './views/login_screen'
import HomeScreen from './views/home_screen'
import SettingScreen from './views/setting_screen'
import ChatScreen from './views/chat_screen'

import appStore from './store/AppStore'

class App extends Component {
  componentDidMount() {
    console.log("-------x------ App - componentDidMount ------x-------")
    OneSignal.inFocusDisplaying(0)
    OneSignal.configure({
      onNotificationReceived: function(notification) {
        //console.log('NOTIFICATION RECEIVED: ', notification)
        if (notification.payload.additionalData.new_message && appStore.current_puid != notification.payload.additionalData.puid) {
          console.log("       appStore.new_messages + 1 : " + appStore.current_puid)
          appStore.new_messages = appStore.new_messages + 1
        }
      },
      onNotificationOpened: function(openResult) {
        console.log(openResult);
        console.log('MESSAGE: ', openResult.notification.payload.body)
        console.log('CURRENT PUID:' + appStore.current_pui)
        console.log('ISACTIVE: ', openResult.notification.isAppInFocus)
        console.log('DATA: ', openResult.notification.payload.additionalData)
        if (!openResult.notification.isAppInFocus) {
          if (openResult.notification.payload.additionalData) {
            if (appStore.current_puid != openResult.notification.payload.additionalData.puid) {
              Actions.login({ type: 'replace', postProps:openResult.notification.payload.additionalData })
            }
          }
          else {
            Actions.login({ type: 'replace', postProps:null })
          }
        }
      }
    })
  }
  render() {
    console.disableYellowBox = true
    return (
      <Provider appStore={appStore}>
        <Router>
          <Scene
            key="login"
            component={LoginScreen}
            duration={1}
            hideNavBar
            initial
          />
          <Scene
            key="home"
            component={HomeScreen}
            duration={1}
            hideNavBar
          />
          <Scene
            key="chat"
            component={ChatScreen}
            //direction="vertical"
            hideNavBar={false}
            panHandlers={null}
            duration={0}
          />
          <Scene
            key="setting"
            component={SettingScreen}
            hideNavBar={false}
            title="Edit your profile"
            panHandlers={null}
            duration={0}
          />
        </Router>
      </Provider>
    )
  }
}

//export default App
//export default App = codePush({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE })(App)
export default App = codePush()(App)
<|endoftext|>