<commit_before>import actionBuilder from 'action-builder'
import api from 'api'
import Notifications from 'app/notifications'
import GoogleMapsLoader from 'google-maps'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {NEVER, Observable, Subject} from 'rxjs'
import {map, mergeMap, takeUntil} from 'rxjs/operators'
import {connect, select} from 'store'
import Portal from 'widget/portal'
import './map.module.css'

export let sepalMap = null
export let google = null
export let googleMap = null

const contextById = {}
let currentContextId

const initListeners = []
const onInit = listener => {
    if (google)
        listener(google)
    else
        initListeners.push(listener)
}

export const initGoogleMapsApi$ = () => {
    const loadGoogleMapsApiKey$ =
        api.map.loadApiKey$().pipe(
            map(({apiKey}) => apiKey)
        )

    const loadGoogleMapsApi$ = apiKey => Observable.create(observer => {
        GoogleMapsLoader.KEY = apiKey
        GoogleMapsLoader.VERSION = '3.35'
        GoogleMapsLoader.LIBRARIES = ['drawing']
        GoogleMapsLoader.load(g => {
            google = g
            initListeners.forEach(listener => listener(google))
            observer.next(apiKey)
            observer.complete()
        })
    })

    return loadGoogleMapsApiKey$.pipe(
        mergeMap(loadGoogleMapsApi$),
        map(apiKey => actionBuilder('SET_GOOGLE_MAPS_API_INITIALIZED', {apiKey: apiKey})
            .set('map.apiKey', apiKey)
            .build()
        )
    )
}

const createMap = mapElement => {
    googleMap = new google.maps.Map(mapElement, {
        zoom: 3,
        minZoom: 3,
        maxZoom: 17,
        center: new google.maps.LatLng(16.7794913, 9.6771556),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoomControl: false,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false,
        backgroundColor: '#131314',
        gestureHandling: 'greedy'
    })
    googleMap.mapTypes.set('styled_map', new google.maps.StyledMapType(defaultStyle, {name: 'sepalMap'}))
    googleMap.setMapTypeId('styled_map')
    googleMap.addListener('zoom_changed', () =>
        actionBuilder('SET_MAP_ZOOM')
            .set('map.zoom', googleMap.getZoom())
            .dispatch()
    )

    const drawingOptions = {
        fillColor: '#FBFAF2',
        fillOpacity: 0.07,
        strokeColor: '#c5b397',
        strokeOpacity: 1,
        strokeWeight: 2,
        clickable: false,
        editable: false,
        zIndex: 1
    }

    sepalMap = {
        getKey() {
            return GoogleMapsLoader.KEY
        },

        getZoom() {
            return googleMap.getZoom()
        },
        setZoom(zoom) {
            return googleMap.setZoom(zoom)
        },
        zoomIn() {
            googleMap.setZoom(googleMap.getZoom() + 1)
        },
        zoomOut() {
            googleMap.setZoom(googleMap.getZoom() - 1)
        },
        zoomArea() {
            const setZooming = zooming =>
                actionBuilder('SET_MAP_ZOOMING')
                    .set('map.zooming', zooming)
                    .set('map.zoom', googleMap.getZoom())
                    .dispatch()
            setZooming(true)
            const drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
                drawingControl: false,
                rectangleOptions: drawingOptions
            })
            const drawingListener = e => {
                const rectangle = e.overlay
                rectangle.setMap(null)
                drawingManager.setMap(null)
                googleMap.fitBounds(rectangle.bounds)
                setZooming(false)
            }
            google.maps.event.addListener(drawingManager, 'overlaycomplete', drawingListener)
            drawingManager.setMap(googleMap)

        },
        isMaxZoom() {
            return googleMap.getZoom() === googleMap.maxZoom
        },
        isMinZoom() {
            return googleMap.getZoom() === googleMap.minZoom
        },
        fitBounds(bounds) {
            const googleBounds = toGoogleBounds(bounds)
            const boundsChanged = !googleMap.getBounds().equals(googleBounds)
            if (boundsChanged)
                googleMap.fitBounds(googleBounds)
        },
        getBounds() {
            return fromGoogleBounds(googleMap.getBounds())
        },
        onBoundsChanged(listener) {
            // return googleMap.addListener('bounds_changed', listener)
        },
        addListener(mapObject, event, listener) {
            return google.maps.event.addListener(mapObject, event, listener)
        },
        removeListener(listener) {
            if (listener)
                google.maps.event.removeListener(listener)
        },
        getContext(contextId) {
            let context = contextById[contextId]
            if (!context) {
                const layerById = {}
                context = {
                    setLayer({id, layer, destroy$ = NEVER, onInitialized, onError}) {
                        const existingLayer = layerById[id]
                        const unchanged = layer === existingLayer || (existingLayer && existingLayer.equals(layer))
                        if (unchanged)
                            return false
                        this.removeLayer(id)
                        if (layer) {
                            layerById[id] = layer
                            layer.__removed$ = new Subject()
                            layer.initialize$()
                                .pipe(
                                    takeUntil(destroy$),
                                    takeUntil(layer.__removed$)
                                )
                                .subscribe(
                                    () => {
                                        layer.__initialized__ = true
                                        currentContextId === contextId && layer.addToMap(googleMap)
                                        onInitialized && onInitialized(layer)
                                    },
                                    e => {
                                        if (onError)
                                            onError(e)
                                        else
                                            Notifications.caught('map.layer', {}, e)
                                                .dispatch()
                                    }
                                )
                        }
                        return true
                    },
                    hideLayer(id, hidden) {
                        const layer = layerById[id]
                        if (layer)
                            layer.hide(googleMap, hidden)
                    },
                    removeLayer(id) {
                        const layer = layerById[id]
                        if (!layer)
                            return
                        layer.__removed$.next()
                        if (currentContextId === contextId)
                            layer.removeFromMap(googleMap)
                        delete layerById[id]
                    },
                    isLayerInitialized(id) {
                        return !!(this.hasLayer(id) && layerById[id].__initialized__)
                    },
                    hasLayer(id) {
                        return !!layerById[id]
                    },
                    fitLayer(id) {
                        const layer = layerById[id]
                        if (layer && layer.bounds && currentContextId === contextId) {
                            const bounds = layer.bounds
                            sepalMap.fitBounds(bounds)
                        }
                    },
                    addToMap() {
                        Object.keys(layerById).forEach(id => {
                            const layer = layerById[id]
                            if (layer.__initialized__)
                                layer.addToMap(googleMap)
                        })
                    },
                    removeFromMap() {
                        Object.keys(layerById).forEach(id => layerById[id].removeFromMap(googleMap))
                    },
                    drawPolygon(id, callback) {
                        this._drawingMode = {id, callback}
                        this._drawingManager = this._drawingManager || new google.maps.drawing.DrawingManager({
                            drawingMode: google.maps.drawing.OverlayType.POLYGON,
                            drawingControl: false,
                            drawingControlOptions: {
                                position: google.maps.ControlPosition.TOP_CENTER,
                                drawingModes: ['polygon']
                            },
                            circleOptions: drawingOptions,
                            polygonOptions: drawingOptions,
                            rectangleOptions: drawingOptions
                        })
                        const drawingListener = e => {
                            const polygon = e.overlay
                            polygon.setMap(null)
                            const toPolygonPath = polygon => polygon.getPaths().getArray()[0].getArray().map(latLng =>
                                [latLng.lng(), latLng.lat()]
                            )
                            callback(toPolygonPath(polygon))
                        }
                        google.maps.event.addListener(this._drawingManager, 'overlaycomplete', drawingListener)
                        this._drawingManager.setMap(googleMap)
                    },
                    pauseDrawingMode() {
                        if (this._drawingManager) {
                            this._drawingManager.setMap(null)
                            google.maps.event.clearListeners(this._drawingManager, 'overlaycomplete')
                        }
                    },
                    disableDrawingMode() {
                        this.pauseDrawingMode()
                        this._drawingMode = null
                    },
                }
                contextById[contextId] = context
            }
            return context
        },
        setContext(contextId) {
            if (currentContextId === contextId)
                return
            const prevContextId = currentContextId
            if (prevContextId) {
                const context = this.getContext(prevContextId)
                context.pauseDrawingMode()
                context.removeFromMap()
            }

            currentContextId = contextId
            if (contextId) {
                const context = this.getContext(contextId)
                context.addToMap()
                context._drawingMode && context.drawPolygon(context._drawingMode.id, context._drawingMode.callback)
            }

        },
        clearContext(contextId) {
            if (contextId === currentContextId)
                sepalMap.clear()
        },
        removeContext(contextId) {
            if (contextId === currentContextId) {
                sepalMap.clear()
            }
            delete contextById[contextId]
        },
        clear() {
            sepalMap.setContext()
        }
    }
}

export const fromGoogleBounds = googleBounds => {
    const sw = googleBounds.getSouthWest()
    const ne = googleBounds.getNorthEast()
    return [
        [sw.lng(), sw.lat()],
        [ne.lng(), ne.lat()]
    ]
}

const toGoogleBounds = bounds => {
    return new google.maps.LatLngBounds(
        {lng: bounds[0][0], lat: bounds[0][1]},
        {lng: bounds[1][0], lat: bounds[1][1]}
    )
}

export const polygonOptions = fill => ({
    fillColor: '#FBFAF2',
    fillOpacity: fill ? 0.07 : 0.000000000000000000000000000001,
    strokeColor: '#FBFAF2',
    strokeOpacity: 0.5,
    strokeWeight: 1
})

// https://developers.google.com/maps/documentation/javascript/style-reference
const defaultStyle = [
    {stylers: [{visibility: 'simplified'}]},
    {stylers: [{color: '#131314'}]},
    {featureType: 'water', stylers: [{color: '#191919'}, {lightness: 4}]},
    {elementType: 'labels.text.fill', stylers: [{visibility: 'off'}, {lightness: 25}]}
]

const mapStateToProps = () => ({
    apiKey: select('map.apiKey')
})

class Map extends React.Component {
    state = {initialized: false}
    mapElement = React.createRef()

    render() {
        return

    }

    componentDidUpdate() {
        const apiKey = this.props.apiKey
        if (apiKey && !this.state.initialized) { // Create map once there is an API key
            this.setState(prevState => ({...prevState, initialized: true}))
            createMap(this.mapElement.current)
            this.initialized = true
        }
    }
}

Map.propTypes = {
    className: PropTypes.string
}

export default connect(mapStateToProps)(Map)

export class MapLayer extends React.Component {
    state = {
        shown:
            false, projection: null
    }

    constructor(props) {
        super(props)
        this.overlay = new ReactOverlayView(this)
        this.overlay.setMap(googleMap)
    }

