<commit_before>var path    = require('path')
var debug   = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var request = require('request')
var async   = require('async')
var op      = require('object-path')
var fs      = require('fs')

var entu    = require('../helpers/entu')

debug('Maintenance Started at ' + Date().toString())

fs.readdir('./pagecache', function(error, files) {
    if (error) {
        debug('0', error)
    }
    files.forEach(function(file) {
        if (path.extname(file) === '.json') {
            debug('Read from cache: ' + path.basename(file, '.json'))
            SDC.set(path.basename(file, '.json'), require(path.join('../pagecache', file)))
        }
    })
})

SDC.set('calendar.min_date', new Date().toLocaleDateString())
SDC.set('calendar.max_date', new Date().toLocaleDateString())
// fs.createWriteStream('./pagecache/calendar.json').write(JSON.stringify(SDC.get('calendar'), null, '  '))

var cacheRoot = function cacheRoot() {
    debug('Caching root')
    SDC.set(['__', 'season'], (new Date().getFullYear()-2000+(Math.sign(new Date().getMonth()-5.5)-1)/2) + '/' + (new Date().getFullYear()-2000+(Math.sign(new Date().getMonth()-5.5)-1)/2+1))
    entu.get_entity(id=APP_ENTU_ROOT, null, null, CB=function(error, institution) {
        if (error) {
            debug('Cant cache institution entity', error)
        }
        SDC.set(['__', 'main_color'], institution.get(['properties', 'main-color', 'value']))
        SDC.set(['__', 'secondary_color'], institution.get(['properties', 'secondary-color', 'value']))
        fs.createWriteStream('./pagecache/root.json').write(JSON.stringify(SDC.get('__'), null, '  '))
        debug('Root cached')
        setTimeout(cacheRoot, APP_ROOT_REFRESH_MS)
    })
}
cacheRoot()

var cacheEntities = function cacheEntities(name, definition, parent, reset_markers, delay_ms, marker_f, manipulator_f) {
    debug('Caching ' + name)
    var callback = function(error, entities) {
        if (error) {
            if (error.code == 'ENOTFOUND') {
                debug('Retry in 5 sec', error)
                setTimeout(function() {cacheEntities(name, definition, parent, reset_markers, delay_ms, marker_f, manipulator_f)}, 5*1000)
                return
            }
        }
        var marked_entities_1 = {}
        var marked_entities_2 = {}
        async.each(entities, function(one_entity, callback) {
            var markers = []
            manipulator_f(one_entity, function(error, processed_entity) {
                if (error) {
                    debug('4', error)
                }
                one_entity = processed_entity
                markers = marker_f(one_entity)
                if (markers.length == 0) {
                    markers.push('_')
                }
                markers.forEach(function(marker) {
                    if (!marked_entities_1[marker]) {
                        marked_entities_1[marker] = []
                    }
                    marked_entities_1[marker].push(one_entity.get())
                    // op.push(marked_entities, marker, one_entity.get())
                })
                callback()
            })
        }, function (error) {
            if (error) {
                debug('2', error)
            }
            Object.keys(marked_entities_1).sort().forEach(function(marker) {
                // debug('pushing to ' + marker, JSON.stringify(marked_entities_1[marker], null, '  '))
                op.set(marked_entities_2, marker, marked_entities_1[marker])
            })

            for (marker in marked_entities_2) {
                debug('Writing ' + name + '.' + marker + ' to cache.')
                var ws = fs.createWriteStream('./pagecache/' + name + '_' + marker + '.json')
                ws.write(JSON.stringify(marked_entities_2[marker], null, '  '))
                SDC.set(name + '_' + marker, marked_entities_2[marker])
            }
            if (delay_ms) {
                setTimeout(function() {cacheEntities(name, definition, parent, reset_markers, delay_ms, marker_f, manipulator_f)}, delay_ms)
            }
            debug('Caching ' + name + ' done. Next check in ' + delay_ms/1000 + ' sec.')
        })
    }
    if (parent) {
        entu.get_childs(parent=parent, definition=definition, auth_id=null, auth_token=null, callback=callback)
    } else {
        entu.get_entities(definition=definition, limit=null, auth_id=null, auth_token=null, callback=callback)
    }
}

var event_manipulator = function manipulator_f(entity_in, callback) {
    var entity_out = op({})
    entity_out.set('id', entity_in.get('id'))
    entity_out.set('category', entity_in.get('properties.category'))
    entity_out.set('name', entity_in.get('properties.name.value'))
    entity_out.set('description', entity_in.get('properties.description.md'))
    entity_out.set('photo', entity_in.get('properties.photo.0'))
    entity_out.set('photos', entity_in.get('properties.photo'))
    entity_out.set('video', entity_in.get('properties.video.value'))
    entity_out.set('location', entity_in.get('properties.location.value'))
    entity_out.set('price', entity_in.get('properties.price.value'))
    entity_out.set('ticket-api', entity_in.get('properties.ticket-api.value'))
    entity_out.set('technical-information', entity_in.get('properties.technical-information.md'))

    entity_in.get('properties.start-time', []).forEach(function(starttime) {
        entity_out.push('start-times', starttime.value)
    })

    if (entity_in.get('properties.performance.reference')) {
        // debug('fetch performance')
        entu.get_entity(id=entity_in.get('properties.performance.reference'), null, null, performanceCB=function(error, performance) {
            if (error) {
                debug('Event manipulator performance reference', error)
            }
            entity_out.set('performance', performance_manipulator(performance).get())
            // debug(entity_out.get('performance'))
            callback(null, entity_out)
        })
    } else {
        // debug('no performance')
        callback(null, entity_out)
    }
}

var performance_manipulator = function manipulator_f(entity_in) {
    var entity_out = op({})
    entity_out.set('id', entity_in.get('id'))
    entity_out.set('category', entity_in.get('properties.category'))
    entity_out.set('name', entity_in.get('properties.name.value'))
    entity_out.set('description', entity_in.get('properties.description.md'))
    entity_out.set('photo', entity_in.get('properties.photo.0'))
    entity_out.set('photos', entity_in.get('properties.photo'))
    entity_out.set('video', entity_in.get('properties.video.value'))
    entity_out.set('technical-information', entity_in.get('properties.technical-information.md'))
    return entity_out
}

// Split events into past and future and group by time
cacheEntities(
    name = 'program',
    definition = 'event',
    parent = 597,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 15 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Fetch events from under SAAL Biennaal and group by time
cacheEntities(
    name = 'SAAL_Biennaal',
    definition = 'event',
    parent = 1932,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 30 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times.sort()) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Fetch events from under NU Performance and group by time
cacheEntities(
    name = 'NU_Performance',
    definition = 'event',
    parent = 1933,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 30 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times.sort()) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Fetch events from under Tours and group by time
cacheEntities(
    name = 'tours',
    definition = 'event',
    parent = 1929,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 30 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times.sort()) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Fetch events from under Residency and group by time
cacheEntities(
    name = 'Residency',
    definition = 'event',
    parent = 1931,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 30 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times.sort()) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Split news into old and new and group by time
cacheEntities(
    name = 'news',
    definition = 'news',
    parent = 597,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 10 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var news_time = entity.get(['properties','time','value'])
        var markers = []
        var ms = Date.parse(news_time)
        var news_date = news_time.slice(0,10)
        // var news_date = (new Date(ms)).toJSON().slice(0,10)
        if (ms < Date.now()) {
            markers.push('past.' + news_date)
        } else if (ms >= Date.now()) {
            markers.push('upcoming.' + news_date)
        }
        return markers
    },
    manipulator_f = function manipulator_f(entity) {
        return entity
    }
)

// Example markers on person
cacheEntities(
    name = 'users',
    definition = 'person',
    parent = null,
    reset_markers = ['entusiastid', 'others'],
    delay_ms = 60 * 60 * 1000,
    marker_f = function marker_f(entity) {
        if (entity.get('name') == 'Mihkel-Mikelis Putrinš')
            return ['entusiastid.mihkel']
        else if (entity.get('name') == 'Argo Roots')
            return ['entusiastid.argo']
        else
            return ['others']
    },
    manipulator_f = function manipulator_f(entity_in) {
        var entity_out = op({})
        entity_out.set('id', entity_in.get('id'))
        entity_out.set('name', entity_in.get('displayname'))
        entity_out.set('entity', entity_in.get())
        return entity_out
    }
)<commit_msg>new season starts in September instead of July<commit_after>var path    = require('path')
var debug   = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var request = require('request')
var async   = require('async')
var op      = require('object-path')
var fs      = require('fs')

var entu    = require('../helpers/entu')

debug('Maintenance Started at ' + Date().toString())

fs.readdir('./pagecache', function(error, files) {
    if (error) {
        debug('0', error)
    }
    files.forEach(function(file) {
        if (path.extname(file) === '.json') {
            debug('Read from cache: ' + path.basename(file, '.json'))
            SDC.set(path.basename(file, '.json'), require(path.join('../pagecache', file)))
        }
    })
})

SDC.set('calendar.min_date', new Date().toLocaleDateString())
SDC.set('calendar.max_date', new Date().toLocaleDateString())