    render() {
        const {shown, projection} = this.state
        const {className, children} = this.props
        const mapPanes = this.overlay.getPanes()
        const content = (

                <ProjectionContext.Provider value={projection}>
                    {children}
                </ProjectionContext.Provider>

        )
        return shown && mapPanes
            ? <Portal content={content} container={mapPanes.overlayMouseTarget}/>
            : null
    }

    componentWillUnmount() {
        this.overlay.setMap(null)
    }
}

class WrappedMapObject extends React.Component {
    render() {
        const {lat, lng, width, height, className, children} = this.props
        const shown = googleMap.getBounds().contains({lng, lat})
        if (!shown)
            return null
        return (
            <ProjectionContext.Consumer>
                {projection => {
                    if (!projection)
                        return null
                    const point = projection.fromLatLngToDivPixel(new google.maps.LatLng(lat, lng))
                    const style = {
                        position: 'absolute',
                        top: `calc(${point.y}px - ${height} / 2)`,
                        left: `calc(${point.x}px - ${width} /2)`
                    }
                    return

                        {children}

                }
                }
            </ProjectionContext.Consumer>
        )
    }

    componentWillUnmount() {

    }
}

export const MapObject = connect(state => ({projectionChange: state.map.projectionChange}))(WrappedMapObject)

const ProjectionContext = React.createContext()

let ReactOverlayView
onInit(google =>
    ReactOverlayView = class ReactOverlayView extends google.maps.OverlayView {
        constructor(component) {
            super()
            this.component = component
            this.xyz = null

        }

        onAdd() {
            this.show(true)
        }

        draw() {
            const projection = this.getProjection() // TODO: Zooming changes the projection...
            const point = projection.fromLatLngToDivPixel(new google.maps.LatLng(0, 0))
            const xyz = [point.x, point.y, sepalMap.getZoom()]
            if (!_.isEqual(this.xyz, xyz)) {
                this.xyz = xyz
                this.component.setState(prevState => ({...prevState, projection}))
                actionBuilder('PROJECTION_CHANGED', {xyz})
                    .set('map.projectionChange', xyz)
                    .dispatch()
            }
        }

        onRemove() {
            this.show(false)
            google.maps.event.removeListener(this.projectionChangeListener)
        }

        show(shown) {
            this.component.setState(prevState => ({...prevState, shown: shown}))
        }
    })
<commit_msg>Hid Google Maps Points of Interest.<commit_after>import actionBuilder from 'action-builder'
import api from 'api'
import Notifications from 'app/notifications'
import GoogleMapsLoader from 'google-maps'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {NEVER, Observable, Subject} from 'rxjs'
import {map, mergeMap, takeUntil} from 'rxjs/operators'
import {connect, select} from 'store'
import Portal from 'widget/portal'
import './map.module.css'

export let sepalMap = null
export let google = null
export let googleMap = null

const contextById = {}
let currentContextId

const initListeners = []
const onInit = listener => {
    if (google)
        listener(google)
    else
        initListeners.push(listener)
}

export const initGoogleMapsApi$ = () => {
    const loadGoogleMapsApiKey$ =
        api.map.loadApiKey$().pipe(
            map(({apiKey}) => apiKey)
        )

    const loadGoogleMapsApi$ = apiKey => Observable.create(observer => {
        GoogleMapsLoader.KEY = apiKey
        GoogleMapsLoader.VERSION = '3.35'
        GoogleMapsLoader.LIBRARIES = ['drawing']
        GoogleMapsLoader.load(g => {
            google = g
            initListeners.forEach(listener => listener(google))
            observer.next(apiKey)
            observer.complete()
        })
    })

    return loadGoogleMapsApiKey$.pipe(
        mergeMap(loadGoogleMapsApi$),
        map(apiKey => actionBuilder('SET_GOOGLE_MAPS_API_INITIALIZED', {apiKey: apiKey})
            .set('map.apiKey', apiKey)
            .build()
        )
    )
}

const createMap = mapElement => {
    googleMap = new google.maps.Map(mapElement, {
        zoom: 3,
        minZoom: 3,
        maxZoom: 17,
        center: new google.maps.LatLng(16.7794913, 9.6771556),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoomControl: false,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false,
        backgroundColor: '#131314',
        gestureHandling: 'greedy'
    })
    googleMap.mapTypes.set('styled_map', new google.maps.StyledMapType(defaultStyle, {name: 'sepalMap'}))
    googleMap.setMapTypeId('styled_map')
    googleMap.addListener('zoom_changed', () =>
        actionBuilder('SET_MAP_ZOOM')
            .set('map.zoom', googleMap.getZoom())
            .dispatch()
    )

    const drawingOptions = {
        fillColor: '#FBFAF2',
        fillOpacity: 0.07,
        strokeColor: '#c5b397',
        strokeOpacity: 1,
        strokeWeight: 2,
        clickable: false,
        editable: false,
        zIndex: 1
    }

    sepalMap = {
        getKey() {
            return GoogleMapsLoader.KEY
        },

        getZoom() {
            return googleMap.getZoom()
        },
        setZoom(zoom) {
            return googleMap.setZoom(zoom)
        },
        zoomIn() {
            googleMap.setZoom(googleMap.getZoom() + 1)
        },
        zoomOut() {
            googleMap.setZoom(googleMap.getZoom() - 1)
        },
        zoomArea() {
            const setZooming = zooming =>
                actionBuilder('SET_MAP_ZOOMING')
                    .set('map.zooming', zooming)
                    .set('map.zoom', googleMap.getZoom())
                    .dispatch()
            setZooming(true)
            const drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
                drawingControl: false,
                rectangleOptions: drawingOptions
            })
            const drawingListener = e => {
                const rectangle = e.overlay
                rectangle.setMap(null)
                drawingManager.setMap(null)
                googleMap.fitBounds(rectangle.bounds)
                setZooming(false)
            }
            google.maps.event.addListener(drawingManager, 'overlaycomplete', drawingListener)
            drawingManager.setMap(googleMap)

        },
        isMaxZoom() {
            return googleMap.getZoom() === googleMap.maxZoom
        },
        isMinZoom() {
            return googleMap.getZoom() === googleMap.minZoom
        },
        fitBounds(bounds) {
            const googleBounds = toGoogleBounds(bounds)
            const boundsChanged = !googleMap.getBounds().equals(googleBounds)
            if (boundsChanged)
                googleMap.fitBounds(googleBounds)
        },
        getBounds() {
            return fromGoogleBounds(googleMap.getBounds())
        },
        onBoundsChanged(listener) {
            return googleMap.addListener('bounds_changed', listener)
        },
        addListener(mapObject, event, listener) {
            return google.maps.event.addListener(mapObject, event, listener)
        },
        removeListener(listener) {
            if (listener)
                google.maps.event.removeListener(listener)
        },
        getContext(contextId) {
            let context = contextById[contextId]
            if (!context) {
                const layerById = {}
                context = {
                    setLayer({id, layer, destroy$ = NEVER, onInitialized, onError}) {
                        const existingLayer = layerById[id]
                        const unchanged = layer === existingLayer || (existingLayer && existingLayer.equals(layer))
                        if (unchanged)
                            return false
                        this.removeLayer(id)
                        if (layer) {
                            layerById[id] = layer
                            layer.__removed$ = new Subject()
                            layer.initialize$()
                                .pipe(
                                    takeUntil(destroy$),
                                    takeUntil(layer.__removed$)
                                )
                                .subscribe(
                                    () => {
                                        layer.__initialized__ = true
                                        currentContextId === contextId && layer.addToMap(googleMap)
                                        onInitialized && onInitialized(layer)
                                    },
                                    e => {
                                        if (onError)
                                            onError(e)
                                        else
                                            Notifications.caught('map.layer', {}, e)
                                                .dispatch()
                                    }
                                )
                        }
                        return true
                    },
                    hideLayer(id, hidden) {
                        const layer = layerById[id]
                        if (layer)
                            layer.hide(googleMap, hidden)
                    },
                    removeLayer(id) {
                        const layer = layerById[id]
                        if (!layer)
                            return
                        layer.__removed$.next()
                        if (currentContextId === contextId)
                            layer.removeFromMap(googleMap)
                        delete layerById[id]
                    },
                    isLayerInitialized(id) {
                        return !!(this.hasLayer(id) && layerById[id].__initialized__)
                    },
                    hasLayer(id) {
                        return !!layerById[id]
                    },
                    fitLayer(id) {
                        const layer = layerById[id]
                        if (layer && layer.bounds && currentContextId === contextId) {
                            const bounds = layer.bounds
                            sepalMap.fitBounds(bounds)
                        }
                    },
                    addToMap() {
                        Object.keys(layerById).forEach(id => {
                            const layer = layerById[id]
                            if (layer.__initialized__)
                                layer.addToMap(googleMap)
                        })
                    },
                    removeFromMap() {
                        Object.keys(layerById).forEach(id => layerById[id].removeFromMap(googleMap))
                    },
                    drawPolygon(id, callback) {
                        this._drawingMode = {id, callback}
                        this._drawingManager = this._drawingManager || new google.maps.drawing.DrawingManager({
                            drawingMode: google.maps.drawing.OverlayType.POLYGON,
                            drawingControl: false,
                            drawingControlOptions: {
                                position: google.maps.ControlPosition.TOP_CENTER,
                                drawingModes: ['polygon']
                            },
                            circleOptions: drawingOptions,
                            polygonOptions: drawingOptions,
                            rectangleOptions: drawingOptions
                        })
                        const drawingListener = e => {
                            const polygon = e.overlay
                            polygon.setMap(null)
                            const toPolygonPath = polygon => polygon.getPaths().getArray()[0].getArray().map(latLng =>
                                [latLng.lng(), latLng.lat()]
                            )
                            callback(toPolygonPath(polygon))
                        }
                        google.maps.event.addListener(this._drawingManager, 'overlaycomplete', drawingListener)
                        this._drawingManager.setMap(googleMap)
                    },
                    pauseDrawingMode() {
                        if (this._drawingManager) {
                            this._drawingManager.setMap(null)
                            google.maps.event.clearListeners(this._drawingManager, 'overlaycomplete')
                        }
                    },
                    disableDrawingMode() {
                        this.pauseDrawingMode()
                        this._drawingMode = null
                    },
                }
                contextById[contextId] = context
            }
            return context
        },
        setContext(contextId) {
            if (currentContextId === contextId)
                return
            const prevContextId = currentContextId
            if (prevContextId) {
                const context = this.getContext(prevContextId)
                context.pauseDrawingMode()
                context.removeFromMap()
            }

            currentContextId = contextId
            if (contextId) {
                const context = this.getContext(contextId)
                context.addToMap()
                context._drawingMode && context.drawPolygon(context._drawingMode.id, context._drawingMode.callback)
            }

        },
        clearContext(contextId) {
            if (contextId === currentContextId)
                sepalMap.clear()
        },
        removeContext(contextId) {
            if (contextId === currentContextId) {
                sepalMap.clear()
            }
            delete contextById[contextId]
        },
        clear() {
            sepalMap.setContext()
        }
    }
}