var cacheRoot = function cacheRoot() {
    debug('Caching root')
    SDC.set(['__', 'season'], (new Date().getFullYear()-2000+(Math.sign(new Date().getMonth()-7.5)-1)/2) + '/' + (new Date().getFullYear()-2000+(Math.sign(new Date().getMonth()-5.5)-1)/2+1))
    entu.get_entity(id=APP_ENTU_ROOT, null, null, CB=function(error, institution) {
        if (error) {
            debug('Cant cache institution entity', error)
        }
        SDC.set(['__', 'main_color'], institution.get(['properties', 'main-color', 'value']))
        SDC.set(['__', 'secondary_color'], institution.get(['properties', 'secondary-color', 'value']))
        fs.createWriteStream('./pagecache/root.json').write(JSON.stringify(SDC.get('__'), null, '  '))
        debug('Root cached')
        setTimeout(cacheRoot, APP_ROOT_REFRESH_MS)
    })
}
cacheRoot()

var cacheEntities = function cacheEntities(name, definition, parent, reset_markers, delay_ms, marker_f, manipulator_f) {
    debug('Caching ' + name)
    var callback = function(error, entities) {
        if (error) {
            if (error.code == 'ENOTFOUND') {
                debug('Retry in 5 sec', error)
                setTimeout(function() {cacheEntities(name, definition, parent, reset_markers, delay_ms, marker_f, manipulator_f)}, 5*1000)
                return
            }
        }
        var marked_entities_1 = {}
        var marked_entities_2 = {}
        async.each(entities, function(one_entity, callback) {
            var markers = []
            manipulator_f(one_entity, function(error, processed_entity) {
                if (error) {
                    debug('4', error)
                }
                one_entity = processed_entity
                markers = marker_f(one_entity)
                if (markers.length == 0) {
                    markers.push('_')
                }
                markers.forEach(function(marker) {
                    if (!marked_entities_1[marker]) {
                        marked_entities_1[marker] = []
                    }
                    marked_entities_1[marker].push(one_entity.get())
                    // op.push(marked_entities, marker, one_entity.get())
                })
                callback()
            })
        }, function (error) {
            if (error) {
                debug('2', error)
            }
            Object.keys(marked_entities_1).sort().forEach(function(marker) {
                // debug('pushing to ' + marker, JSON.stringify(marked_entities_1[marker], null, '  '))
                op.set(marked_entities_2, marker, marked_entities_1[marker])
            })

            for (marker in marked_entities_2) {
                debug('Writing ' + name + '.' + marker + ' to cache.')
                var ws = fs.createWriteStream('./pagecache/' + name + '_' + marker + '.json')
                ws.write(JSON.stringify(marked_entities_2[marker], null, '  '))
                SDC.set(name + '_' + marker, marked_entities_2[marker])
            }
            if (delay_ms) {
                setTimeout(function() {cacheEntities(name, definition, parent, reset_markers, delay_ms, marker_f, manipulator_f)}, delay_ms)
            }
            debug('Caching ' + name + ' done. Next check in ' + delay_ms/1000 + ' sec.')
        })
    }
    if (parent) {
        entu.get_childs(parent=parent, definition=definition, auth_id=null, auth_token=null, callback=callback)
    } else {
        entu.get_entities(definition=definition, limit=null, auth_id=null, auth_token=null, callback=callback)
    }
}

var event_manipulator = function manipulator_f(entity_in, callback) {
    var entity_out = op({})
    entity_out.set('id', entity_in.get('id'))
    entity_out.set('category', entity_in.get('properties.category'))
    entity_out.set('name', entity_in.get('properties.name.value'))
    entity_out.set('description', entity_in.get('properties.description.md'))
    entity_out.set('photo', entity_in.get('properties.photo.0'))
    entity_out.set('photos', entity_in.get('properties.photo'))
    entity_out.set('video', entity_in.get('properties.video.value'))
    entity_out.set('location', entity_in.get('properties.location.value'))
    entity_out.set('price', entity_in.get('properties.price.value'))
    entity_out.set('ticket-api', entity_in.get('properties.ticket-api.value'))
    entity_out.set('technical-information', entity_in.get('properties.technical-information.md'))

    entity_in.get('properties.start-time', []).forEach(function(starttime) {
        entity_out.push('start-times', starttime.value)
    })

    if (entity_in.get('properties.performance.reference')) {
        // debug('fetch performance')
        entu.get_entity(id=entity_in.get('properties.performance.reference'), null, null, performanceCB=function(error, performance) {
            if (error) {
                debug('Event manipulator performance reference', error)
            }
            entity_out.set('performance', performance_manipulator(performance).get())
            // debug(entity_out.get('performance'))
            callback(null, entity_out)
        })
    } else {
        // debug('no performance')
        callback(null, entity_out)
    }
}

var performance_manipulator = function manipulator_f(entity_in) {
    var entity_out = op({})
    entity_out.set('id', entity_in.get('id'))
    entity_out.set('category', entity_in.get('properties.category'))
    entity_out.set('name', entity_in.get('properties.name.value'))
    entity_out.set('description', entity_in.get('properties.description.md'))
    entity_out.set('photo', entity_in.get('properties.photo.0'))
    entity_out.set('photos', entity_in.get('properties.photo'))
    entity_out.set('video', entity_in.get('properties.video.value'))
    entity_out.set('technical-information', entity_in.get('properties.technical-information.md'))
    return entity_out
}

// Split events into past and future and group by time
cacheEntities(
    name = 'program',
    definition = 'event',
    parent = 597,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 15 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Fetch events from under SAAL Biennaal and group by time
cacheEntities(
    name = 'SAAL_Biennaal',
    definition = 'event',
    parent = 1932,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 30 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times.sort()) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Fetch events from under NU Performance and group by time
cacheEntities(
    name = 'NU_Performance',
    definition = 'event',
    parent = 1933,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 30 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times.sort()) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Fetch events from under Tours and group by time
cacheEntities(
    name = 'tours',
    definition = 'event',
    parent = 1929,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 30 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times.sort()) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Fetch events from under Residency and group by time
cacheEntities(
    name = 'Residency',
    definition = 'event',
    parent = 1931,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 30 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var event_times = entity.get('start-times')
        var markers = []
        if (!event_times || !Array.isArray(event_times) || event_times.length == 0) {
            markers.push('no_date')
        } else {
            for (i in event_times.sort()) {
                var ms = Date.parse(event_times[i])
                var event_date = (event_times[i]).slice(0,10)
                var event_time = (event_times[i]).slice(11,16)
                // var event_date = (new Date(ms)).toJSON().slice(0,10)
                if (ms < Date.now()) {
                    markers.push('past.' + event_date + '.' + event_time)
                } else if (ms >= Date.now()) {
                    markers.push('upcoming.' + event_date + '.' + event_time)
                }
            }
        }
        return markers
    },
    manipulator_f = event_manipulator
)

// Split news into old and new and group by time
cacheEntities(
    name = 'news',
    definition = 'news',
    parent = 597,
    reset_markers = ['no_date', 'past', 'upcoming'],
    delay_ms = 10 * 60 * 1000,
    marker_f = function marker_f(entity) {
        var news_time = entity.get(['properties','time','value'])
        var markers = []
        var ms = Date.parse(news_time)
        var news_date = news_time.slice(0,10)
        // var news_date = (new Date(ms)).toJSON().slice(0,10)
        if (ms < Date.now()) {
            markers.push('past.' + news_date)
        } else if (ms >= Date.now()) {
            markers.push('upcoming.' + news_date)
        }
        return markers
    },
    manipulator_f = function manipulator_f(entity) {
        return entity
    }
)

// Example markers on person
cacheEntities(
    name = 'users',
    definition = 'person',
    parent = null,
    reset_markers = ['entusiastid', 'others'],
    delay_ms = 60 * 60 * 1000,
    marker_f = function marker_f(entity) {
        if (entity.get('name') == 'Mihkel-Mikelis Putrinš')
            return ['entusiastid.mihkel']
        else if (entity.get('name') == 'Argo Roots')
            return ['entusiastid.argo']
        else
            return ['others']
    },
    manipulator_f = function manipulator_f(entity_in) {
        var entity_out = op({})
        entity_out.set('id', entity_in.get('id'))
        entity_out.set('name', entity_in.get('displayname'))
        entity_out.set('entity', entity_in.get())
        return entity_out
    }
)<|endoftext|>


<commit_before>export const smartTruncate = (text, limit = 200) => {
  if (!text) { return; }

  let size = 0;
  let textArray = [];
  let tokens = text.split(' ');

  for (let i = 0; i < tokens.length; i++) {
    let token = tokens[i];

    size += token.length + 1;

    if (size > limit) { break; }

    textArray.push(token);
  }

  return textArray.join(' ') + (text.length > limit ? '…' : '');
}

export default {
  smartTruncate
};
<commit_msg>Add more basic version of string truncate helper<commit_after>export let truncate = (text, limit = 200) => {
  if (!text) { return; }

  let truncated = text.substr(0, limit);

  return truncated + (text.length > limit ? '…' : '');
}

export default {
  truncate
};
<|endoftext|>


<commit_before>module('users.timfelgentreff.reactive.reactive').requires('users.timfelgentreff.babelsberg.constraintinterpreter', 'cop.Layers').toRun(function() {

	JSLoader.loadJs(module('users.timfelgentreff.csp.underscore-min').uri());

	/***************************************************************
	 * Abstract Reactive Solver
	 ***************************************************************/

	Object.subclass("ReactiveSolver", {
	    isConstraintObject: function() { return true; },
	    constraintVariableFor: function(value, ivarname, bbbCVar) {
	    	return new ReactiveSolver.Variable(this, value, ivarname, bbbCVar);
	    },
	    weight: 10
	});

	Object.subclass("ReactiveSolver.Variable", {
	    isConstraintObject: function() { return true; },
		initialize: function(solver, value, ivarname, bbbCVar) {
			this.solver = solver;
			this.__val__ = value;
		},
	    suggestValue: function(value) {
			var prev = this.__val__;
	    	this.__val__ = value;
			try {
				this.solver.solve();
			} catch(e) {
				// revert value in case of a violated assertion
				//if(e instanceof ContinuousAssertError) {
				//	this.__val__ = prev;
				//}
				throw e;
			}

			// re-constrain variables
			if (typeof(value) == 'object' || typeof(value) == 'function') {
			    // only recalculate to reconstraint complex objects
                var bbbConstraint = this.solver.constraint.bbbConstraint;
                var enabled = bbbConstraint._enabled;
                bbbConstraint.initialize(bbbConstraint.predicate, bbbConstraint.solver);
                bbbConstraint.addPrimitiveConstraint(this.solver.constraint);
                if(enabled) bbbConstraint.enable();
			}

	    	return this.__val__;
	    },
	    value: function() {
	    	return this.__val__;
	    },
	    setReadonly: function(bool) {
	    	this.readonly = bool;
	    },
	    isReadonly: function() {
	        return this.readonly;
	    },
	    cnEquals: function() {
	        return new ReactiveSolver.PrimitiveConstraint(this, arguments);
	    }
	});

	Object.subclass("ReactiveSolver.PrimitiveConstraint", {
	    isConstraintObject: function() { return true; },
	    initialize: function(variable, args) {
			this.enabled = false;
	    	this.solver = variable.solver;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	Object.subclass("ReactiveSolver.Constraint", {
	    isConstraintObject: function() { return true; },
	    initialize: function(solver, bbbConstraint, func) {
			this.enabled = false;
	    	this.solver = solver;
	    	this.solver.constraint = this;
			this.bbbConstraint = bbbConstraint;

	    	this.predicate = func;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	/***************************************************************
	 * Continuous asserts
	 ***************************************************************/

	// TODO: integration with other solvers

	Error.subclass("ContinuousAssertError", {
		initialize: function ContinuousAssertError(msg) {
			if (Error.captureStackTrace) {
				Error.captureStackTrace(this, ContinuousAssertError);
			} else {
				this.stack = (new Error).stack || '';
			}
			this.message = msg;
		},
		name: "ContinuousAssertError"
	});

	ReactiveSolver.subclass("AssertSolver", {
		initialize: function(message) {
			this.message = message;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			try {
				if(!opts.postponeEnabling) { cobj.enable(); }
			} catch(e) {
				//if(e instanceof ContinuousAssertError) {
				//	cobj.disable();
				//}
				throw e;
			}
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint && this.constraint.enabled && typeof this.constraint.predicate === "function")
	    		if(!this.constraint.predicate())
	    			throw new ContinuousAssertError(this.message);
	    }
	});

	Object.extend(Babelsberg.prototype, {
		assert: function(opts, func) {
			opts.solver = new AssertSolver(opts.message);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Triggering
	 ***************************************************************/
	AssertSolver.subclass("TriggerSolver", {
		initialize: function(callback) {
			this.callback = callback;
			this.triggeredOnce = false;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			if(!opts.postponeEnabling) { cobj.enable(); }
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
	    		if(this.constraint.predicate()) {
					if(!this.triggeredOnce) {
						this.triggeredOnce = true;
						bbb.addCallback(this.callback, this.constraint.bbbConstraint, []);
					}
				} else {
					this.triggeredOnce = false;
				}
			}
	    },
	    weight: 10
	});

	Object.extend(Babelsberg.prototype, {
		trigger: function(opts, func) {
			opts.solver = new TriggerSolver(opts.callback);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Layer activation
	 ***************************************************************/
	AssertSolver.subclass("LayerActivationSolver", {
		initialize: function(layer) {
			this.layer = layer;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			cobj.enable();
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
				var predicateFulfilled = this.constraint.predicate();
	    		if(predicateFulfilled && !this.layer.isGlobal()) {
	    			this.layer.beGlobal();
				} else  if(!predicateFulfilled && this.layer.isGlobal()) {
	    			this.layer.beNotGlobal();
				}
			}
	    },
	    weight: 10
	});

	Object.extend(Layer.prototype, {
		activeOn: function(opts, func) {
			opts.solver = new LayerActivationSolver(this);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        bbb.always(opts, func);

			return this;
		}
	});

	/***************************************************************
	 * Scoped constraints
	 ***************************************************************/
	Object.extend(Layer.prototype, {
		always: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.always(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		assert: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.assert(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		trigger: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.trigger(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		_activate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.enable();
			});
		},
		_deactivate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.disable();
			});
		}
	});

	/* Layer Activation */
	cop.withLayers = cop.withLayers.wrap(function(callOriginal, layers, func) {
		layers.forEach(function(layer) { layer._activate(); });

		try {
			return callOriginal(layers, func);
		} finally {
			layers.forEach(function(layer) { layer._deactivate(); });
		}
	});

	cop.withoutLayers = cop.withoutLayers.wrap(function(callOriginal, layers, func) {
		layers.forEach(function(layer) { layer._deactivate(); });

		try {
			return callOriginal(layers, func);
		} finally {
			layers.forEach(function(layer) { layer._activate(); });
		}
	});

	/* Global Layer Activation */
	cop.enableLayer = cop.enableLayer.wrap(function(callOriginal, layer) {
		layer._activate();
		return callOriginal(layer);
	});

	cop.disableLayer = cop.disableLayer.wrap(function(callOriginal, layer) {
		layer._deactivate();
		return callOriginal(layer);
	});
});
<commit_msg>make isConstraintObject a property in reactive<commit_after>module('users.timfelgentreff.reactive.reactive').requires('users.timfelgentreff.babelsberg.constraintinterpreter', 'cop.Layers').toRun(function() {

	JSLoader.loadJs(module('users.timfelgentreff.csp.underscore-min').uri());

	/***************************************************************
	 * Abstract Reactive Solver
	 ***************************************************************/

	Object.subclass("ReactiveSolver", {
	    isConstraintObject: true,
	    constraintVariableFor: function(value, ivarname, bbbCVar) {
	    	return new ReactiveSolver.Variable(this, value, ivarname, bbbCVar);
	    },
	    weight: 10
	});

	Object.subclass("ReactiveSolver.Variable", {
	    isConstraintObject: true,
		initialize: function(solver, value, ivarname, bbbCVar) {
			this.solver = solver;
			this.__val__ = value;
		},
	    suggestValue: function(value) {
			var prev = this.__val__;
	    	this.__val__ = value;
			try {
				this.solver.solve();
			} catch(e) {
				// revert value in case of a violated assertion
				//if(e instanceof ContinuousAssertError) {
				//	this.__val__ = prev;
				//}
				throw e;
			}

			// re-constrain variables
			if (typeof(value) == 'object' || typeof(value) == 'function') {
			    // only recalculate to reconstraint complex objects
                var bbbConstraint = this.solver.constraint.bbbConstraint;
                var enabled = bbbConstraint._enabled;
                bbbConstraint.initialize(bbbConstraint.predicate, bbbConstraint.solver);
                bbbConstraint.addPrimitiveConstraint(this.solver.constraint);
                if(enabled) bbbConstraint.enable();
			}

	    	return this.__val__;
	    },
	    value: function() {
	    	return this.__val__;
	    },
	    setReadonly: function(bool) {
	    	this.readonly = bool;
	    },
	    isReadonly: function() {
	        return this.readonly;
	    },
	    cnEquals: function() {
	        return new ReactiveSolver.PrimitiveConstraint(this, arguments);
	    }
	});

	Object.subclass("ReactiveSolver.PrimitiveConstraint", {
	    isConstraintObject: true,
	    initialize: function(variable, args) {
			this.enabled = false;
	    	this.solver = variable.solver;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	Object.subclass("ReactiveSolver.Constraint", {
	    isConstraintObject: true,
	    initialize: function(solver, bbbConstraint, func) {
			this.enabled = false;
	    	this.solver = solver;
	    	this.solver.constraint = this;
			this.bbbConstraint = bbbConstraint;

	    	this.predicate = func;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	/***************************************************************
	 * Continuous asserts
	 ***************************************************************/

	// TODO: integration with other solvers

	Error.subclass("ContinuousAssertError", {
		initialize: function ContinuousAssertError(msg) {
			if (Error.captureStackTrace) {
				Error.captureStackTrace(this, ContinuousAssertError);
			} else {
				this.stack = (new Error).stack || '';
			}
			this.message = msg;
		},
		name: "ContinuousAssertError"
	});

	ReactiveSolver.subclass("AssertSolver", {
		initialize: function(message) {
			this.message = message;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			try {
				if(!opts.postponeEnabling) { cobj.enable(); }
			} catch(e) {
				//if(e instanceof ContinuousAssertError) {
				//	cobj.disable();
				//}
				throw e;
			}
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint && this.constraint.enabled && typeof this.constraint.predicate === "function")
	    		if(!this.constraint.predicate())
	    			throw new ContinuousAssertError(this.message);
	    }
	});

	Object.extend(Babelsberg.prototype, {
		assert: function(opts, func) {
			opts.solver = new AssertSolver(opts.message);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Triggering
	 ***************************************************************/
	AssertSolver.subclass("TriggerSolver", {
		initialize: function(callback) {
			this.callback = callback;
			this.triggeredOnce = false;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			if(!opts.postponeEnabling) { cobj.enable(); }
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
	    		if(this.constraint.predicate()) {
					if(!this.triggeredOnce) {
						this.triggeredOnce = true;
						bbb.addCallback(this.callback, this.constraint.bbbConstraint, []);
					}
				} else {
					this.triggeredOnce = false;
				}
			}
	    },
	    weight: 10
	});

	Object.extend(Babelsberg.prototype, {
		trigger: function(opts, func) {
			opts.solver = new TriggerSolver(opts.callback);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Layer activation
	 ***************************************************************/
	AssertSolver.subclass("LayerActivationSolver", {
		initialize: function(layer) {
			this.layer = layer;
		},
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			cobj.enable();
	        return cobj;
	    },
	    solve: function() {
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
				var predicateFulfilled = this.constraint.predicate();
	    		if(predicateFulfilled && !this.layer.isGlobal()) {
	    			this.layer.beGlobal();
				} else  if(!predicateFulfilled && this.layer.isGlobal()) {
	    			this.layer.beNotGlobal();
				}
			}
	    },
	    weight: 10
	});

	Object.extend(Layer.prototype, {
		activeOn: function(opts, func) {
			opts.solver = new LayerActivationSolver(this);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        bbb.always(opts, func);

			return this;
		}
	});

	/***************************************************************
	 * Scoped constraints
	 ***************************************************************/
	Object.extend(Layer.prototype, {
		always: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.always(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		assert: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.assert(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		trigger: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.trigger(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);
		},
		_activate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.enable();
			});
		},
		_deactivate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.disable();
			});
		}
	});

	/* Layer Activation */
	cop.withLayers = cop.withLayers.wrap(function(callOriginal, layers, func) {
		layers.forEach(function(layer) { layer._activate(); });

		try {
			return callOriginal(layers, func);
		} finally {
			layers.forEach(function(layer) { layer._deactivate(); });
		}
	});

	cop.withoutLayers = cop.withoutLayers.wrap(function(callOriginal, layers, func) {
		layers.forEach(function(layer) { layer._deactivate(); });

		try {
			return callOriginal(layers, func);
		} finally {
			layers.forEach(function(layer) { layer._activate(); });
		}
	});

	/* Global Layer Activation */
	cop.enableLayer = cop.enableLayer.wrap(function(callOriginal, layer) {
		layer._activate();
		return callOriginal(layer);
	});

	cop.disableLayer = cop.disableLayer.wrap(function(callOriginal, layer) {
		layer._deactivate();
		return callOriginal(layer);
	});
});
<|endoftext|>


<commit_before>/*
 * CARIS oscar - Open Spatial Component ARchitecture
 *
 * Copyright 2012 CARIS <http://www.caris.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Class: oscar.FramedCloud
 *
 * Inherits from:
 * - <OpenLayers.Popup.FramedCloud>
 */

oscar.FramedCloud = oscar.BaseClass(OpenLayers.Popup.FramedCloud, {
	/**
	 * Property: positionBlocks
	 * {Object} Hash of different position blocks, keyed by relativePosition
	 *          two-character code string (ie "tl", "tr", "bl", "br")
	 */
	positionBlocks : {
		"tl" : {
			'offset' :new OpenLayers.Pixel(51, 4),
			'padding' :new OpenLayers.Bounds(8, 40, 8, 9),
			'blocks' : [ { // top-left
						size :new OpenLayers.Size('auto', 'auto'),
						anchor :new OpenLayers.Bounds(0, 51, 22, 0),
						position :new OpenLayers.Pixel(0, 0)
					}, { //top-right
						size :new OpenLayers.Size(22, 'auto'),
						anchor :new OpenLayers.Bounds(null, 50, 0, 0),
						position :new OpenLayers.Pixel(-638, 0)
					}, { //bottom-left
						size :new OpenLayers.Size('auto', 19),
						anchor :new OpenLayers.Bounds(0, 32, 22, null),
						position :new OpenLayers.Pixel(0, -631)
					}, { //bottom-right
						size :new OpenLayers.Size(22, 18),
						anchor :new OpenLayers.Bounds(null, 32, 0, null),
						position :new OpenLayers.Pixel(-638, -632)
					}, { // stem
						size :new OpenLayers.Size(80, 40),
						anchor :new OpenLayers.Bounds(null, 0, 0, null),
						position :new OpenLayers.Pixel(0, -681)
					} ]
		},
		"tr" : {
			'offset' :new OpenLayers.Pixel(-54, 4),
			'padding' :new OpenLayers.Bounds(8, 40, 8, 9),
			'blocks' : [ { // top-left
						size :new OpenLayers.Size('auto', 'auto'),
						anchor :new OpenLayers.Bounds(0, 51, 22, 0),
						position :new OpenLayers.Pixel(0, 0)
					}, { //top-right
						size :new OpenLayers.Size(22, 'auto'),
						anchor :new OpenLayers.Bounds(null, 50, 0, 0),
						position :new OpenLayers.Pixel(-638, 0)
					}, { //bottom-left
						size :new OpenLayers.Size('auto', 19),
						anchor :new OpenLayers.Bounds(0, 32, 22, null),
						position :new OpenLayers.Pixel(0, -631)
					}, { //bottom-right
						size :new OpenLayers.Size(22, 19),
						anchor :new OpenLayers.Bounds(null, 32, 0, null),
						position :new OpenLayers.Pixel(-638, -631)
					}, { // stem
						size :new OpenLayers.Size(80, 40),
						anchor :new OpenLayers.Bounds(0, 0, null, null),
						position :new OpenLayers.Pixel(-215, -681)
					} ]
		},
		"bl" : {
			'offset' :new OpenLayers.Pixel(41, -24),
			'padding' :new OpenLayers.Bounds(8, 9, 8, 40),
			'blocks' : [ { // top-left
						size :new OpenLayers.Size('auto', 'auto'),
						anchor :new OpenLayers.Bounds(0, 21, 22, 32),
						position :new OpenLayers.Pixel(0, 0)
					}, { //top-right
						size :new OpenLayers.Size(22, 'auto'),
						anchor :new OpenLayers.Bounds(null, 21, 0, 32),
						position :new OpenLayers.Pixel(-638, 0)
					}, { //bottom-left
						size :new OpenLayers.Size('auto', 21),
						anchor :new OpenLayers.Bounds(0, 0, 22, null),
						position :new OpenLayers.Pixel(0, -629)
					}, { //bottom-right
						size :new OpenLayers.Size(22, 21),
						anchor :new OpenLayers.Bounds(null, 0, 0, null),
						position :new OpenLayers.Pixel(-638, -629)
					}, { // stem,
						size :new OpenLayers.Size(80, 40),
						anchor :new OpenLayers.Bounds(null, null, 0, 0),
						position :new OpenLayers.Pixel(-100, -674)
					} ]
		},
		"br" : {
			'offset' :new OpenLayers.Pixel(-61, -24),
			'padding' :new OpenLayers.Bounds(8, 9, 8, 40),
			'blocks' : [ { // top-left
						size :new OpenLayers.Size('auto', 'auto'),
						anchor :new OpenLayers.Bounds(0, 21, 22, 32),
						position :new OpenLayers.Pixel(0, 0)
					}, { //top-right
						size :new OpenLayers.Size(22, 'auto'),
						anchor :new OpenLayers.Bounds(null, 21, 0, 32),
						position :new OpenLayers.Pixel(-638, 0)
					}, { //bottom-left
						size :new OpenLayers.Size('auto', 21),
						anchor :new OpenLayers.Bounds(0, 0, 22, null),
						position :new OpenLayers.Pixel(0, -629)
					}, { //bottom-right
						size :new OpenLayers.Size(22, 21),
						anchor :new OpenLayers.Bounds(null, 0, 0, null),
						position :new OpenLayers.Pixel(-638, -629)
					}, { // stem
						size :new OpenLayers.Size(80, 40),
						anchor :new OpenLayers.Bounds(0, null, null, 0),
						position :new OpenLayers.Pixel(-310, -674)
					} ]
		}
	},
	/**
	 * Property: imageSize
	 */
	imageSize :new OpenLayers.Size(676, 736),
	/**
	 * Constructor: oscar.FramedCloud
	 *
	 * Parameters:
	 * id - {String} a unique id of the popup. If null is passed an identifier will be automatically generated.
	 * lonlat - {OpenLayers.LonLat} a longitude and latitude pair. The position on the map the popup will be shown.
	 * contentSize - {OpenLayers.Size} a width/height pair size of the content.
	 * contentHTML - {String} the HTML content to be displayed inside the popup.
	 * anchor - {Object} object to which we�ll anchor the popup.
	 * closeBox - {Boolean} whether to display a close box inside the popup.
	 * closeBoxCallback - {Function} Function to be called on closeBox click.
	 */
	initialize : function(id, lonlat, contentSize, contentHTML, anchor,
			closeBox, closeBoxCallback) {
		OpenLayers.Popup.FramedCloud.prototype.initialize
				.apply(this, arguments);
		this.imageSrc = oscar.getImagePath()
				+ "cloud_popup_relative_outlined_a.png";
	},
	/**
	 * APIMethod: destroy
	 */
	destroy : function() {
		OpenLayers.Popup.FramedCloud.prototype.destroy.apply(this, arguments);
	},
	/**
	 * Constant: CLASS_NAME
	 *  - oscar.Popup.FramedCloud
	 */
	CLASS_NAME :'oscar.Popup.FramedCloud'
});<commit_msg>OSCAR-0<commit_after>/*
* CARIS oscar - Open Spatial Component ARchitecture
*
* Copyright 2012 CARIS <http://www.caris.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 	http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Class: oscar.FramedCloud
*
* Inherits from:
* - <OpenLayers.Popup.FramedCloud>
*/

oscar.FramedCloud = oscar.BaseClass(OpenLayers.Popup.FramedCloud, {
	/**
	* Property: positionBlocks
	* {Object} Hash of different position blocks, keyed by relativePosition
	*          two-character code string (ie "tl", "tr", "bl", "br")
	*/
	positionBlocks : {
		"tl" : {
			'offset' :new OpenLayers.Pixel(51, 4),
			'padding' :new OpenLayers.Bounds(8, 40, 8, 9),
			'blocks' : [ { // top-left
						size :new OpenLayers.Size('auto', 'auto'),
						anchor :new OpenLayers.Bounds(0, 51, 22, 0),
						position :new OpenLayers.Pixel(0, 0)
					}, { //top-right
						size :new OpenLayers.Size(22, 'auto'),
						anchor :new OpenLayers.Bounds(null, 50, 0, 0),
						position :new OpenLayers.Pixel(-638, 0)
					}, { //bottom-left
						size :new OpenLayers.Size('auto', 19),
						anchor :new OpenLayers.Bounds(0, 32, 22, null),
						position :new OpenLayers.Pixel(0, -631)
					}, { //bottom-right
						size :new OpenLayers.Size(22, 18),
						anchor :new OpenLayers.Bounds(null, 32, 0, null),
						position :new OpenLayers.Pixel(-638, -632)
					}, { // stem
						size :new OpenLayers.Size(80, 40),
						anchor :new OpenLayers.Bounds(null, 0, 0, null),
						position :new OpenLayers.Pixel(0, -681)
					} ]
		},
		"tr" : {
			'offset' :new OpenLayers.Pixel(-54, 4),
			'padding' :new OpenLayers.Bounds(8, 40, 8, 9),
			'blocks' : [ { // top-left
						size :new OpenLayers.Size('auto', 'auto'),
						anchor :new OpenLayers.Bounds(0, 51, 22, 0),
						position :new OpenLayers.Pixel(0, 0)
					}, { //top-right
						size :new OpenLayers.Size(22, 'auto'),
						anchor :new OpenLayers.Bounds(null, 50, 0, 0),
						position :new OpenLayers.Pixel(-638, 0)
					}, { //bottom-left
						size :new OpenLayers.Size('auto', 19),
						anchor :new OpenLayers.Bounds(0, 32, 22, null),
						position :new OpenLayers.Pixel(0, -631)
					}, { //bottom-right
						size :new OpenLayers.Size(22, 19),
						anchor :new OpenLayers.Bounds(null, 32, 0, null),
						position :new OpenLayers.Pixel(-638, -631)
					}, { // stem
						size :new OpenLayers.Size(80, 40),
						anchor :new OpenLayers.Bounds(0, 0, null, null),
						position :new OpenLayers.Pixel(-215, -681)
					} ]
		},
		"bl" : {
			'offset' :new OpenLayers.Pixel(41, -24),
			'padding' :new OpenLayers.Bounds(8, 9, 8, 40),
			'blocks' : [ { // top-left
						size :new OpenLayers.Size('auto', 'auto'),
						anchor :new OpenLayers.Bounds(0, 21, 22, 32),
						position :new OpenLayers.Pixel(0, 0)
					}, { //top-right
						size :new OpenLayers.Size(22, 'auto'),
						anchor :new OpenLayers.Bounds(null, 21, 0, 32),
						position :new OpenLayers.Pixel(-638, 0)
					}, { //bottom-left
						size :new OpenLayers.Size('auto', 21),
						anchor :new OpenLayers.Bounds(0, 0, 22, null),
						position :new OpenLayers.Pixel(0, -629)
					}, { //bottom-right
						size :new OpenLayers.Size(22, 21),
						anchor :new OpenLayers.Bounds(null, 0, 0, null),
						position :new OpenLayers.Pixel(-638, -629)
					}, { // stem,
						size :new OpenLayers.Size(80, 40),
						anchor :new OpenLayers.Bounds(null, null, 0, 0),
						position :new OpenLayers.Pixel(-100, -674)
					} ]
		},
		"br" : {
			'offset' :new OpenLayers.Pixel(-61, -24),
			'padding' :new OpenLayers.Bounds(8, 9, 8, 40),
			'blocks' : [ { // top-left
						size :new OpenLayers.Size('auto', 'auto'),
						anchor :new OpenLayers.Bounds(0, 21, 22, 32),
						position :new OpenLayers.Pixel(0, 0)
					}, { //top-right
						size :new OpenLayers.Size(22, 'auto'),
						anchor :new OpenLayers.Bounds(null, 21, 0, 32),
						position :new OpenLayers.Pixel(-638, 0)
					}, { //bottom-left
						size :new OpenLayers.Size('auto', 21),
						anchor :new OpenLayers.Bounds(0, 0, 22, null),
						position :new OpenLayers.Pixel(0, -629)
					}, { //bottom-right
						size :new OpenLayers.Size(22, 21),
						anchor :new OpenLayers.Bounds(null, 0, 0, null),
						position :new OpenLayers.Pixel(-638, -629)
					}, { // stem
						size :new OpenLayers.Size(80, 40),
						anchor :new OpenLayers.Bounds(0, null, null, 0),
						position :new OpenLayers.Pixel(-310, -674)
					} ]
		}
	},
	/**
	* Property: imageSize
	*/
	imageSize :new OpenLayers.Size(676, 736),
	/**
	* Constructor: oscar.FramedCloud
	*
	* Parameters:
	* id - {String} a unique id of the popup. If null is passed an identifier will be automatically generated.
	* lonlat - {OpenLayers.LonLat} a longitude and latitude pair. The position on the map the popup will be shown.
	* contentSize - {OpenLayers.Size} a width/height pair size of the content.
	* contentHTML - {String} the HTML content to be displayed inside the popup.
	* anchor - {Object} object to which we�ll anchor the popup.
	* closeBox - {Boolean} whether to display a close box inside the popup.
	* closeBoxCallback - {Function} Function to be called on closeBox click.
	*/
	initialize : function(id, lonlat, contentSize, contentHTML, anchor,
			closeBox, closeBoxCallback) {
		OpenLayers.Popup.FramedCloud.prototype.initialize
				.apply(this, arguments);
		this.imageSrc = oscar.getImagePath()
				+ "cloud_popup_relative_outlined_a.png";
	},
	/**
	* APIMethod: destroy
	*/
	destroy : function() {
		OpenLayers.Popup.FramedCloud.prototype.destroy.apply(this, arguments);
	},
	/**
	* Constant: CLASS_NAME
	*  - oscar.Popup.FramedCloud
	*/
	CLASS_NAME :'oscar.Popup.FramedCloud'
});<|endoftext|>


<commit_before>// Dependencies.
import { expect } from 'chai';
import sinon from 'sinon';

// Relative imports.
import {
  fetchFormsAction,
  fetchFormsFailure,
  fetchFormsSuccess,
  fetchFormsThunk,
} from '../../actions';
import {
  FETCH_FORMS,
  FETCH_FORMS_FAILURE,
  FETCH_FORMS_SUCCESS,
} from '../../constants';

describe('Find VA Forms actions', () => {
  describe('fetchFormsAction', () => {
    it('should return an action in the shape we expect', () => {
      const query = 'some text';
      const result = fetchFormsAction(query);

      expect(result).to.be.deep.equal({
        type: FETCH_FORMS,
        query,
      });
    });
  });

  describe('fetchFormsFailure', () => {
    it('should return an action in the shape we expect', () => {
      const result = fetchFormsFailure();

      expect(result).to.be.deep.equal({
        type: FETCH_FORMS_FAILURE,
      });
    });
  });

  describe('fetchFormsSuccess', () => {
    it('should return an action in the shape we expect', () => {
      const response = {};
      const result = fetchFormsSuccess(response);

      expect(result).to.be.deep.equal({
        response,
        type: FETCH_FORMS_SUCCESS,
      });
    });
  });

  describe('fetchFormsThunk', () => {
    const oldWindow = global.window;

    beforeEach(() => {
      global.window = {
        location: {
          search: '',
          pathname: '',
        },
        history: {
          replaceState: sinon.stub(),
        },
      };
    });

    afterEach(() => {
      global.window = oldWindow;
    });

    it('updates search params', async () => {
      const dispatch = () => {};
      const query = 'health';
      const thunk = fetchFormsThunk(query);

      await thunk(dispatch);

      const replaceStateStub = global.window.history.replaceState;

      expect(replaceStateStub.calledOnce).to.be.true;
      expect(replaceStateStub.firstCall.args[2]).to.be.equal('?q=health');
    });

    it('calls dispatch', async () => {
      const dispatch = sinon.stub();
      const query = 'health';
      const thunk = fetchFormsThunk(query);

      await thunk(dispatch);

      expect(
        dispatch.firstCall.calledWith({
          type: FETCH_FORMS,
          query,
        }),
      ).to.be.true;

      const secondCallAction = dispatch.secondCall.args[0];

      expect(secondCallAction.type).to.be.equal(FETCH_FORMS_SUCCESS);
      expect(secondCallAction.response).to.have.keys(['data']);
    });
  });
});
<commit_msg>Move global.window stub into Mocha hook (#11278)<commit_after>// Dependencies.
import { expect } from 'chai';
import sinon from 'sinon';

// Relative imports.
import {
  fetchFormsAction,
  fetchFormsFailure,
  fetchFormsSuccess,
  fetchFormsThunk,
} from '../../actions';
import {
  FETCH_FORMS,
  FETCH_FORMS_FAILURE,
  FETCH_FORMS_SUCCESS,
} from '../../constants';

describe('Find VA Forms actions', () => {
  describe('fetchFormsAction', () => {
    it('should return an action in the shape we expect', () => {
      const query = 'some text';
      const result = fetchFormsAction(query);

      expect(result).to.be.deep.equal({
        type: FETCH_FORMS,
        query,
      });
    });
  });

  describe('fetchFormsFailure', () => {
    it('should return an action in the shape we expect', () => {
      const result = fetchFormsFailure();

      expect(result).to.be.deep.equal({
        type: FETCH_FORMS_FAILURE,
      });
    });
  });

  describe('fetchFormsSuccess', () => {
    it('should return an action in the shape we expect', () => {
      const response = {};
      const result = fetchFormsSuccess(response);

      expect(result).to.be.deep.equal({
        response,
        type: FETCH_FORMS_SUCCESS,
      });
    });
  });

  describe('fetchFormsThunk', () => {
    let oldWindow;

    beforeEach(() => {
      oldWindow = global.window;
      global.window = {
        location: {
          search: '',
          pathname: '',
        },
        history: {
          replaceState: sinon.stub(),
        },
      };
    });

    afterEach(() => {
      global.window = oldWindow;
    });

    it('updates search params', async () => {
      const dispatch = () => {};
      const query = 'health';
      const thunk = fetchFormsThunk(query);

      await thunk(dispatch);

      const replaceStateStub = global.window.history.replaceState;

      expect(replaceStateStub.calledOnce).to.be.true;
      expect(replaceStateStub.firstCall.args[2]).to.be.equal('?q=health');
    });

    it('calls dispatch', async () => {
      const dispatch = sinon.stub();
      const query = 'health';
      const thunk = fetchFormsThunk(query);

      await thunk(dispatch);

      expect(
        dispatch.firstCall.calledWith({
          type: FETCH_FORMS,
          query,
        }),
      ).to.be.true;

      const secondCallAction = dispatch.secondCall.args[0];

      expect(secondCallAction.type).to.be.equal(FETCH_FORMS_SUCCESS);
      expect(secondCallAction.response).to.have.keys(['data']);
    });
  });
});
<|endoftext|>


<commit_before>/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.mozilla.js
 *        Gecko specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Volker Mische (vmx a-t gmx dotde)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
 */

WYMeditor.WymClassMozilla = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {

    this._iframe = iframe;
    this._doc = iframe.contentDocument;

    //add css rules from options

    var styles = this._doc.styleSheets[0];
    var aCss = eval(this._options.editorStyles);

    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);

    //init html value
    this.html(this._wym._html);

    //init designMode
    this.enableDesignMode();

    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);

    //bind external events
    this._wym.bindEvents();

    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);

    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);

    //bind editor focus events (used to reset designmode - Gecko bug)
    jQuery(this._doc).bind("focus", this.enableDesignMode);

    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);

    //add event listeners to doc elements, e.g. images
    this.listen();
};

/* @name html
 * @description Get/Set the html value
 */
WYMeditor.WymClassMozilla.prototype.html = function(html) {

  if(typeof html === 'string') {

    //disable designMode
    try { this._doc.designMode = "off"; } catch(e) { };

    //replace em by i and strong by bold
    //(designMode issue)
    html = html.replace(/]*)>/gi, "")
      .replace(/<\/em>/gi, "")
      .replace(/]*)>/gi, "")
      .replace(/<\/strong>/gi, "");

    //update the html body
    jQuery(this._doc.body).html(html);

    //re-init designMode
    this.enableDesignMode();
  }
  else return(jQuery(this._doc.body).html());
};

WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    switch(cmd) {

    case WYMeditor.INDENT: case WYMeditor.OUTDENT:

        var focusNode = this.selected();
        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;

        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);

        if(focusNode && focusNode == anchorNode
          && focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1
              || ancestor.tagName.toLowerCase() == WYMeditor.OL
              || ancestor.tagName.toLowerCase() == WYMeditor.UL)
                this._doc.execCommand(cmd,'',null);
        }

    break;

    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);
    }

    //set to P if parent = BODY
    var container = this.selected();
    if(container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
};