export const fromGoogleBounds = googleBounds => {
    const sw = googleBounds.getSouthWest()
    const ne = googleBounds.getNorthEast()
    return [
        [sw.lng(), sw.lat()],
        [ne.lng(), ne.lat()]
    ]
}

const toGoogleBounds = bounds => {
    return new google.maps.LatLngBounds(
        {lng: bounds[0][0], lat: bounds[0][1]},
        {lng: bounds[1][0], lat: bounds[1][1]}
    )
}

export const polygonOptions = fill => ({
    fillColor: '#FBFAF2',
    fillOpacity: fill ? 0.07 : 0.000000000000000000000000000001,
    strokeColor: '#FBFAF2',
    strokeOpacity: 0.5,
    strokeWeight: 1
})

// https://developers.google.com/maps/documentation/javascript/style-reference
const defaultStyle = [
    {stylers: [{visibility: 'simplified'}]},
    {stylers: [{color: '#131314'}]},
    {featureType: "poi", stylers: [{ visibility: "off" }]},
    {featureType: 'water', stylers: [{color: '#191919'}, {lightness: 4}]},
    {elementType: 'labels.text.fill', stylers: [{visibility: 'off'}, {lightness: 25}]}
]

const mapStateToProps = () => ({
    apiKey: select('map.apiKey')
})

class Map extends React.Component {
    state = {initialized: false}
    mapElement = React.createRef()

    render() {
        return

    }

    componentDidUpdate() {
        const apiKey = this.props.apiKey
        if (apiKey && !this.state.initialized) { // Create map once there is an API key
            this.setState(prevState => ({...prevState, initialized: true}))
            createMap(this.mapElement.current)
            this.initialized = true
        }
    }
}

Map.propTypes = {
    className: PropTypes.string
}

export default connect(mapStateToProps)(Map)

export class MapLayer extends React.Component {
    state = {
        shown:
            false, projection: null
    }

    constructor(props) {
        super(props)
        this.overlay = new ReactOverlayView(this)
        this.overlay.setMap(googleMap)
    }

    render() {
        const {shown, projection} = this.state
        const {className, children} = this.props
        const mapPanes = this.overlay.getPanes()
        const content = (

                <ProjectionContext.Provider value={projection}>
                    {children}
                </ProjectionContext.Provider>

        )
        return shown && mapPanes
            ? <Portal content={content} container={mapPanes.overlayMouseTarget}/>
            : null
    }

    componentWillUnmount() {
        this.overlay.setMap(null)
    }
}

class WrappedMapObject extends React.Component {
    render() {
        const {lat, lng, width, height, className, children} = this.props
        const shown = googleMap.getBounds().contains({lng, lat})
        if (!shown)
            return null
        return (
            <ProjectionContext.Consumer>
                {projection => {
                    if (!projection)
                        return null
                    const point = projection.fromLatLngToDivPixel(new google.maps.LatLng(lat, lng))
                    const style = {
                        position: 'absolute',
                        top: `calc(${point.y}px - ${height} / 2)`,
                        left: `calc(${point.x}px - ${width} /2)`
                    }
                    return

                        {children}

                }
                }
            </ProjectionContext.Consumer>
        )
    }

    componentWillUnmount() {

    }
}

export const MapObject = connect(state => ({projectionChange: state.map.projectionChange}))(WrappedMapObject)

const ProjectionContext = React.createContext()

let ReactOverlayView
onInit(google =>
    ReactOverlayView = class ReactOverlayView extends google.maps.OverlayView {
        constructor(component) {
            super()
            this.component = component
            this.xyz = null

        }

        onAdd() {
            this.show(true)
        }

        draw() {
            const projection = this.getProjection() // TODO: Zooming changes the projection...
            const point = projection.fromLatLngToDivPixel(new google.maps.LatLng(0, 0))
            const xyz = [point.x, point.y, sepalMap.getZoom()]
            if (!_.isEqual(this.xyz, xyz)) {
                this.xyz = xyz
                this.component.setState(prevState => ({...prevState, projection}))
                actionBuilder('PROJECTION_CHANGED', {xyz})
                    .set('map.projectionChange', xyz)
                    .dispatch()
            }
        }

        onRemove() {
            this.show(false)
            google.maps.event.removeListener(this.projectionChangeListener)
        }

        show(shown) {
            this.component.setState(prevState => ({...prevState, shown: shown}))
        }
    })
<|endoftext|>


<commit_before>'use strict';

const MergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');
const Rollup = require('broccoli-rollup');
const babelHelpers = require('./broccoli/babel-helpers');
const bootstrapModule = require('./broccoli/bootstrap-modules');
const concatBundle = require('./broccoli/concat-bundle');
const concat = require('broccoli-concat');
const testIndexHTML = require('./broccoli/test-index-html');
const toES5 = require('./broccoli/to-es5');
const toNamedAMD = require('./broccoli/to-named-amd');
const stripForProd = toES5.stripForProd;
const minify = require('./broccoli/minify');
const rename = require('./broccoli/rename');
const { stripIndent } = require('common-tags');
const {
  routerES,
  jquery,
  internalLoader,
  qunit,
  handlebarsES,
  rsvpES,
  simpleHTMLTokenizerES,
  backburnerES,
  dagES,
  routeRecognizerES,
  glimmerTrees,
  nodeModuleUtils,
  emberVersionES,
  emberLicense,
  nodeTests,
  buildEmberEnvFlagsES,
  getPackagesES,
} = require('./broccoli/packages');
const ENV = process.env.EMBER_ENV || 'development';

module.exports = function() {
  let loader = internalLoader();
  let nodeModule = nodeModuleUtils();
  let license = emberLicense();

  // generate "loose" ES<latest> modules...
  let dependenciesES = new MergeTrees([
    backburnerES(),
    rsvpES(),
    dagES(),
    routerES(),
    routeRecognizerES(),

    ...glimmerDependenciesES(),
  ]);

  let templateCompilerDependenciesES = new MergeTrees([
    simpleHTMLTokenizerES(),
    handlebarsES(),
    ...glimmerTrees(['@glimmer/compiler']),
  ]);

  let packagesES = new MergeTrees([
    // dynamically generated packages
    emberVersionES(),

    // packages/** (after typescript compilation)
    getPackagesES(),
  ]);

  let es = new MergeTrees([packagesES, dependenciesES, templateCompilerDependenciesES], {
    overwrite: true,
  });
  let pkgAndTestESInAMD = toNamedAMD(es);
  let emberEnvFlagsDebug = toNamedAMD(buildEmberEnvFlagsES({ DEBUG: true }));

  let pkgAndTestESBundleDebug = concat(
    new MergeTrees([pkgAndTestESInAMD, loader, nodeModule, emberEnvFlagsDebug]),
    {
      headerFiles: ['loader.js'],
      inputFiles: ['**/*.js'],
      outputFile: 'ember-all.debug.js',
    }
  );

  let babelDebugHelpersES5 = toES5(babelHelpers('debug'), {
    annotation: 'babel helpers debug',
  });

  // Rollup
  let packagesESRollup = new MergeTrees([
    new Funnel(packagesES, {
      exclude: [
        'container/index.js',
        'container/lib/**',
        'ember-environment/index.js',
        'ember-environment/lib/**',
        'ember-browser-environment/index.js',
        'ember-browser-environment/lib/**',
        'ember-glimmer/index.js',
        'ember-glimmer/lib/**',
        'ember-metal/index.js',
        'ember-metal/lib/**',
        'ember-utils/index.js',
        'ember-utils/lib/**',
      ],
    }),
    rollupPackage(packagesES, 'container'),
    rollupPackage(packagesES, 'ember-environment'),
    rollupPackage(packagesES, 'ember-browser-environment'),
    rollupPackage(packagesES, 'ember-glimmer'),
    rollupPackage(packagesES, 'ember-metal'),
    rollupPackage(packagesES, 'ember-utils'),
  ]);

  // ES5
  let packagesES5 = toES5(packagesESRollup);
  let dependenciesES5 = toES5(dependenciesES);
  let templateCompilerDependenciesES5 = toES5(templateCompilerDependenciesES);

  // Bundling
  let emberTestsBundle = new MergeTrees([
    new Funnel(packagesES5, {
      include: ['internal-test-helpers/**', '*/tests/**', 'license.js'],
    }),
    loader,
    license,
    nodeModule,
    babelDebugHelpersES5,
  ]);

  emberTestsBundle = concatBundle(emberTestsBundle, {
    outputFile: 'ember-tests.js',
    hasBootstrap: false,
  });

  let emberDebugBundle = new MergeTrees([
    new Funnel(packagesES5, {
      exclude: ['*/tests/**', 'ember-template-compiler/**', 'internal-test-helpers/**'],
    }),
    dependenciesES5,
    loader,
    license,
    nodeModule,
    bootstrapModule('ember'),
    babelDebugHelpersES5,
  ]);

  emberDebugBundle = concatBundle(emberDebugBundle, {
    outputFile: 'ember.debug.js',
  });

  let emberTestingBundle = new MergeTrees([
    new Funnel(packagesES5, {
      include: [
        '@ember/debug/lib/**',
        '@ember/debug/index.js',
        'ember-testing/index.js',
        'ember-testing/lib/**',
        'license.js',
      ],
    }),
    loader,
    license,
    babelDebugHelpersES5,
    nodeModule,
  ]);

  emberTestingBundle = concatBundle(emberTestingBundle, {
    outputFile: 'ember-testing.js',
    hasBootstrap: false,
    footer: stripIndent`
      var testing = requireModule('ember-testing');
      Ember.Test = testing.Test;
      Ember.Test.Adapter = testing.Adapter;
      Ember.Test.QUnitAdapter = testing.QUnitAdapter;
      Ember.setupForTesting = testing.setupForTesting;
    `,
  });

  function templateCompiler() {
    return new MergeTrees([
      new Funnel(packagesES5, {
        include: [
          '@ember/canary-features/**',
          '@ember/debug/index.js',
          '@ember/debug/lib/**',
          '@ember/error/index.js',
          '@ember/polyfills/index.js',
          '@ember/polyfills/lib/**',
          'ember/version.js',
          'ember-environment.js',
          'ember-browser-environment.js',
          'ember-template-compiler/**',
          'ember-utils.js',
        ],
      }),
      bootstrapModule('ember-template-compiler', 'umd'),
    ]);
  }

  let trees = [];

  if (ENV === 'production') {
    let prodPackagesES5 = stripForProd(toES5(packagesESRollup, { environment: 'production' }));
    let babelProdHelpersES5 = toES5(babelHelpers('prod'), {
      environment: 'production',
    });

    let emberProdBundle = new MergeTrees([
      new Funnel(prodPackagesES5, {
        exclude: [
          '*/tests/**',
          'ember-template-compiler/**',
          'ember-testing/**',
          'internal-test-helpers/**',
        ],
      }),
      stripForProd(dependenciesES5),
      loader,
      license,
      nodeModule,
      bootstrapModule('ember'),
      babelProdHelpersES5,
    ]);

    emberProdBundle = concatBundle(emberProdBundle, {
      outputFile: 'ember.prod.js',
    });
    trees.push(emberProdBundle);

    let emberProdMinRename = rename(emberProdBundle, {
      'ember.prod.js': 'ember.min.js',
    });
    let emberMinBundle = minify(emberProdMinRename);
    trees.push(emberMinBundle);

    let emberTestsBundle = new MergeTrees([
      new Funnel(prodPackagesES5, {
        include: ['internal-test-helpers/**', '*/tests/**', 'license.js'],
      }),
      loader,
      license,
      nodeModule,
      babelProdHelpersES5,
    ]);

    emberTestsBundle = concatBundle(emberTestsBundle, {
      outputFile: 'ember-tests.prod.js',
      hasBootstrap: false,
    });
    trees.push(emberTestsBundle);

    // Note:
    // We have to build custom production template compiler
    // because we strip babel helpers in the prod build
    let emberTemplateCompilerBundle = new MergeTrees([
      stripForProd(templateCompiler()),
      stripForProd(templateCompilerDependenciesES5),
      loader,
      license,
      babelProdHelpersES5,
      nodeModule,
    ]);

    emberTemplateCompilerBundle = concatBundle(emberTemplateCompilerBundle, {
      outputFile: 'ember-template-compiler.js',
    });
    trees.push(emberTemplateCompilerBundle);
  } else {
    let emberTemplateCompilerBundle = new MergeTrees([
      templateCompiler(),
      templateCompilerDependenciesES5,
      loader,
      license,
      babelDebugHelpersES5,
      nodeModule,
    ]);

    emberTemplateCompilerBundle = concatBundle(emberTemplateCompilerBundle, {
      outputFile: 'ember-template-compiler.js',
    });

    trees.push(emberTemplateCompilerBundle);
  }

  return new MergeTrees([
    new Funnel(es, { destDir: 'es' }),
    pkgAndTestESBundleDebug,
    ...trees,
    emberTestsBundle,
    emberDebugBundle,
    emberTestingBundle,
    nodeTests(),

    // test harness
    testIndexHTML(),
    jquery(),
    qunit(),
  ]);
};