/* @name selected
 * @description Returns the selected container
 */
WYMeditor.WymClassMozilla.prototype.selected = function() {

    var sel = this._iframe.contentWindow.getSelection();
    var node = sel.focusNode;
    if(node) {
        if(node.nodeName == "#text") return(node.parentNode);
        else return(node);
    } else return(null);
};

WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};

//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  var container = null;

  if(evt.ctrlKey){
    if(evt.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      return false;
    }
    if(evt.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      return false;
    }
  }

  else if(evt.keyCode == 13) {
    if(!evt.shiftKey){
      //fix PRE bug #73
      container = wym.selected();
      if(container && container.tagName.toLowerCase() == WYMeditor.PRE) {
        evt.preventDefault();
        wym.insert('

');
      }
    }
  }
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];

  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {

    //RETURN key
    //cleanup

 between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();
  }

  else if(evt.keyCode != 8
       && evt.keyCode != 17
       && evt.keyCode != 46
       && evt.keyCode != 224
       && !evt.metaKey
       && !evt.ctrlKey) {

    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P

    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a"

    ) name = container.parentNode.tagName.toLowerCase();

    if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
  }
};

WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
    if(this.designMode == "off") {
      try {
        this.designMode = "on";
        this.execCommand("styleWithCSS", '', false);
      } catch(e) { }
    }
};

WYMeditor.WymClassMozilla.prototype.setFocusToNode = function(node) {
    var range = document.createRange();
    range.selectNode(node);
    var selected = this._iframe.contentWindow.getSelection();
    selected.addRange(range);
    selected.collapse(node, node.childNodes.length);
    this._iframe.contentWindow.focus();
};

WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
  var attributes = this.validator.getValidTagAttributes(tag, attributes);

  // Handle Mozilla styled spans
  if(tag == 'span' && attributes.style){
    var new_tag = this.getTagForStyle(attributes.style);
    if(new_tag){
      this._tag_stack.pop();
      var tag = new_tag;
      this._tag_stack.push(new_tag);
      attributes.style = '';
    }else{
      return;
    }
  }

  this.output += this.helper.tag(tag, attributes, true);
};

WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {

  if(/bold/.test(style)) return 'strong';
  if(/italic/.test(style)) return 'em';
  if(/sub/.test(style)) return 'sub';
  if(/super/.test(style)) return 'sup';
  return false;
};

<commit_msg>Fixing #201, designMode weren't initiated properly until editor got focus<commit_after>/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.mozilla.js
 *        Gecko specific class and functions.
 *        See the documentation for more info.
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 *        Volker Mische (vmx a-t gmx dotde)
 *        Bermi Ferrer (wymeditor a-t bermi dotorg)
 *        Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
 */