function glimmerDependenciesES() {
  let glimmerEntries = ['@glimmer/node', '@glimmer/opcode-compiler', '@glimmer/runtime'];

  if (ENV === 'development') {
    let hasGlimmerDebug = true;
    try {
      require.resolve('@glimmer/debug');
    } catch (e) {
      hasGlimmerDebug = false;
    }
    if (hasGlimmerDebug) {
      glimmerEntries.push('@glimmer/debug', '@glimmer/local-debug-flags');
    }
  }
  return glimmerTrees(glimmerEntries);
}

function rollupPackage(packagesES, name) {
  // this prevents broccoli-rollup from "seeing" changes in
  // its input that are unrelated to what we are building
  // and therefore noop on rebuilds...
  let rollupRestrictedInput = new Funnel(packagesES, {
    srcDir: name,
    destDir: name,
  });

  return new Rollup(rollupRestrictedInput, {
    annotation: `rollup ${name}`,
    rollup: {
      input: `${name}/index.js`,
      external(importee, importer) {
        // importer of null/undefined means entry module
        if (!importer) {
          return false;
        }

        // import is relative initially, then expanded to absolute
        // when resolveId is called. this checks for either...
        if (importee[0] === '.' || importee[0] === '/') {
          return false;
        }

        return true;
      },
      output: {
        file: `${name}.js`,
        format: 'es',
        exports: 'named',
      },
    },
  });
}
<commit_msg>Ensure @ember/deprecated-features ends up in template compiler build.<commit_after>'use strict';

const MergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');
const Rollup = require('broccoli-rollup');
const babelHelpers = require('./broccoli/babel-helpers');
const bootstrapModule = require('./broccoli/bootstrap-modules');
const concatBundle = require('./broccoli/concat-bundle');
const concat = require('broccoli-concat');
const testIndexHTML = require('./broccoli/test-index-html');
const toES5 = require('./broccoli/to-es5');
const toNamedAMD = require('./broccoli/to-named-amd');
const stripForProd = toES5.stripForProd;
const minify = require('./broccoli/minify');
const rename = require('./broccoli/rename');
const { stripIndent } = require('common-tags');
const {
  routerES,
  jquery,
  internalLoader,
  qunit,
  handlebarsES,
  rsvpES,
  simpleHTMLTokenizerES,
  backburnerES,
  dagES,
  routeRecognizerES,
  glimmerTrees,
  nodeModuleUtils,
  emberVersionES,
  emberLicense,
  nodeTests,
  buildEmberEnvFlagsES,
  getPackagesES,
} = require('./broccoli/packages');
const ENV = process.env.EMBER_ENV || 'development';

module.exports = function() {
  let loader = internalLoader();
  let nodeModule = nodeModuleUtils();
  let license = emberLicense();

  // generate "loose" ES<latest> modules...
  let dependenciesES = new MergeTrees([
    backburnerES(),
    rsvpES(),
    dagES(),
    routerES(),
    routeRecognizerES(),

    ...glimmerDependenciesES(),
  ]);

  let templateCompilerDependenciesES = new MergeTrees([
    simpleHTMLTokenizerES(),
    handlebarsES(),
    ...glimmerTrees(['@glimmer/compiler']),
  ]);

  let packagesES = new MergeTrees([
    // dynamically generated packages
    emberVersionES(),

    // packages/** (after typescript compilation)
    getPackagesES(),
  ]);

  let es = new MergeTrees([packagesES, dependenciesES, templateCompilerDependenciesES], {
    overwrite: true,
  });
  let pkgAndTestESInAMD = toNamedAMD(es);
  let emberEnvFlagsDebug = toNamedAMD(buildEmberEnvFlagsES({ DEBUG: true }));

  let pkgAndTestESBundleDebug = concat(
    new MergeTrees([pkgAndTestESInAMD, loader, nodeModule, emberEnvFlagsDebug]),
    {
      headerFiles: ['loader.js'],
      inputFiles: ['**/*.js'],
      outputFile: 'ember-all.debug.js',
    }
  );

  let babelDebugHelpersES5 = toES5(babelHelpers('debug'), {
    annotation: 'babel helpers debug',
  });

  // Rollup
  let packagesESRollup = new MergeTrees([
    new Funnel(packagesES, {
      exclude: [
        'container/index.js',
        'container/lib/**',
        'ember-environment/index.js',
        'ember-environment/lib/**',
        'ember-browser-environment/index.js',
        'ember-browser-environment/lib/**',
        'ember-glimmer/index.js',
        'ember-glimmer/lib/**',
        'ember-metal/index.js',
        'ember-metal/lib/**',
        'ember-utils/index.js',
        'ember-utils/lib/**',
      ],
    }),
    rollupPackage(packagesES, 'container'),
    rollupPackage(packagesES, 'ember-environment'),
    rollupPackage(packagesES, 'ember-browser-environment'),
    rollupPackage(packagesES, 'ember-glimmer'),
    rollupPackage(packagesES, 'ember-metal'),
    rollupPackage(packagesES, 'ember-utils'),
  ]);

  // ES5
  let packagesES5 = toES5(packagesESRollup);
  let dependenciesES5 = toES5(dependenciesES);
  let templateCompilerDependenciesES5 = toES5(templateCompilerDependenciesES);

  // Bundling
  let emberTestsBundle = new MergeTrees([
    new Funnel(packagesES5, {
      include: ['internal-test-helpers/**', '*/tests/**', 'license.js'],
    }),
    loader,
    license,
    nodeModule,
    babelDebugHelpersES5,
  ]);

  emberTestsBundle = concatBundle(emberTestsBundle, {
    outputFile: 'ember-tests.js',
    hasBootstrap: false,
  });

  let emberDebugBundle = new MergeTrees([
    new Funnel(packagesES5, {
      exclude: ['*/tests/**', 'ember-template-compiler/**', 'internal-test-helpers/**'],
    }),
    dependenciesES5,
    loader,
    license,
    nodeModule,
    bootstrapModule('ember'),
    babelDebugHelpersES5,
  ]);

  emberDebugBundle = concatBundle(emberDebugBundle, {
    outputFile: 'ember.debug.js',
  });

  let emberTestingBundle = new MergeTrees([
    new Funnel(packagesES5, {
      include: [
        '@ember/debug/lib/**',
        '@ember/debug/index.js',
        'ember-testing/index.js',
        'ember-testing/lib/**',
        'license.js',
      ],
    }),
    loader,
    license,
    babelDebugHelpersES5,
    nodeModule,
  ]);

  emberTestingBundle = concatBundle(emberTestingBundle, {
    outputFile: 'ember-testing.js',
    hasBootstrap: false,
    footer: stripIndent`
      var testing = requireModule('ember-testing');
      Ember.Test = testing.Test;
      Ember.Test.Adapter = testing.Adapter;
      Ember.Test.QUnitAdapter = testing.QUnitAdapter;
      Ember.setupForTesting = testing.setupForTesting;
    `,
  });

  function templateCompiler() {
    return new MergeTrees([
      new Funnel(packagesES5, {
        include: [
          '@ember/canary-features/**',
          '@ember/debug/index.js',
          '@ember/debug/lib/**',
          '@ember/deprecated-features/**',
          '@ember/error/index.js',
          '@ember/polyfills/index.js',
          '@ember/polyfills/lib/**',
          'ember/version.js',
          'ember-environment.js',
          'ember-browser-environment.js',
          'ember-template-compiler/**',
          'ember-utils.js',
        ],
      }),
      bootstrapModule('ember-template-compiler', 'umd'),
    ]);
  }

  let trees = [];

  if (ENV === 'production') {
    let prodPackagesES5 = stripForProd(toES5(packagesESRollup, { environment: 'production' }));
    let babelProdHelpersES5 = toES5(babelHelpers('prod'), {
      environment: 'production',
    });

    let emberProdBundle = new MergeTrees([
      new Funnel(prodPackagesES5, {
        exclude: [
          '*/tests/**',
          'ember-template-compiler/**',
          'ember-testing/**',
          'internal-test-helpers/**',
        ],
      }),
      stripForProd(dependenciesES5),
      loader,
      license,
      nodeModule,
      bootstrapModule('ember'),
      babelProdHelpersES5,
    ]);

    emberProdBundle = concatBundle(emberProdBundle, {
      outputFile: 'ember.prod.js',
    });
    trees.push(emberProdBundle);

    let emberProdMinRename = rename(emberProdBundle, {
      'ember.prod.js': 'ember.min.js',
    });
    let emberMinBundle = minify(emberProdMinRename);
    trees.push(emberMinBundle);

    let emberTestsBundle = new MergeTrees([
      new Funnel(prodPackagesES5, {
        include: ['internal-test-helpers/**', '*/tests/**', 'license.js'],
      }),
      loader,
      license,
      nodeModule,
      babelProdHelpersES5,
    ]);

    emberTestsBundle = concatBundle(emberTestsBundle, {
      outputFile: 'ember-tests.prod.js',
      hasBootstrap: false,
    });
    trees.push(emberTestsBundle);

    // Note:
    // We have to build custom production template compiler
    // because we strip babel helpers in the prod build
    let emberTemplateCompilerBundle = new MergeTrees([
      stripForProd(templateCompiler()),
      stripForProd(templateCompilerDependenciesES5),
      loader,
      license,
      babelProdHelpersES5,
      nodeModule,
    ]);

    emberTemplateCompilerBundle = concatBundle(emberTemplateCompilerBundle, {
      outputFile: 'ember-template-compiler.js',
    });
    trees.push(emberTemplateCompilerBundle);
  } else {
    let emberTemplateCompilerBundle = new MergeTrees([
      templateCompiler(),
      templateCompilerDependenciesES5,
      loader,
      license,
      babelDebugHelpersES5,
      nodeModule,
    ]);

    emberTemplateCompilerBundle = concatBundle(emberTemplateCompilerBundle, {
      outputFile: 'ember-template-compiler.js',
    });

    trees.push(emberTemplateCompilerBundle);
  }

  return new MergeTrees([
    new Funnel(es, { destDir: 'es' }),
    pkgAndTestESBundleDebug,
    ...trees,
    emberTestsBundle,
    emberDebugBundle,
    emberTestingBundle,
    nodeTests(),

    // test harness
    testIndexHTML(),
    jquery(),
    qunit(),
  ]);
};