WYMeditor.WymClassMozilla = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {
    var wym = this;

    this._iframe = iframe;
    this._doc = iframe.contentDocument;

    //add css rules from options

    var styles = this._doc.styleSheets[0];
    var aCss = eval(this._options.editorStyles);

    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);

    //init html value
    this.html(this._wym._html);

    //init designMode
    this.enableDesignMode();

    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);

    //bind external events
    this._wym.bindEvents();

    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);

    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);

    //bind editor focus events (used to reset designmode - Gecko bug)
    jQuery(this._doc).bind("focus", function () {
        // Fix scope
        wym.enableDesignMode.call(wym);
    });

    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);

    //add event listeners to doc elements, e.g. images
    this.listen();
};

/* @name html
 * @description Get/Set the html value
 */
WYMeditor.WymClassMozilla.prototype.html = function(html) {

  if(typeof html === 'string') {

    //disable designMode
    try { this._doc.designMode = "off"; } catch(e) { };

    //replace em by i and strong by bold
    //(designMode issue)
    html = html.replace(/]*)>/gi, "")
      .replace(/<\/em>/gi, "")
      .replace(/]*)>/gi, "")
      .replace(/<\/strong>/gi, "");

    //update the html body
    jQuery(this._doc.body).html(html);

    //re-init designMode
    this.enableDesignMode();
  }
  else return(jQuery(this._doc.body).html());
};

WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    switch(cmd) {

    case WYMeditor.INDENT: case WYMeditor.OUTDENT:

        var focusNode = this.selected();
        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;

        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);

        if(focusNode && focusNode == anchorNode
          && focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1
              || ancestor.tagName.toLowerCase() == WYMeditor.OL
              || ancestor.tagName.toLowerCase() == WYMeditor.UL)
                this._doc.execCommand(cmd,'',null);
        }

    break;

    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);
    }

    //set to P if parent = BODY
    var container = this.selected();
    if(container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
};