function glimmerDependenciesES() {
  let glimmerEntries = ['@glimmer/node', '@glimmer/opcode-compiler', '@glimmer/runtime'];

  if (ENV === 'development') {
    let hasGlimmerDebug = true;
    try {
      require.resolve('@glimmer/debug');
    } catch (e) {
      hasGlimmerDebug = false;
    }
    if (hasGlimmerDebug) {
      glimmerEntries.push('@glimmer/debug', '@glimmer/local-debug-flags');
    }
  }
  return glimmerTrees(glimmerEntries);
}

function rollupPackage(packagesES, name) {
  // this prevents broccoli-rollup from "seeing" changes in
  // its input that are unrelated to what we are building
  // and therefore noop on rebuilds...
  let rollupRestrictedInput = new Funnel(packagesES, {
    srcDir: name,
    destDir: name,
  });

  return new Rollup(rollupRestrictedInput, {
    annotation: `rollup ${name}`,
    rollup: {
      input: `${name}/index.js`,
      external(importee, importer) {
        // importer of null/undefined means entry module
        if (!importer) {
          return false;
        }

        // import is relative initially, then expanded to absolute
        // when resolveId is called. this checks for either...
        if (importee[0] === '.' || importee[0] === '/') {
          return false;
        }

        return true;
      },
      output: {
        file: `${name}.js`,
        format: 'es',
        exports: 'named',
      },
    },
  });
}
<|endoftext|>


<commit_before>const express = require('express')

const app = express()

app.get('/', async (req, res) => {
  try {
    const thing = await Promise.resolve({ one: 'two' }) // async/await!
    return res.json({...thing, hello: 'world'}) // object-rest-spread!
  } catch (e) {
    return res.json({ error: e.message })
  }
})
const port = process.env.PORT || 3000

app.listen(port, (err) => {
  if (err) {
    console.error(err)
  }

  if (__DEV__) { // webpack flags!
    console.log('> in development')
  }

  console.log(`> listening on port ${port}`)
})
<commit_msg>Revert the unnecessary change<commit_after>import express from 'express'

const app = express()

app.get('/', async (req, res) => {
  try {
    const thing = await Promise.resolve({ one: 'two' }) // async/await!
    return res.json({...thing, hello: 'world'}) // object-rest-spread!
  } catch (e) {
    return res.json({ error: e.message })
  }
})
const port = process.env.PORT || 3000

app.listen(port, (err) => {
  if (err) {
    console.error(err)
  }

  if (__DEV__) { // webpack flags!
    console.log('> in development')
  }

  console.log(`> listening on port ${port}`)
})
<|endoftext|>


<commit_before>var actionRegistry = new Array();

function updateState() {
	$.ajax({
		type : "GET",
		url : '/api/issue/' + issue + ':updateprocstate',
		data : {
			state : JSON.stringify(Proclib.netstate)
		},
		dataType : "json",
		contentType : "application/json"
	});
}

function confirmAction(msg) {
	return function(transition) {
		return function() {
			var btn = null;
			document.getElementById('procform').appendChild(
					p(btn = button(msg, '')));

			var action = function() {
				transition.finalize();
				updateState();
				contribute("Confirmed process task: " + msg);
			};

			var idx = actionRegistry.push(action) - 1;

			btn.setAttribute('onClick', 'javascript:actionRegistry[' + idx
					+ ']()');
		}
	}
}

function enterAction(msg) {
	return enterAction(msg, function(v) {
		return v;
	});
}

function enterAction(msg, interpreter) {
	return function(transition) {
		return function() {
			var ig = null;
			document.getElementById('procform').appendChild(
					p(ig = inputGroupButton(msg, '')));

			var action = function() {
				var value = interpreter(ig.childNodes[0].value);

				if (value != null) {
					transition.finalize();
					Proclib.netstate.data[transition.name] = value;
					updateState();
					contribute("User entered required information (" + msg
							+ "): " + value);
				}
			};

			var idx = actionRegistry.push(action) - 1;

			ig.childNodes[1].childNodes[0].setAttribute('onClick',
					'javascript:actionRegistry[' + idx + ']()');
		}
	}
}
<commit_msg>fixed value interpreter<commit_after>var actionRegistry = new Array();

function updateState() {
	$.ajax({
		type : "GET",
		url : '/api/issue/' + issue + ':updateprocstate',
		data : {
			state : JSON.stringify(Proclib.netstate)
		},
		dataType : "json",
		contentType : "application/json"
	});
}

function confirmAction(msg) {
	return function(transition) {
		return function() {
			var btn = null;
			document.getElementById('procform').appendChild(
					p(btn = button(msg, '')));

			var action = function() {
				transition.finalize();
				updateState();
				contribute("Confirmed process task: " + msg);
			};

			var idx = actionRegistry.push(action) - 1;

			btn.setAttribute('onClick', 'javascript:actionRegistry[' + idx
					+ ']()');
		}
	}
}

function enterAction(msg, interpreter) {
	return function(transition) {
		return function() {
			var ig = null;
			document.getElementById('procform').appendChild(
					p(ig = inputGroupButton(msg, '')));

			var action = function() {
				if(typeof interpreter == 'undefined'){
					interpreter = function(v){return v};
				}

				var value = interpreter(ig.childNodes[0].value);

				if (value != null) {
					transition.finalize();
					Proclib.netstate.data[transition.name] = value;
					updateState();
					contribute("User entered required information (" + msg
							+ "): " + value);
				}
			};

			var idx = actionRegistry.push(action) - 1;

			ig.childNodes[1].childNodes[0].setAttribute('onClick',
					'javascript:actionRegistry[' + idx + ']()');
		}
	}
}
<|endoftext|>


<commit_before>define("ace/snippets/scala",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText =undefined;
exports.scope = "scala";

});
<commit_msg>Update public/libs/bower_components/ace-builds/src/snippets/scala.js<commit_after><|endoftext|>


<commit_before>/*!
 * Open Orchestra jQuery initialize
 *
 * Refacto of jQuery initialize - v1.0.0 - 12/14/2016
 * https://github.com/adampietrasiak/jquery.initialize
 *
 * Copyright (c) 2015-2016 Adam Pietrasiak
 * Released under the MIT license
 * https://github.com/timpler/jquery.initialize/blob/master/LICENSE
 */
;(function ($) {
    var prefix = 'jquery_initialize';
    var count = 0;
    var msobservers = {
        'callbacks': {},

        'initialize': function (id, selector, callback) {
            // Wrap the callback so that we can ensure that it is only called once per element.
            var seen = [];
            callbackOnce = function () {
                if (seen.indexOf(this) == -1) {
                    seen.push(this);
                    $(this).each(callback);
                }
            };

            // See if the selector matches any elements already on the page.
            $('#' + id + ' ' + selector).each(callbackOnce);

            // Then, add it to the list of selector observers.
            this.addCallback(id, selector, callbackOnce);
        },

        'addCallback': function (id, selector, callback) {
            if (typeof this.callbacks[id] == 'undefined') {
                this.callbacks[id] = [];
            }
            if (typeof this.callbacks[id][selector] == 'undefined') {
                this.callbacks[id][selector] = [];
            }
            this.callbacks[id][selector].push(callback);
        },

        'removeId': function(id) {
            if (this.callbacks.hasOwnProperty(id)) {
                delete(this.callbacks[id]);
            }
        }
    };

    var observer = new MutationObserver(function (mutations) {
        // Stop watching selectors when they disappear from the DOM
        mutations.forEach(function(mutation) {
            if (mutation.type == 'childList' && mutation.removedNodes.length > 0) {
                for (id in msobservers.callbacks) {
                    for (var index = 0; index < mutation.removedNodes.length; index++) {
                        if ($(mutation.removedNodes[index]).attr('id') == id) {
                            msobservers.removeId(id);
                        }
                    }
                }
            }
        });

        // The MutationObserver watches for when new elements are added to the DOM.
        for (id in msobservers.callbacks) {
            for (selector in msobservers.callbacks[id]) {
                for (var i = 0; i < msobservers.callbacks[id][selector].length; i++) {
                    $('#' + id + ' ' + selector).each(msobservers.callbacks[id][selector][i]);
                }
            }
        }
    });

    // Observe the entire document.
    observer.observe(document.documentElement, {childList: true, subtree: true, attributes: true});

    // Handle .initialize() calls.
    $.fn.initialize = function (selector, callback) {
        let id = $(this).attr('id');
        if (typeof id == 'undefined') {
            while ($("#" + id).length > 0) {
                id = prefix + '_' + count;
                count++;
            }
        }
        $(this).attr('id', id);
        msobservers.initialize(id, selector, callback);
    };

    // Handle manual .destroy() calls.
    $.fn.destroy = function (id) {
        msobservers.removeId(id);
    };
})(jQuery);
<commit_msg>fix tiny (#2339)<commit_after>/*!
 * Open Orchestra jQuery initialize
 *
 * Refacto of jQuery initialize - v1.0.0 - 12/14/2016
 * https://github.com/adampietrasiak/jquery.initialize
 *
 * Copyright (c) 2015-2016 Adam Pietrasiak
 * Released under the MIT license
 * https://github.com/timpler/jquery.initialize/blob/master/LICENSE
 */
;(function ($) {
    var prefix = 'jquery_initialize';
    var count = 0;
    var msobservers = {
        'callbacks': {},

        'initialize': function (id, selector, callback) {
            // Wrap the callback so that we can ensure that it is only called once per element.
            var seen = [];
            callbackOnce = function () {
                if (seen.indexOf(this) == -1) {
                    seen.push(this);
                    $(this).each(callback);
                }
            };

            // See if the selector matches any elements already on the page.
            $('#' + id + ' ' + selector).each(callbackOnce);

            // Then, add it to the list of selector observers.
            this.addCallback(id, selector, callbackOnce);
        },

        'addCallback': function (id, selector, callback) {
            if (typeof this.callbacks[id] == 'undefined') {
                this.callbacks[id] = [];
            }
            if (typeof this.callbacks[id][selector] == 'undefined') {
                this.callbacks[id][selector] = [];
            }
            this.callbacks[id][selector].push(callback);
        },

        'removeId': function(id) {
            if (this.callbacks.hasOwnProperty(id)) {
                delete(this.callbacks[id]);
            }
        }
    };

    var observer = new MutationObserver(function (mutations) {
        // Stop watching selectors when they disappear from the DOM
        mutations.forEach(function(mutation) {
            if (mutation.type == 'childList' && mutation.removedNodes.length > 0) {
                for (id in msobservers.callbacks) {
                    for (var index = 0; index < mutation.removedNodes.length; index++) {
                        if ($(mutation.removedNodes[index]).attr('id') == id) {
                            msobservers.removeId(id);
                        }
                    }
                }
            }
        });

        // The MutationObserver watches for when new elements are added to the DOM.
        for (id in msobservers.callbacks) {
            for (selector in msobservers.callbacks[id]) {
                for (var i = 0; i < msobservers.callbacks[id][selector].length; i++) {
                    $('#' + id + ' ' + selector).each(msobservers.callbacks[id][selector][i]);
                }
            }
        }
    });

    // Observe the entire document.
    observer.observe(document.documentElement, {childList: true, subtree: true, attributes: true});

    // Handle .initialize() calls.
    $.fn.initialize = function (selector, callback) {
        let id = $(this).attr('id');
        if (typeof id == 'undefined') {
            do {
                id = prefix + '_' + count;
                count++;
            } while ($("#" + id).length > 0);
        }
        $(this).attr('id', id);
        msobservers.initialize(id, selector, callback);
    };

    // Handle manual .destroy() calls.
    $.fn.destroy = function (id) {
        msobservers.removeId(id);
    };
})(jQuery);
<|endoftext|>


<commit_before>const { env } = require('process');
const { join } = require('path');
const { mkdirpSync } = require('fs-extra');
const { cwd } = require('process');
const { JUnitXmlReporter } = require('jasmine-reporters');
const { SpecReporter } = require('jasmine-spec-reporter');
const webpack = require('webpack');
const express = require('express');
const webpackConfig = require('../configs/webpack.e2e.config');

const e2eHostPort = 4000;
const e2eHostAddress = env.E2E_HOST_ADDRESS || 'localhost';
const outputDir = join(cwd(), 'target', 'e2e');
const junitDir = join(outputDir, 'junit');
const screenshotOutputDir = join(outputDir, 'screenshots');

// Configuration for running Protractor on Jenkins
exports.config = {
  directConnect: true,
  chromeDriver: require('chromedriver').path,
  baseUrl: `http://${e2eHostAddress}:${e2eHostPort}/#/`,

  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: ["--headless", "--disable-gpu", "--no-sandbox", "--window-size=800x600", "--log-level=1"],
      w3c: false
    },
    shardTestFiles: true,
    maxInstances: 5
  },

  maxSessions: 3,

  framework: 'jasmine',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 30000,
    showTiming: true,
    print: function () { }
  },

  beforeLaunch: onBeforeLaunch,
  afterLaunch: onAfterLaunch,

  // Spec patterns are relative to this config file
  specs: ['./tests/**/**/*.e2e-spec.ts'],

  plugins: [
    {
      package: 'protractor-image-comparison',
      options: {
        baselineFolder: join(cwd(), './e2e/screenshots'),
        formatImageName: `{tag}-{logName}-{width}x{height}`,
        screenshotPath: screenshotOutputDir,
        savePerInstance: true,
        autoSaveBaseline: false,
        ignoreAntialiasing: true
      },
    },
    {
      package: 'protractor-console-plugin',
      failOnError: true,
      logWarnings: false,
      exclude: [
        new RegExp(/favicon.ico/, 'g'),
        'Invalid Host/Origin header',
        '[WDS] Disconnected!',
        /sockjs-node\/info/
      ]
    }
  ],

  useAllAngular2AppRoots: true,

  onPrepare: function () {

    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });

    mkdirpSync(junitDir);

    // returning the promise makes protractor wait for the reporter config before executing tests
    return browser.getProcessedConfig().then(function (config) {
      browser.driver.getCapabilities().then(function (caps) {
        browser.browserName = caps.get('browserName');
      });

      const browserName = config.capabilities.browserName;

      // Add reporter which will output results in XML format
      jasmine.getEnv().addReporter(
        new JUnitXmlReporter({
          consolidateAll: false,
          savePath: junitDir,
          filePrefix: `${browserName}.`
        })
      );

      jasmine.getEnv().addReporter(
        new SpecReporter({
          spec: {
            displayStacktrace: true
          },
          summary: {
            displayErrorMessages: true,
            displayFailed: true,
            displayDuration: false
          }
        })
      );
    });
  },
};

let webServer;

async function onBeforeLaunch() {
    await startWebServer();
}

function onAfterLaunch() {
    if (webServer) {
        webServer.close();
        webServer = null;
        console.log('Stopped webserver.')
    }
}

async function startWebServer() {
    return new Promise((resolve, reject) => {
        console.log('Starting webpack compilation...');
        webpack(webpackConfig, (err, stats) => {
            if (err || stats.hasErrors()) {
                reject(err || 'Webpack compilation failed.');
            }

            webServer = express().use(express.static(join(__dirname, 'dist'))).listen(e2eHostPort);
            console.log(`Webserver is listening on port ${e2eHostPort}.`);

            resolve();
        });
    });
}
<commit_msg>e2e: add --disable-dev-shm-usage flag (#1451)<commit_after>const { env } = require('process');
const { join } = require('path');
const { mkdirpSync } = require('fs-extra');
const { cwd } = require('process');
const { JUnitXmlReporter } = require('jasmine-reporters');
const { SpecReporter } = require('jasmine-spec-reporter');
const webpack = require('webpack');
const express = require('express');
const webpackConfig = require('../configs/webpack.e2e.config');

const e2eHostPort = 4000;
const e2eHostAddress = env.E2E_HOST_ADDRESS || 'localhost';
const outputDir = join(cwd(), 'target', 'e2e');
const junitDir = join(outputDir, 'junit');
const screenshotOutputDir = join(outputDir, 'screenshots');

// Configuration for running Protractor on Jenkins
exports.config = {
  directConnect: true,
  chromeDriver: require('chromedriver').path,
  baseUrl: `http://${e2eHostAddress}:${e2eHostPort}/#/`,

  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: [
        "--headless",
        "--disable-gpu",
        "--no-sandbox",
        "--disable-dev-shm-usage",
        "--window-size=800x600",
        "--log-level=1"
      ],
      w3c: false
    },
    shardTestFiles: true,
    maxInstances: 5
  },

  maxSessions: 3,

  framework: 'jasmine',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 30000,
    showTiming: true,
    print: function () { }
  },

  beforeLaunch: onBeforeLaunch,
  afterLaunch: onAfterLaunch,

  // Spec patterns are relative to this config file
  specs: ['./tests/**/**/*.e2e-spec.ts'],

  plugins: [
    {
      package: 'protractor-image-comparison',
      options: {
        baselineFolder: join(cwd(), './e2e/screenshots'),
        formatImageName: `{tag}-{logName}-{width}x{height}`,
        screenshotPath: screenshotOutputDir,
        savePerInstance: true,
        autoSaveBaseline: false,
        ignoreAntialiasing: true
      },
    },
    {
      package: 'protractor-console-plugin',
      failOnError: true,
      logWarnings: false,
      exclude: [
        new RegExp(/favicon.ico/, 'g'),
        'Invalid Host/Origin header',
        '[WDS] Disconnected!',
        /sockjs-node\/info/
      ]
    }
  ],

  useAllAngular2AppRoots: true,

  onPrepare: function () {

    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });

    mkdirpSync(junitDir);

    // returning the promise makes protractor wait for the reporter config before executing tests
    return browser.getProcessedConfig().then(function (config) {
      browser.driver.getCapabilities().then(function (caps) {
        browser.browserName = caps.get('browserName');
      });

      const browserName = config.capabilities.browserName;

      // Add reporter which will output results in XML format
      jasmine.getEnv().addReporter(
        new JUnitXmlReporter({
          consolidateAll: false,
          savePath: junitDir,
          filePrefix: `${browserName}.`
        })
      );

      jasmine.getEnv().addReporter(
        new SpecReporter({
          spec: {
            displayStacktrace: true
          },
          summary: {
            displayErrorMessages: true,
            displayFailed: true,
            displayDuration: false
          }
        })
      );
    });
  },
};

let webServer;

async function onBeforeLaunch() {
    await startWebServer();
}

function onAfterLaunch() {
    if (webServer) {
        webServer.close();
        webServer = null;
        console.log('Stopped webserver.')
    }
}

async function startWebServer() {
    return new Promise((resolve, reject) => {
        console.log('Starting webpack compilation...');
        webpack(webpackConfig, (err, stats) => {
            if (err || stats.hasErrors()) {
                reject(err || 'Webpack compilation failed.');
            }

            webServer = express().use(express.static(join(__dirname, 'dist'))).listen(e2eHostPort);
            console.log(`Webserver is listening on port ${e2eHostPort}.`);

            resolve();
        });
    });
}
<|endoftext|>


<commit_before>/* globals module, require */
'use strict';
const MergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');
const Rollup = require('broccoli-rollup');
const stew = require('broccoli-stew');
const path = require('path');
const typescript = require('broccoli-typescript-compiler');
const ts = typescript(stew.find('lib'), {
  tsconfig: {
    compilerOptions: {
      module: 'es6',
      target: 'es6',
      removeComments: true,
      moduleResolution: 'node'
    }
  }
});