/* @name selected
 * @description Returns the selected container
 */
WYMeditor.WymClassMozilla.prototype.selected = function() {

    var sel = this._iframe.contentWindow.getSelection();
    var node = sel.focusNode;
    if(node) {
        if(node.nodeName == "#text") return(node.parentNode);
        else return(node);
    } else return(null);
};

WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};

//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];
  var container = null;

  if(evt.ctrlKey){
    if(evt.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      return false;
    }
    if(evt.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      return false;
    }
  }

  else if(evt.keyCode == 13) {
    if(!evt.shiftKey){
      //fix PRE bug #73
      container = wym.selected();
      if(container && container.tagName.toLowerCase() == WYMeditor.PRE) {
        evt.preventDefault();
        wym.insert('

');
      }
    }
  }
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];

  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {

    //RETURN key
    //cleanup

 between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();
  }

  else if(evt.keyCode != 8
       && evt.keyCode != 17
       && evt.keyCode != 46
       && evt.keyCode != 224
       && !evt.metaKey
       && !evt.ctrlKey) {

    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P

    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a"

    ) name = container.parentNode.tagName.toLowerCase();

    if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
  }
};

WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
    if(this._doc.designMode == "off") {
      try {
        this._doc.designMode = "on";
        this._doc.execCommand("styleWithCSS", '', false);
      } catch(e) { }
    }
};

WYMeditor.WymClassMozilla.prototype.setFocusToNode = function(node) {
    var range = document.createRange();
    range.selectNode(node);
    var selected = this._iframe.contentWindow.getSelection();
    selected.addRange(range);
    selected.collapse(node, node.childNodes.length);
    this._iframe.contentWindow.focus();
};

WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
  var attributes = this.validator.getValidTagAttributes(tag, attributes);

  // Handle Mozilla styled spans
  if(tag == 'span' && attributes.style){
    var new_tag = this.getTagForStyle(attributes.style);
    if(new_tag){
      this._tag_stack.pop();
      var tag = new_tag;
      this._tag_stack.push(new_tag);
      attributes.style = '';
    }else{
      return;
    }
  }

  this.output += this.helper.tag(tag, attributes, true);
};

WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {

  if(/bold/.test(style)) return 'strong';
  if(/italic/.test(style)) return 'em';
  if(/sub/.test(style)) return 'sub';
  if(/super/.test(style)) return 'sup';
  return false;
};

<|endoftext|>


<commit_before>class ChartsChartjsController {
  constructor ($scope) {
    'ngInject'
  }

  $onInit () {
    this.lineChartLabels = ['Januarys', 'February', 'March', 'April', 'May', 'June', 'July']
    this.lineChartSeries = ['Series A', 'Series B']
    this.lineChartData = [
      [65, 59, 80, 81, 56, 55, 40],
      [28, 48, 40, 19, 86, 27, 90]
    ]

    this.areaChartLabels = ['Januarys', 'February', 'March', 'April', 'May', 'June', 'July']
    this.areaChartSeries = ['Series A', 'Series B']
    this.areaChartData = [
      [65, 59, 80, 81, 56, 55, 40],
      [28, 48, 40, 19, 86, 27, 90]
    ]
    this.areaChartColours = [
      {
        fillColor: '#D2D6DE',
        strokeColor: '#D2D6DE',
        pointColor: 'rgba(148,159,177,1)',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(148,159,177,0.8)'
      },
      {
        fillColor: '#4B94C0',
        strokeColor: '#4B94C0',
        pointColor: '#2980b9',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(77,83,96,1)'
      }
    ]

    this.onClick = function () {}

    this.barChartLabels = ['Januarys', 'February', 'March', 'April', 'May', 'June', 'July']
    this.barChartSeries = ['Series A', 'Series B']
    this.barChartData = [
      [65, 59, 80, 81, 56, 55, 40],
      [28, 48, 40, 19, 86, 27, 90]
    ]
    this.barChartColours = [
      {
        fillColor: '#D2D6DE',
        strokeColor: '#D2D6DE',
        pointColor: 'rgba(148,159,177,1)',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(148,159,177,0.8)'
      },
      {
        fillColor: '#00A65A',
        strokeColor: '#00A65A',
        pointColor: '#2980b9',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(77,83,96,1)'
      }
    ]

    this.pieLabels = ['Download Sales', 'In-Store Sales', 'Mail-Order Sales']
    this.pieData = [300, 500, 100]
  }
}

export const ChartsChartjsComponent = {
  templateUrl: './views/app/components/charts-chartjs/charts-chartjs.component.html',
  controller: ChartsChartjsController,
  controllerAs: 'vm',
  bindings: {}
}
<commit_msg>Fix error on running ngHtml2Js<commit_after>class ChartsChartjsController {
  constructor () {
    'ngInject'
  }

  $onInit () {
    this.lineChartLabels = ['Januarys', 'February', 'March', 'April', 'May', 'June', 'July']
    this.lineChartSeries = ['Series A', 'Series B']
    this.lineChartData = [
      [65, 59, 80, 81, 56, 55, 40],
      [28, 48, 40, 19, 86, 27, 90]
    ]

    this.areaChartLabels = ['Januarys', 'February', 'March', 'April', 'May', 'June', 'July']
    this.areaChartSeries = ['Series A', 'Series B']
    this.areaChartData = [
      [65, 59, 80, 81, 56, 55, 40],
      [28, 48, 40, 19, 86, 27, 90]
    ]
    this.areaChartColours = [
      {
        fillColor: '#D2D6DE',
        strokeColor: '#D2D6DE',
        pointColor: 'rgba(148,159,177,1)',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(148,159,177,0.8)'
      },
      {
        fillColor: '#4B94C0',
        strokeColor: '#4B94C0',
        pointColor: '#2980b9',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(77,83,96,1)'
      }
    ]

    this.onClick = function () {}

    this.barChartLabels = ['Januarys', 'February', 'March', 'April', 'May', 'June', 'July']
    this.barChartSeries = ['Series A', 'Series B']
    this.barChartData = [
      [65, 59, 80, 81, 56, 55, 40],
      [28, 48, 40, 19, 86, 27, 90]
    ]
    this.barChartColours = [
      {
        fillColor: '#D2D6DE',
        strokeColor: '#D2D6DE',
        pointColor: 'rgba(148,159,177,1)',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(148,159,177,0.8)'
      },
      {
        fillColor: '#00A65A',
        strokeColor: '#00A65A',
        pointColor: '#2980b9',
        pointStrokeColor: '#fff',
        pointHighlightFill: '#fff',
        pointHighlightStroke: 'rgba(77,83,96,1)'
      }
    ]

    this.pieLabels = ['Download Sales', 'In-Store Sales', 'Mail-Order Sales']
    this.pieData = [300, 500, 100]
  }
}

export const ChartsChartjsComponent = {
  templateUrl: './views/app/components/charts-chartjs/charts-chartjs.component.html',
  controller: ChartsChartjsController,
  controllerAs: 'vm',
  bindings: {}
}
<|endoftext|>