module.exports = function () {
  return new MergeTrees([
    new Rollup(ts, {
      rollup: {
        entry: 'lib/index.js',
        targets: [{
          dest: 'backburner.js',
          format: 'es',
          exports: 'named'
        }]
      }
    }),
    new Rollup(ts, {
      rollup: {
        entry: 'lib/index.js',
        targets: [{
          dest: 'tests/backburner.js',
          format: 'amd',
          moduleId: 'backburner',
          exports: 'named'
        }]
      }
    }),
    new Rollup(new Funnel('tests', { include: ['**/*.js'], destDir: 'tests' }), {
      rollup: {
        entry: 'tests/index.js',
        external: ['backburner'],
        targets: [{
          dest: 'tests/tests.js',
          format: 'amd',
          moduleId: 'backburner-tests'
        }]
      },
      annotation: 'tests/tests.js'
    }),
    new Funnel(path.dirname(require.resolve('qunitjs')), {
      annotation: 'tests/qunit.{js,css}',
      files: ['qunit.css', 'qunit.js'],
      destDir: 'tests'
    }),
    new Funnel(path.dirname(require.resolve('loader.js')), {
      annotation: 'tests/loader.js',
      files: ['loader.js'],
      destDir: 'tests'
    }),
    new Funnel('tests', {
      files: ['index.html'],
      destDir: 'tests'
    })
  ], {
    annotation: 'dist'
  });
};<commit_msg>including es6 dir for ember config<commit_after>/* globals module, require */
'use strict';
const MergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');
const Rollup = require('broccoli-rollup');
const stew = require('broccoli-stew');
const path = require('path');
const typescript = require('broccoli-typescript-compiler');
const ts = typescript(stew.find('lib'), {
  tsconfig: {
    compilerOptions: {
      module: 'es6',
      target: 'es6',
      removeComments: true,
      moduleResolution: 'node'
    }
  }
});

module.exports = function () {
  return new MergeTrees([
    new Rollup(ts, {
      rollup: {
        entry: 'lib/index.js',
        targets: [{
          dest: 'backburner.js',
          format: 'es',
          exports: 'named'
        },{
          dest: 'es6/backburner.js',
          format: 'es',
          exports: 'named'
        }]
      }
    }),
    new Rollup(ts, {
      rollup: {
        entry: 'lib/index.js',
        targets: [{
          dest: 'tests/backburner.js',
          format: 'amd',
          moduleId: 'backburner',
          exports: 'named'
        }]
      }
    }),
    new Rollup(new Funnel('tests', { include: ['**/*.js'], destDir: 'tests' }), {
      rollup: {
        entry: 'tests/index.js',
        external: ['backburner'],
        targets: [{
          dest: 'tests/tests.js',
          format: 'amd',
          moduleId: 'backburner-tests'
        }]
      },
      annotation: 'tests/tests.js'
    }),
    new Funnel(path.dirname(require.resolve('qunitjs')), {
      annotation: 'tests/qunit.{js,css}',
      files: ['qunit.css', 'qunit.js'],
      destDir: 'tests'
    }),
    new Funnel(path.dirname(require.resolve('loader.js')), {
      annotation: 'tests/loader.js',
      files: ['loader.js'],
      destDir: 'tests'
    }),
    new Funnel('tests', {
      files: ['index.html'],
      destDir: 'tests'
    })
  ], {
    annotation: 'dist'
  });
};<|endoftext|>


<commit_before>var moment = require('moment');

var ImageList = mongoose.model("ImageList");

module.exports = function(app) {

  app.get('/api/photos',
    passport.authenticate('token-auth'),
    // need to do a token check, not a passport auth check
    // passport.authenticate('instagram', { failureRedirect: '/' }),
    function(req, res){
      var user = req.user
      var force_refresh = req.param("force_refresh", "false") == "true";
      ImageList.instagramPhotosForUser(user, {force_refresh: force_refresh}, function(err, imageList){
        var limit = Number(req.param("limit", "30"));
        var include_raw = req.param("include_raw", "no");

        var outputObj = imageList.toObject();

        if (limit < outputObj.images.length) {
          outputObj.images.splice(limit,outputObj.images.length-limit);
        }
        if (include_raw == "no" || include_raw == "false" || include_raw === false) {
          for (var i = outputObj.images.length - 1; i >= 0; i--){
            outputObj.images[i].raw_json = undefined;
          }
        }
        res.send({meta: 200, data: outputObj}, 200);
      });
    }
  );

}<commit_msg>null check<commit_after>var moment = require('moment');

var ImageList = mongoose.model("ImageList");

module.exports = function(app) {

  app.get('/api/photos',
    passport.authenticate('token-auth'),
    // need to do a token check, not a passport auth check
    // passport.authenticate('instagram', { failureRedirect: '/' }),
    function(req, res){
      var user = req.user
      var force_refresh = req.param("force_refresh", "false") == "true";
      ImageList.instagramPhotosForUser(user, {force_refresh: force_refresh}, function(err, imageList){
        var outputObj = null;
        if (imageList != null) {
          var limit = Number(req.param("limit", "30"));
          var include_raw = req.param("include_raw", "no");

          outputObj = imageList.toObject();

          if (limit < outputObj.images.length) {
            outputObj.images.splice(limit,outputObj.images.length-limit);
          }
          if (include_raw == "no" || include_raw == "false" || include_raw === false) {
            for (var i = outputObj.images.length - 1; i >= 0; i--){
              outputObj.images[i].raw_json = undefined;
            }
          }
        }
        res.send({meta: 200, data: outputObj}, 200);
      });
    }
  );

}<|endoftext|>


<commit_before>define("ace/theme/terminal",["require","exports","module","ace/lib/dom"], function(require, exports, module) {

exports.isDark = true;
exports.cssClass = "ace-terminal-theme";
exports.cssText = ".ace-terminal-theme .ace_gutter {\
background: #1a0005;\
color: steelblue\
}\
.ace-terminal-theme .ace_print-margin {\
width: 1px;\
background: #1a1a1a\
}\
.ace-terminal-theme {\
background-color: black;\
color: #DEDEDE\
}\
.ace-terminal-theme .ace_cursor {\
color: #9F9F9F\
}\
.ace-terminal-theme .ace_marker-layer .ace_selection {\
background: #424242\
}\
.ace-terminal-theme.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px black;\
}\
.ace-terminal-theme .ace_marker-layer .ace_step {\
background: rgb(0, 0, 0)\
}\
.ace-terminal-theme .ace_marker-layer .ace_bracket {\
background: #090;\
}\
.ace-terminal-theme .ace_marker-layer .ace_bracket-start {\
background: #090;\
}\
.ace-terminal-theme .ace_marker-layer .ace_bracket-unmatched {\
margin: -1px 0 0 -1px;\
border: 1px solid #900\
}\
.ace-terminal-theme .ace_marker-layer .ace_active-line {\
background: #2A2A2A\
}\
.ace-terminal-theme .ace_gutter-active-line {\
background-color: #2A112A\
}\
.ace-terminal-theme .ace_marker-layer .ace_selected-word {\
border: 1px solid #424242\
}\
.ace-terminal-theme .ace_invisible {\
color: #343434\
}\
.ace-terminal-theme .ace_keyword,\
.ace-terminal-theme .ace_meta,\
.ace-terminal-theme .ace_storage,\
.ace-terminal-theme .ace_storage.ace_type,\
.ace-terminal-theme .ace_support.ace_type {\
color: tomato\
}\
.ace-terminal-theme .ace_keyword.ace_operator {\
color: deeppink\
}\
.ace-terminal-theme .ace_constant.ace_character,\
.ace-terminal-theme .ace_constant.ace_language,\
.ace-terminal-theme .ace_constant.ace_numeric,\
.ace-terminal-theme .ace_keyword.ace_other.ace_unit,\
.ace-terminal-theme .ace_support.ace_constant,\
.ace-terminal-theme .ace_variable.ace_parameter {\
color: #E78C45\
}\
.ace-terminal-theme .ace_constant.ace_other {\
color: gold\
}\
.ace-terminal-theme .ace_invalid {\
color: yellow;\
background-color: red\
}\
.ace-terminal-theme .ace_invalid.ace_deprecated {\
color: #CED2CF;\
background-color: #B798BF\
}\
.ace-terminal-theme .ace_fold {\
background-color: #7AA6DA;\
border-color: #DEDEDE\
}\
.ace-terminal-theme .ace_entity.ace_name.ace_function,\
.ace-terminal-theme .ace_support.ace_function,\
.ace-terminal-theme .ace_variable {\
color: #7AA6DA\
}\
.ace-terminal-theme .ace_support.ace_class,\
.ace-terminal-theme .ace_support.ace_type {\
color: #E7C547\
}\
.ace-terminal-theme .ace_heading,\
.ace-terminal-theme .ace_string {\
color: #B9CA4A\
}\
.ace-terminal-theme .ace_entity.ace_name.ace_tag,\
.ace-terminal-theme .ace_entity.ace_other.ace_attribute-name,\
.ace-terminal-theme .ace_meta.ace_tag,\
.ace-terminal-theme .ace_string.ace_regexp,\
.ace-terminal-theme .ace_variable {\
color: #D54E53\
}\
.ace-terminal-theme .ace_comment {\
color: orangered\
}\
.ace-terminal-theme .ace_indent-guide {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYLBWV/8PAAK4AYnhiq+xAAAAAElFTkSuQmCC) right repeat-y;\
}\
";

var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
<commit_msg>Update public/libs/bower_components/ace-builds/src/theme-terminal.js<commit_after><|endoftext|>


<commit_before>/**
 * blink.js
 */

/* api */
import { getType, isString } from './common.js';
import { createFile, mkdir, readFile, rm } from './file-util.js';
import path from 'path';
import process from 'process';

/* constants */
const CHAR = 'utf8';
const DIR_CWD = process.cwd();
const DIR_OUT = path.resolve(DIR_CWD, 'bundle');
const DIR_SRC = path.resolve(DIR_CWD, 'src');
const INDENT = 2;

/**
 * create blink specific manifest.json
 *
 * @param {boolean} info - console info
 * @returns {string} - file path
 */
export const createManifest = async info => {
  const srcContent = await readFile(path.join(DIR_SRC, 'manifest.json'), {
    encoding: CHAR,
    flag: 'r'
  });
  const manifest = JSON.parse(srcContent);
  const replaceItems = {
    background: {
      page: 'html/background.html',
      persistent: false
    },
    icons: {
      16: 'img/icon-outline-16.png',
      32: 'img/icon-outline-32.png',
      64: 'img/icon-color.png',
      128: 'img/icon-color-128.png'
    },
    // TODO: refactoring when switching to MV3
    permissions: [
      'activeTab',
      'clipboardWrite',
      'contextMenus',
      'storage',
      'tabs'
    ]
  };
  const items = Object.entries(replaceItems);
  for (const [key, value] of items) {
    manifest[key] = value;
  }
  const content = `${JSON.stringify(manifest, null, INDENT)}\n`;
  const filePath =
    await createFile(path.join(DIR_OUT, 'manifest.json'), content);
  if (filePath && info) {
    console.info(`Created: ${filePath}`);
  }
  return filePath;
};

/**
 * create polyfilled *.js file
 *
 * @param {string} file - file path
 * @param {boolean} info - console info
 * @returns {string} - file path
 */
export const createPolyfilledJsFile = async (file, info) => {
  if (!isString(file)) {
    throw new TypeError(`Expected String but got ${getType(file)}.`);
  }
  const srcContent = await readFile(path.join(DIR_SRC, 'mjs', file), {
    encoding: CHAR,
    flag: 'r'
  });
  const arr = srcContent.split('\n');
  const i = arr.findIndex(str => /^import\s/.test(str));
  if (i > -1) {
    const includeStr = "import '../lib/mozilla/browser-polyfill.min.js';";
    arr.splice(i, 0, includeStr);
  }
  const content = arr.join('\n');
  const dir = await mkdir(path.join(DIR_OUT, 'mjs'));
  const filePath = await createFile(path.join(dir, file), content);
  if (filePath && info) {
    console.info(`Created: ${filePath}`);
  }
  return filePath;
};

/**
 * create blink specific *.js files
 *
 * @param {boolean} info - console info
 * @returns {Promise.<Array>} - results of each handler
 */
export const createJsFiles = async info => {
  const files = [
    'background.js',
    'options.js',
    'popup.js'
  ];
  const func = [];
  for (const file of files) {
    func.push(createPolyfilledJsFile(file, info));
  }
  return Promise.all(func);
};

/**
 * create blink specific files
 *
 * @param {object} cmdOpts - command options
 * @returns {Promise.<Array>} - results of each handler
 */
export const createBlinkFiles = async (cmdOpts = {}) => {
  const { clean, info } = cmdOpts;
  if (clean) {
    await rm(DIR_OUT);
    await mkdir(DIR_OUT);
  }
  const func = [
    createManifest(info),
    createJsFiles(info)
  ];
  return Promise.all(func);
};
<commit_msg>Temporary remove persistent (#124)<commit_after>/**
 * blink.js
 */

/* api */
import { getType, isString } from './common.js';
import { createFile, mkdir, readFile, rm } from './file-util.js';
import path from 'path';
import process from 'process';

/* constants */
const CHAR = 'utf8';
const DIR_CWD = process.cwd();
const DIR_OUT = path.resolve(DIR_CWD, 'bundle');
const DIR_SRC = path.resolve(DIR_CWD, 'src');
const INDENT = 2;

/**
 * create blink specific manifest.json
 *
 * @param {boolean} info - console info
 * @returns {string} - file path
 */
export const createManifest = async info => {
  const srcContent = await readFile(path.join(DIR_SRC, 'manifest.json'), {
    encoding: CHAR,
    flag: 'r'
  });
  const manifest = JSON.parse(srcContent);
  const replaceItems = {
    icons: {
      16: 'img/icon-outline-16.png',
      32: 'img/icon-outline-32.png',
      64: 'img/icon-color.png',
      128: 'img/icon-color-128.png'
    },
    // TODO: refactoring when switching to MV3
    permissions: [
      'activeTab',
      'clipboardWrite',
      'contextMenus',
      'storage',
      'tabs'
    ]
  };
  const items = Object.entries(replaceItems);
  for (const [key, value] of items) {
    manifest[key] = value;
  }
  const content = `${JSON.stringify(manifest, null, INDENT)}\n`;
  const filePath =
    await createFile(path.join(DIR_OUT, 'manifest.json'), content);
  if (filePath && info) {
    console.info(`Created: ${filePath}`);
  }
  return filePath;
};

/**
 * create polyfilled *.js file
 *
 * @param {string} file - file path
 * @param {boolean} info - console info
 * @returns {string} - file path
 */
export const createPolyfilledJsFile = async (file, info) => {
  if (!isString(file)) {
    throw new TypeError(`Expected String but got ${getType(file)}.`);
  }
  const srcContent = await readFile(path.join(DIR_SRC, 'mjs', file), {
    encoding: CHAR,
    flag: 'r'
  });
  const arr = srcContent.split('\n');
  const i = arr.findIndex(str => /^import\s/.test(str));
  if (i > -1) {
    const includeStr = "import '../lib/mozilla/browser-polyfill.min.js';";
    arr.splice(i, 0, includeStr);
  }
  const content = arr.join('\n');
  const dir = await mkdir(path.join(DIR_OUT, 'mjs'));
  const filePath = await createFile(path.join(dir, file), content);
  if (filePath && info) {
    console.info(`Created: ${filePath}`);
  }
  return filePath;
};

/**
 * create blink specific *.js files
 *
 * @param {boolean} info - console info
 * @returns {Promise.<Array>} - results of each handler
 */
export const createJsFiles = async info => {
  const files = [
    'background.js',
    'options.js',
    'popup.js'
  ];
  const func = [];
  for (const file of files) {
    func.push(createPolyfilledJsFile(file, info));
  }
  return Promise.all(func);
};

/**
 * create blink specific files
 *
 * @param {object} cmdOpts - command options
 * @returns {Promise.<Array>} - results of each handler
 */
export const createBlinkFiles = async (cmdOpts = {}) => {
  const { clean, info } = cmdOpts;
  if (clean) {
    await rm(DIR_OUT);
    await mkdir(DIR_OUT);
  }
  const func = [
    createManifest(info),
    createJsFiles(info)
  ];
  return Promise.all(func);
};
<|endoftext|>


<commit_before>module.exports = {

	/**
	* Get All todos
	*/
	generate : function(req, res) {
		res.json({status : 200, token : req.token, user : req.user});
	}

};<commit_msg>change function name (generate -> login)<commit_after>module.exports = {

	/**
	* Send the token and the user authenticate
	*/
	login : function(req, res) {
		res.json({status : 200, token : req.token, user : req.user});
	}

};<|endoftext|>


<commit_before>define(function() {

	// Export
	return function(Prism) {

		Prism.languages.clike = {
			'comment': {
				pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|(^|[^:])\/\/.*?(\r?\n|$))/g,
				lookbehind: true
			},
			'string': /("|')(\\?.)*?\1/g,
			'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|catch|finally|null|break|continue)\b/g,
			'boolean': /\b(true|false)\b/g,
			'number': /\b-?(0x)?\d*\.?[\da-f]+\b/g,
			'operator': /[-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\//g,
			'ignore': /&(lt|gt|amp);/gi,
			'punctuation': /[{}[\];(),.:]/g
		};

	};

});
<commit_msg>Add more operators to the ‘Prism.languages.clike’ object<commit_after>define(function() {

	// Export
	return function(Prism) {

		Prism.languages.clike = {
			'comment': {
				pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|(^|[^:])\/\/.*?(\r?\n|$))/g,
				lookbehind: true
			},
			'string': /("|')(\\?.)*?\1/g,
			'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|catch|finally|null|break|continue)\b/g,
			'boolean': /\b(true|false)\b/g,
			'number': /\b-?(0x)?\d*\.?[\da-f]+\b/g,
			'operator': /[-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,
			'ignore': /&(lt|gt|amp);/gi,
			'punctuation': /[{}[\];(),.:]/g
		};

	};

});
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {renderRoutes} from 'react-router-config';
import {Redirect} from 'react-router-dom';

import * as actions from 'reduxes/actions';
import Event from 'vendors/Event';
import Config from 'examples/config';

import 'assets/font-awesome/css/fontawesome-all.min.css';
import 'sass/global.scss';
import 'sass/containers/Root.scss';

class Root extends Component {

    constructor(props) {

        super(props);

        this.resizeHandle = ::this.resizeHandle;

    }

    resizeHandle() {
        window.innerWidth >= Config.desktopMinWidth ?
            (!this.props.isDesktop && this.props.switchToDesktop())
            :
            (this.props.isDesktop && this.props.switchToMobile());
    }

    componentDidMount() {

        Event.addEvent(window, 'resize', this.resizeHandle);

        document.getElementById('loading').style.display = 'none';

    }

    componentWillUnmount() {
        Event.removeEvent(window, 'resize', this.resizeHandle);
    }

    render() {

        const {route, location} = this.props;

        return (

                {renderRoutes(route.routes)}

                {
                    location.pathname === '/' ?
                        <Redirect from="/" to="/landing"/>
                        :
                        null
                }

        );
    }

}

Root.propTypes = {

    isDesktop: PropTypes.bool,

    switchToDesktop: PropTypes.func,
    switchToMobile: PropTypes.func

};

export default connect(state => ({
    isDesktop: state.device.isDesktop
}), dispatch => bindActionCreators({
    switchToDesktop: actions.switchToDesktop,
    switchToMobile: actions.switchToMobile
}, dispatch))(Root);<commit_msg>update Root<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {renderRoutes} from 'react-router-config';
import {Redirect} from 'react-router-dom';

import * as actions from 'reduxes/actions';
import Event from 'vendors/Event';
import Config from 'examples/config';

import 'assets/font-awesome/css/fontawesome-all.min.css';
import 'sass/global.scss';
import 'sass/containers/Root.scss';

class Root extends Component {

    constructor(props) {
        super(props);
    }

    resizeHandle = () => {
        window.innerWidth >= Config.desktopMinWidth ?
            (!this.props.isDesktop && this.props.switchToDesktop())
            :
            (this.props.isDesktop && this.props.switchToMobile());
    };

    componentDidMount() {

        Event.addEvent(window, 'resize', this.resizeHandle);

        document.getElementById('loading').style.display = 'none';

    }

    componentWillUnmount() {
        Event.removeEvent(window, 'resize', this.resizeHandle);
    }

    render() {

        const {route, location} = this.props;

        return (

                {renderRoutes(route.routes)}

                {
                    location.pathname === '/' ?
                        <Redirect from="/" to="/landing"/>
                        :
                        null
                }

        );
    }

}

Root.propTypes = {

    isDesktop: PropTypes.bool,

    switchToDesktop: PropTypes.func,
    switchToMobile: PropTypes.func

};

export default connect(state => ({
    isDesktop: state.device.isDesktop
}), dispatch => bindActionCreators({
    switchToDesktop: actions.switchToDesktop,
    switchToMobile: actions.switchToMobile
}, dispatch))(Root);<|endoftext|>