<commit_before>(function() {
  var Payment, React, ReactCard, ReactCardFormContainer, ReactDOM;

  React = require('react');

  ReactDOM = require('react-dom');

  Payment = require('payment');

  ReactCard = require('./card-react-component');

  ReactCardFormContainer = React.createClass({
    displayName: 'ReactCardContainer',
    getDefaultProps: function() {
      return {
        formatting: true,
        formInputsNames: {
          number: 'number',
          expiry: 'expiry',
          cvc: 'cvc',
          name: 'name'
        },
        classes: {
          valid: 'jp-card-valid',
          invalid: 'jp-card-invalid'
        },
        initialValues: {},
        fieldTypes: ["number", "cvc", "expiry", "name"]
      };
    },
    getInitialState: function() {
      return {
        inputsValidationClass: {}
      };
    },
    componentWillMount: function() {
      var type, _i, _len, _ref, _results;
      this.inputsValues = {};
      this.inputsRefs = {};
      this.cardFlipped = false;
      _ref = this.props.fieldTypes;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        type = _ref[_i];
        _results.push(this.inputsValues[this.props.formInputsNames[type]] = this.props.initialValues[type]);
      }
      return _results;
    },
    componentDidMount: function() {
      if (!this.props.container) {
        console.log("Please provide a container react-card");
        return;
      }
      this.cardContainer = document.getElementById(this.props.container);
      if (!this.cardContainer) {
        console.log("couldn't find react-card container by its id. please make sure the correct id is provided");
        return;
      }
      if (this.props.formatting) {
        this.formatInputs();
      }
      return this.renderCardComponent();
    },
    formatInputs: function() {
      var inputsNames;
      inputsNames = this.props.formInputsNames;
      Payment.formatCardNumber(ReactDOM.findDOMNode(this.refs[this.inputsRefs[inputsNames["number"]]]));
      Payment.formatCardCVC(ReactDOM.findDOMNode(this.refs[this.inputsRefs[inputsNames["cvc"]]]));
      return Payment.formatCardExpiry(ReactDOM.findDOMNode(this.refs[this.inputsRefs[inputsNames["expiry"]]]));
    },
    renderCardComponent: function() {
      if (this.cardContainer) {
        return ReactDOM.render(React.createElement(ReactCard, React.__spread({}, this.props, {
          "cardFlipped": this.cardFlipped,
          "focusedInput": this.focusedInput,
          "inputsValues": this.inputsValues,
          "inputsValidationClass": this.state.inputsValidationClass
        })), this.cardContainer);
      }
    },
    traverseChildrenAndRegisterInputs: function(children) {
      if (typeof children !== 'object' || children === null) {
        return children;
      }
      return React.Children.map(children, (function(_this) {
        return function(child) {
          var inputsValidationClass, newClassName;
          if (typeof child !== 'object' || child === null) {
            return child;
          }
          if (child.props && child.props.name) {
            newClassName = child.props.className;
            inputsValidationClass = _this.state.inputsValidationClass[child.props.name];
            if (child.ref) {
              _this.inputsRefs[child.props.name] = child.ref;
            } else {
              _this.inputsRefs[child.props.name] = "react-card-input-" + child.props.name;
            }
            if (newClassName && inputsValidationClass) {
              newClassName = "" + newClassName + " " + inputsValidationClass;
            } else if (inputsValidationClass) {
              newClassName = inputsValidationClass;
            }
            return React.cloneElement(child, {
              onKeyUp: _this.inputOnKeyUp,
              onFocus: _this.inputOnFocus,
              onBlur: _this.inputOnBlur,
              ref: _this.inputsRefs[child.props.name],
              defaultValue: _this.inputsValues[child.props.name],
              className: newClassName
            }, child.props && child.props.children);
          } else {
            return React.cloneElement(child, {}, _this.traverseChildrenAndRegisterInputs(child.props && child.props.children));
          }
        };
      })(this));
    },
    inputOnKeyUp: function(event) {
      this.inputsValues[event.target.name] = event.target.value;
      this.validateInput(event.target.name, event.target.value);
      return this.renderCardComponent();
    },
    inputOnFocus: function(event) {
      this.focusedInput = event.target.name;
      if (this.focusedInput === this.props.formInputsNames['cvc']) {
        this.cardFlipped = true;
      }
      return this.renderCardComponent();
    },
    inputOnBlur: function(event) {
      this.focusedInput = '';
      this.cardFlipped = false;
      return this.renderCardComponent();
    },
    validateInput: function(inputName, inputValue) {
      var currentInputsValidationClass, inputsNames, objVal;
      inputsNames = this.props.formInputsNames;
      currentInputsValidationClass = this.state.inputsValidationClass;
      switch (inputName) {
        case inputsNames["expiry"]:
          objVal = Payment.fns.cardExpiryVal(inputValue);
          currentInputsValidationClass[inputsNames["expiry"]] = this.getInputValidationClass(Payment.fns.validateCardExpiry(objVal.month, objVal.year));
          break;
        case inputsNames["cvc"]:
          currentInputsValidationClass[inputsNames["cvc"]] = this.getInputValidationClass(Payment.fns.validateCardCVC(inputValue, this.cardType));
          break;
        case inputsNames["number"]:
          currentInputsValidationClass[inputsNames["number"]] = this.getInputValidationClass(Payment.fns.validateCardNumber(inputValue));
          break;
        case inputsNames["name"]:
          currentInputsValidationClass[inputsNames["name"]] = this.getInputValidationClass(inputValue !== "");
      }
      return this.setState({
        inputsValidationClass: currentInputsValidationClass
      });
    },
    getInputValidationClass: function(inputValid) {
      if (inputValid) {
        return this.props.classes.valid;
      } else {
        return this.props.classes.invalid;
      }
    },
    render: function() {
      return React.createElement("div", null, this.traverseChildrenAndRegisterInputs(this.props.children));
    }
  });

  module.exports = ReactCardFormContainer;

}).call(this);
<commit_msg>Updated lib js file<commit_after>(function() {
  var Payment, React, ReactCard, ReactCardFormContainer, ReactDOM;

  React = require('react');

  ReactDOM = require('react-dom');

  Payment = require('payment');

  ReactCard = require('./card-react-component');

  ReactCardFormContainer = React.createClass({
    displayName: 'ReactCardContainer',
    getDefaultProps: function() {
      return {
        formatting: true,
        formInputsNames: {
          number: 'number',
          expiry: 'expiry',
          cvc: 'cvc',
          name: 'name'
        },
        classes: {
          valid: 'jp-card-valid',
          invalid: 'jp-card-invalid'
        },
        initialValues: {},
        fieldTypes: ["number", "cvc", "expiry", "name"]
      };
    },
    getInitialState: function() {
      return {
        inputsValidationClass: {}
      };
    },
    componentWillMount: function() {
      var i, len, ref, results, type;
      this.inputsValues = {};
      this.inputsRefs = {};
      this.cardFlipped = false;
      ref = this.props.fieldTypes;
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        type = ref[i];
        results.push(this.inputsValues[this.props.formInputsNames[type]] = this.props.initialValues[type]);
      }
      return results;
    },
    componentDidMount: function() {
      if (!this.props.container) {
        console.log("Please provide a container react-card");
        return;
      }
      this.cardContainer = document.getElementById(this.props.container);
      if (!this.cardContainer) {
        console.log("couldn't find react-card container by its id. please make sure the correct id is provided");
        return;
      }
      if (this.props.formatting) {
        this.formatInputs();
      }
      return this.renderCardComponent();
    },
    formatInputs: function() {
      var inputsNames;
      inputsNames = this.props.formInputsNames;
      Payment.formatCardNumber(ReactDOM.findDOMNode(this.refs[this.inputsRefs[inputsNames["number"]]]));
      Payment.formatCardCVC(ReactDOM.findDOMNode(this.refs[this.inputsRefs[inputsNames["cvc"]]]));
      return Payment.formatCardExpiry(ReactDOM.findDOMNode(this.refs[this.inputsRefs[inputsNames["expiry"]]]));
    },
    renderCardComponent: function() {
      if (this.cardContainer) {
        return ReactDOM.render(React.createElement(ReactCard, Object.assign({}, this.props, {
          "cardFlipped": this.cardFlipped,
          "focusedInput": this.focusedInput,
          "inputsValues": this.inputsValues,
          "inputsValidationClass": this.state.inputsValidationClass
        })), this.cardContainer);
      }
    },
    traverseChildrenAndRegisterInputs: function(children) {
      if (typeof children !== 'object' || children === null) {
        return children;
      }
      return React.Children.map(children, (function(_this) {
        return function(child) {
          var inputsValidationClass, newClassName;
          if (typeof child !== 'object' || child === null) {
            return child;
          }
          if (child.props && child.props.name) {
            newClassName = child.props.className;
            inputsValidationClass = _this.state.inputsValidationClass[child.props.name];
            if (child.ref) {
              _this.inputsRefs[child.props.name] = child.ref;
            } else {
              _this.inputsRefs[child.props.name] = "react-card-input-" + child.props.name;
            }
            if (newClassName && inputsValidationClass) {
              newClassName = newClassName + " " + inputsValidationClass;
            } else if (inputsValidationClass) {
              newClassName = inputsValidationClass;
            }
            return React.cloneElement(child, {
              onKeyUp: _this.inputOnKeyUp,
              onFocus: _this.inputOnFocus,
              onBlur: _this.inputOnBlur,
              ref: _this.inputsRefs[child.props.name],
              defaultValue: _this.inputsValues[child.props.name],
              className: newClassName
            }, child.props && child.props.children);
          } else {
            return React.cloneElement(child, {}, _this.traverseChildrenAndRegisterInputs(child.props && child.props.children));
          }
        };
      })(this));
    },
    inputOnKeyUp: function(event) {
      this.inputsValues[event.target.name] = event.target.value;
      this.validateInput(event.target.name, event.target.value);
      return this.renderCardComponent();
    },
    inputOnFocus: function(event) {
      this.focusedInput = event.target.name;
      if (this.focusedInput === this.props.formInputsNames['cvc']) {
        this.cardFlipped = true;
      }
      return this.renderCardComponent();
    },
    inputOnBlur: function(event) {
      this.focusedInput = '';
      this.cardFlipped = false;
      return this.renderCardComponent();
    },
    validateInput: function(inputName, inputValue) {
      var currentInputsValidationClass, inputsNames, objVal;
      inputsNames = this.props.formInputsNames;
      currentInputsValidationClass = this.state.inputsValidationClass;
      switch (inputName) {
        case inputsNames["expiry"]:
          objVal = Payment.fns.cardExpiryVal(inputValue);
          currentInputsValidationClass[inputsNames["expiry"]] = this.getInputValidationClass(Payment.fns.validateCardExpiry(objVal.month, objVal.year));
          break;
        case inputsNames["cvc"]:
          currentInputsValidationClass[inputsNames["cvc"]] = this.getInputValidationClass(Payment.fns.validateCardCVC(inputValue, this.cardType));
          break;
        case inputsNames["number"]:
          currentInputsValidationClass[inputsNames["number"]] = this.getInputValidationClass(Payment.fns.validateCardNumber(inputValue));
          break;
        case inputsNames["name"]:
          currentInputsValidationClass[inputsNames["name"]] = this.getInputValidationClass(inputValue !== "");
      }
      return this.setState({
        inputsValidationClass: currentInputsValidationClass
      });
    },
    getInputValidationClass: function(inputValid) {
      if (inputValid) {
        return this.props.classes.valid;
      } else {
        return this.props.classes.invalid;
      }
    },
    render: function() {
      return React.createElement("div", null, this.traverseChildrenAndRegisterInputs(this.props.children));
    }
  });

  module.exports = ReactCardFormContainer;

}).call(this);
<|endoftext|>