<commit_before>Vue.prototype.$axios = axios;
Vue.prototype.$moment = moment;
Vue.prototype.$qs = Qs;
Vue.prototype._ = _;
Vue.prototype.sessionStorage = window.sessionStorage;
Vue.prototype.localStorage = window.localStorage;
Vue.prototype.console = console;

(function () {
    let urlKey = `last_url_query.${document.location.pathname}`;
    window.onbeforeunload = (e) => {
        sessionStorage.setItem(urlKey, document.location.search);
    };

    if (document.location.search !== '' || document.referrer === '') {
        return;
    }
    let last_url_query = sessionStorage.getItem(urlKey);
    window.history.replaceState(null, null, last_url_query === null ? '' : last_url_query);
}());

document.location.query = document.location.search !== '' ? Qs.parse(document.location.search.substr(1)) : {};

//axios.defaults.baseURL = 'http://www.manaphp.com';
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

axios.interceptors.request.use(function (config) {
    if (typeof vm.loading == 'boolean') {
        vm.loading = true;
    }

    config.url += config.url.indexOf('?') === -1 ? '?ajax' : '&ajax';
    return config;
});

axios.interceptors.response.use(function (res) {
        if (typeof vm.loading === 'boolean') {
            vm.loading = false;
        }

        if (!Vue.config.silent) {
            var now = new Date();
            console.warn('[AJAX][%s.%i][%s][%s] %o', now.toLocaleString('en-GB'), now.getMilliseconds(), res.headers['x-response-time'], res.config.url, res);
        }

        if (typeof res.data === 'string') {
            vm.$alert(res.data, '服务器错误', {customClass: 'error-response'});
        }

        if (res.data.code === 0) {
            if (res.data.message) {
                vm.$message({type: 'success', duration: 1000, message: res.data.message});
            } else if (res.config.method !== 'get') {
                vm.$message({type: 'success', duration: 1000, message: '操作成功'});
            }
        }

        for (let name in res.headers) {
            let value = res.headers[name];
            if (value.match(/^https?:\/\//)) {
                console.warn('*'.repeat(32) + ' ' + name + ': ' + value);
            }
        }

        return res;
    },
    function (error) {
        if (typeof vm.loading == 'boolean') {
            vm.loading = false;
        }

        console.log(error);
        if (error.response.status) {
            switch (error.response.status) {
                case 400:
                    alert(error.response.data.message);
                    break;
                case 401:
                    window.location.href = window.login_url;
                    break;
                default:
                    alert(error.response.message || '网络错误，请稍后重试: ' + error.response.status);
                    break;
            }
        } else {
            alert('网络错误，请稍后重试。');
        }
    });

Vue.prototype.ajax_get = function (url, data, success) {
    if (typeof data === 'function') {
        success = data;
        data = null;
    } else if (data) {
        url += (url.indexOf('?') === -1 ? '?' : '&') + Qs.stringify(data);
    }

    if (success && url.match(/\bcache=[12]\b/) && localStorage.getItem('axios.cache.enabled') !== '0') {
        var cache_key = 'axios.cache.' + url;
        let cache_value = sessionStorage.getItem(cache_key);
        if (cache_value) {
            success.bind(this)(JSON.parse(cache_value));
            return;
        }
    }

    return this.$axios.get(url).then(function (res) {
        if (res.data.code === 0) {
            if (success) {
                if (cache_key) {
                    sessionStorage.setItem(cache_key, JSON.stringify(res.data.data));
                }
                success.bind(this)(res.data.data);
            }
        } else if (res.data.message) {
            this.$alert(res.data.message);
        }
        return res;
    }.bind(this));
}

Vue.prototype.ajax_post = function (url, data, success) {
    if (typeof data === 'function') {
        success = data;
        data = {};
    }

    var config = {};
    if (data instanceof FormData) {
        config.headers = {'Content-Type': 'multipart/form-data'};
    }

    return this.$axios.post(url, data, config).then(function (res) {
        if (res.data.code === 0 && success) {
            success.bind(this)(res.data.data);
        }

        if (res.data.message !== '') {
            this.$alert(res.data.message);
        }
        return res
    }.bind(this));
}

Vue.filter('date', function (value, format = 'YYYY-MM-DD HH:mm:ss') {
    return value ? moment(value * 1000).format(format) : '';
})

Vue.filter('json', function (value) {
    return JSON.stringify(typeof value === 'string' ? JSON.parse(value) : value, null, 2);
})

Vue.component('pager', {
    props: ['request', 'response'],
    template: ' <el-pagination background :current-page="Number(response.page)"\n' +
        '                   :page-size="Number(request.size)"\n' +
        '                   :page-sizes="[10,20,25,50,100,500,1000]"\n' +
        '                   @current-change="request.page=$event"\n' +
        '                   @size-change="request.size=$event; request.page=1"\n' +
        '                   :total="response.count" layout="sizes,total, prev, pager, next, jumper"></el-pagination>\n',
    watch: {
        request: {
            handler: function () {
                for (var field in this.request) {
                    if (field === 'page' || field === 'size') {
                        continue;
                    }
                    if (field in this.last_request && this.last_request[field] != this.request[field]) {
                        this.response.page = 1;
                        this.request.page = 1;
                        this.last_request = Object.assign({}, this.request);
                        break;
                    }
                }
            },
            deep: true
        }
    },
    data: function () {
        return {
            last_request: Object.assign({}, this.request)
        }
    }
});

Vue.component('date-picker', {
    props: ['value'],
    template: '<el-date-picker v-model="time" type="daterange" start-placeholder="开始日期"\n ' +
        '                            end-placeholder="结束日期" value-format="yyyy-MM-dd" size="small"\n ' +
        ' :picker-options="pickerOptions" @change="change"' +
        '></el-date-picker>',
    methods: {
        change: function (value) {
            this.$emit('input', value);
        }
    },
    watch: {
        value: function (val) {
            this.time = val;
        }
    },
    data: function () {
        return {
            time: this.value,
            pickerOptions: {
                shortcuts: [
                    {
                        text: '今天',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime());
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '昨天',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24);
                            end.setDate(end.getDate() - 1);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近三天',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近一周',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近一个月',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近三个月',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近一年',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '本周',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setDate(start.getDate() - start.getDay() + 1);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '本月',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setDate(1);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '本季',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setMonth(parseInt(start.getMonth() / 3) * 3);
                            start.setDate(1);
                            picker.$emit('pick', [start, end]);
                        }
                    }
                ]
            }
        }
    }
});

Vue.component('my-menu', {
    template: `
<el-menu :default-active="active" class="el-menu-vertical-demo" :unique-opened="true">
    <template v-for="group in groups">
        <el-submenu :index="group.group_name">
            <template slot="title">

                {{group.group_name}}
            </template>
            <template v-for="item in group.items ">
                <el-menu-item :index="item.url">
                    <el-link :href="item.url">{{item.item_name}}</el-link>
                </el-menu-item>
            </template>
        </el-submenu>
     </template>
</el-menu>`,
    created() {
        this.ajax_get('/menu/my?cache=2', function (res) {
            this.groups = res;

            let active = location.pathname;
            for (let group of res) {
                for (let item of group.items) {
                    if (item.url === active) {
                        document.title = ' ' + group.group_name + ' - ' + item.item_name;
                        break;
                    }
                }
            }
        })
    },
    data() {
        return {
            active: location.pathname,
            groups: []
        }
    }
});

Vue.component('axios-cache-switcher', {
    template: `

缓存 (√)

缓存 (×)

`,
    data() {
        return {
            enabled: localStorage.getItem('axios.cache.enabled') !== '0'
        }
    }
});
Vue.prototype.format_date = function (value) {
    return value ? this.$moment(value * 1000).format('YYYY-MM-DD HH:mm:ss') : '';
}

Vue.prototype.auto_reload = function () {
    if (this.request && this.response) {
        let qs = this.$qs.parse(document.location.query);
        for (let k in qs) {
            this.$set(this.request, k, qs[k]);
        }

        this.$watch('request', _.debounce(function () {
            this.reload();
        }, 500), {deep: true});

        this.reload();
    }
}

App = Vue.extend({
    methods: {
        reload: function () {
            if (!this.request || !this.response) {
                alert('bad reload');
            }

            var qs = this.$qs.stringify(this.request);
            window.history.replaceState(null, null, qs ? ('?' + qs) : '');
            document.location.query = document.location.search !== '' ? Qs.parse(document.location.search.substr(1)) : {};
            this.response = [];
            this.$axios.get(document.location.href).then(function (res) {
                if (res.data.code !== 0) {
                    this.$alert(res.data.message);
                } else {
                    this.response = res.data.data;
                }
            }.bind(this));
        },
        fDate: function (row, column, value) {
            return this.format_date(value);
        },

        fEnabled: function (row, column, value) {
            return ['禁用', '启用'][value];
        },
        do_create: function (create) {
            var success = true;
            if (typeof create === 'string') {
                this.$refs[create].validate(valid => success = valid);
            }
            success && this.ajax_post(window.location.pathname + "/create", this.create, function (res) {
                this.createVisible = false;
                this.$refs.create.resetFields();
                this.reload();
            });
        },
        show_edit: function (row, overwrite = {}) {
            this.edit = Object.assign({}, row, overwrite);
            this.editVisible = true;
        },
        do_edit: function () {
            this.ajax_post(window.location.pathname + "/edit", this.edit, function (res) {
                this.editVisible = false;
                this.reload();
            });
        },
        show_detail: function (row, action) {
            this.detailVisible = true;

            var data = {};
            var key = Object.keys(row)[0];
            data[key] = row[key];

            this.ajax_get(window.location.pathname + '/' + (action ? action : "detail"), data, function (res) {
                this.detail = res;
            });
        },
        do_delete: function (row, name = '') {
            var data = {};
            var keys = Object.keys(row);
            var key = keys[0];
            data[key] = row[key];

            if (!name) {
                name = (keys[1] && keys[1].indexOf('_name')) ? row[keys[1]] : row[key];
            }

            if (window.event.ctrlKey) {
                this.ajax_post(window.location.pathname + "/delete", data, function (res) {
                    this.reload();
                });
            } else {
                this.$confirm('确认删除 `' + (name ? name : row[key]) + '` ?').then(function (value) {
                    this.ajax_post(window.location.pathname + "/delete", data, function (res) {
                        this.reload();
                    });
                }.bind(this));
            }
        },
    },
});
<commit_msg>Modified   apps/admin/public/assets/js/app.js<commit_after>Vue.prototype.$axios = axios;
Vue.prototype.$moment = moment;
Vue.prototype.$qs = Qs;
Vue.prototype._ = _;
Vue.prototype.sessionStorage = window.sessionStorage;
Vue.prototype.localStorage = window.localStorage;
Vue.prototype.console = console;

(function () {
    let urlKey = `last_url_query.${document.location.pathname}`;
    window.onbeforeunload = (e) => {
        sessionStorage.setItem(urlKey, document.location.search);
    };

    if (document.location.search !== '' || document.referrer === '') {
        return;
    }
    let last_url_query = sessionStorage.getItem(urlKey);
    window.history.replaceState(null, null, last_url_query === null ? '' : last_url_query);
}());

document.location.query = document.location.search !== '' ? Qs.parse(document.location.search.substr(1)) : {};

//axios.defaults.baseURL = 'http://www.manaphp.com';
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

axios.interceptors.request.use(function (config) {
    if (typeof vm.loading == 'boolean') {
        vm.loading = true;
    }

    config.url += config.url.indexOf('?') === -1 ? '?ajax' : '&ajax';
    return config;
});

axios.interceptors.response.use(function (res) {
        if (typeof vm.loading === 'boolean') {
            vm.loading = false;
        }

        if (!Vue.config.silent) {
            var now = new Date();
            console.warn('[AJAX][%s.%i][%s][%s] %o', now.toLocaleString('en-GB'), now.getMilliseconds(), res.headers['x-response-time'], res.config.url, res);
        }

        if (typeof res.data === 'string') {
            vm.$alert(res.data, '服务器错误', {customClass: 'error-response'});
        }

        if (res.data.code === 0) {
            if (res.data.message) {
                vm.$message({type: 'success', duration: 1000, message: res.data.message});
            } else if (res.config.method !== 'get') {
                vm.$message({type: 'success', duration: 1000, message: '操作成功'});
            }
        }

        for (let name in res.headers) {
            let value = res.headers[name];
            if (value.match(/^https?:\/\//)) {
                console.warn('*'.repeat(32) + ' ' + name + ': ' + value);
            }
        }

        return res;
    },
    function (error) {
        if (typeof vm.loading == 'boolean') {
            vm.loading = false;
        }

        console.log(error);
        if (error.response.status) {
            switch (error.response.status) {
                case 400:
                    alert(error.response.data.message);
                    break;
                case 401:
                    window.location.href = window.login_url;
                    break;
                default:
                    alert(error.response.message || '网络错误，请稍后重试: ' + error.response.status);
                    break;
            }
        } else {
            alert('网络错误，请稍后重试。');
        }
    });

Vue.prototype.ajax_get = function (url, data, success) {
    if (typeof data === 'function') {
        success = data;
        data = null;
    } else if (data) {
        url += (url.indexOf('?') === -1 ? '?' : '&') + Qs.stringify(data);
    }

    if (success && url.match(/\bcache=[12]\b/) && localStorage.getItem('axios.cache.enabled') !== '0') {
        var cache_key = 'axios.cache.' + url;
        let cache_value = sessionStorage.getItem(cache_key);
        if (cache_value) {
            success.bind(this)(JSON.parse(cache_value));
            return;
        }
    }

    return this.$axios.get(url).then(function (res) {
        if (res.data.code === 0) {
            if (success) {
                if (cache_key) {
                    sessionStorage.setItem(cache_key, JSON.stringify(res.data.data));
                }
                success.bind(this)(res.data.data);
            }
        } else if (res.data.message) {
            this.$alert(res.data.message);
        }
        return res;
    }.bind(this));
}

Vue.prototype.ajax_post = function (url, data, success) {
    if (typeof data === 'function') {
        success = data;
        data = {};
    }

    var config = {};
    if (data instanceof FormData) {
        config.headers = {'Content-Type': 'multipart/form-data'};
    }

    return this.$axios.post(url, data, config).then(function (res) {
        if (res.data.code === 0 && success) {
            success.bind(this)(res.data.data);
        }

        if (res.data.message !== '') {
            this.$alert(res.data.message);
        }
        return res
    }.bind(this));
}

Vue.filter('date', function (value, format = 'YYYY-MM-DD HH:mm:ss') {
    return value ? moment(value * 1000).format(format) : '';
})

Vue.filter('json', function (value) {
    return JSON.stringify(typeof value === 'string' ? JSON.parse(value) : value, null, 2);
})

Vue.component('pager', {
    props: ['request', 'response'],
    template: ' <el-pagination background :current-page="Number(response.page)"\n' +
        '                   :page-size="Number(request.size)"\n' +
        '                   :page-sizes="[10,20,25,50,100,500,1000]"\n' +
        '                   @current-change="request.page=$event"\n' +
        '                   @size-change="request.size=$event; request.page=1"\n' +
        '                   :total="response.count" layout="sizes,total, prev, pager, next, jumper"></el-pagination>\n',
    watch: {
        request: {
            handler: function () {
                for (var field in this.request) {
                    if (field === 'page' || field === 'size') {
                        continue;
                    }
                    if (field in this.last_request && this.last_request[field] != this.request[field]) {
                        this.response.page = 1;
                        this.request.page = 1;
                        this.last_request = Object.assign({}, this.request);
                        break;
                    }
                }
            },
            deep: true
        }
    },
    data: function () {
        return {
            last_request: Object.assign({}, this.request)
        }
    }
});

Vue.component('date-picker', {
    props: ['value'],
    template: '<el-date-picker v-model="time" type="daterange" start-placeholder="开始日期"\n ' +
        '                            end-placeholder="结束日期" value-format="yyyy-MM-dd" size="small"\n ' +
        ' :picker-options="pickerOptions" @change="change"' +
        '></el-date-picker>',
    methods: {
        change: function (value) {
            this.$emit('input', value);
        }
    },
    watch: {
        value: function (val) {
            this.time = val;
        }
    },
    data: function () {
        return {
            time: this.value,
            pickerOptions: {
                shortcuts: [
                    {
                        text: '今天',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime());
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '昨天',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24);
                            end.setDate(end.getDate() - 1);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近三天',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近一周',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近一个月',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近三个月',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '最近一年',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '本周',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setDate(start.getDate() - start.getDay() + 1);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '本月',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setDate(1);
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '本季',
                        onClick: function (picker) {
                            var end = new Date();
                            var start = new Date();
                            start.setMonth(parseInt(start.getMonth() / 3) * 3);
                            start.setDate(1);
                            picker.$emit('pick', [start, end]);
                        }
                    }
                ]
            }
        }
    }
});

Vue.component('my-menu', {
    template: `
<el-menu :default-active="active" class="el-menu-vertical-demo" :unique-opened="true">
    <template v-for="group in groups">
        <el-submenu :index="group.group_name">
            <template slot="title">

                {{group.group_name}}
            </template>
            <template v-for="item in group.items ">
                <el-menu-item :index="item.url">
                    <el-link :href="item.url">{{item.item_name}}</el-link>
                </el-menu-item>
            </template>
        </el-submenu>
     </template>
</el-menu>`,
    created() {
        this.ajax_get('/menu/my?cache=2', function (res) {
            this.groups = res;

            let active = location.pathname;
            for (let group of res) {
                for (let item of group.items) {
                    if (item.url === active) {
                        document.title = ' ' + group.group_name + ' - ' + item.item_name;
                        break;
                    }
                }
            }
        })
    },
    data() {
        return {
            active: location.pathname,
            groups: []
        }
    }
});

Vue.component('axios-cache-switcher', {
    template: `

缓存 (√)

缓存 (×)

`,
    data() {
        return {
            enabled: localStorage.getItem('axios.cache.enabled') !== '0'
        }
    }
});
Vue.prototype.format_date = function (value) {
    return value ? this.$moment(value * 1000).format('YYYY-MM-DD HH:mm:ss') : '';
}

Vue.prototype.auto_reload = function () {
    if (this.request && this.response) {
        let qs = this.$qs.parse(document.location.query);
        for (let k in qs) {
            this.$set(this.request, k, qs[k]);
        }

        let vm = this;
        this.reload().then(function () {
            vm.$watch('request', _.debounce(function () {
                vm.reload();
            }, 500), {deep: true});
        });
    }
}

App = Vue.extend({
    methods: {
        reload: function () {
            if (!this.request || !this.response) {
                alert('bad reload');
            }

            var qs = this.$qs.stringify(this.request);
            window.history.replaceState(null, null, qs ? ('?' + qs) : '');
            document.location.query = document.location.search !== '' ? Qs.parse(document.location.search.substr(1)) : {};
            this.response = [];
            return this.$axios.get(document.location.href).then(function (res) {
                if (res.data.code !== 0) {
                    this.$alert(res.data.message);
                } else {
                    this.response = res.data.data;
                }
            }.bind(this));
        },
        fDate: function (row, column, value) {
            return this.format_date(value);
        },

        fEnabled: function (row, column, value) {
            return ['禁用', '启用'][value];
        },
        do_create: function (create) {
            var success = true;
            if (typeof create === 'string') {
                this.$refs[create].validate(valid => success = valid);
            }
            success && this.ajax_post(window.location.pathname + "/create", this.create, function (res) {
                this.createVisible = false;
                this.$refs.create.resetFields();
                this.reload();
            });
        },
        show_edit: function (row, overwrite = {}) {
            this.edit = Object.assign({}, row, overwrite);
            this.editVisible = true;
        },
        do_edit: function () {
            this.ajax_post(window.location.pathname + "/edit", this.edit, function (res) {
                this.editVisible = false;
                this.reload();
            });
        },
        show_detail: function (row, action) {
            this.detailVisible = true;

            var data = {};
            var key = Object.keys(row)[0];
            data[key] = row[key];

            this.ajax_get(window.location.pathname + '/' + (action ? action : "detail"), data, function (res) {
                this.detail = res;
            });
        },
        do_delete: function (row, name = '') {
            var data = {};
            var keys = Object.keys(row);
            var key = keys[0];
            data[key] = row[key];

            if (!name) {
                name = (keys[1] && keys[1].indexOf('_name')) ? row[keys[1]] : row[key];
            }

            if (window.event.ctrlKey) {
                this.ajax_post(window.location.pathname + "/delete", data, function (res) {
                    this.reload();
                });
            } else {
                this.$confirm('确认删除 `' + (name ? name : row[key]) + '` ?').then(function (value) {
                    this.ajax_post(window.location.pathname + "/delete", data, function (res) {
                        this.reload();
                    });
                }.bind(this));
            }
        },
    },
});
<|endoftext|>


<commit_before>function setEditorSize(){
	// Sets the size of the text editor window.
	fillWindow($('#editor'));
}

function getFileExtension(file){
	var parts=file.split('.');
	return parts[parts.length-1];
}

function setSyntaxMode(ext){
	// Loads the syntax mode files and tells the editor
	var filetype = new Array();
	// Todo finish these
    filetype["h"] = "c_cpp";
    filetype["c"] = "c_cpp";
    filetype["clj"] = "clojure";
    filetype["coffee"] = "coffee"; // coffescript can be compiled to javascript
    filetype["coldfusion"] = "cfc";
    filetype["cpp"] = "c_cpp";
    filetype["cs"] = "csharp";
	filetype["css"] = "css";
    filetype["groovy"] = "groovy";
   	filetype["haxe"] = "hx";
	filetype["html"] = "html";
    filetype["java"] = "java";
	filetype["js"] = "javascript";
    filetype["json"] = "json";
   	filetype["latex"] = "latex";
    filetype["lua"] = "lua";
    filetype["markdown"] = "markdown"; // also: .md .markdown .mdown .mdwn
    filetype["ml"] = "ocaml";
    filetype["mli"] = "ocaml";
	filetype["pl"] = "perl";
	filetype["php"] = "php";
	filetype["powershell"] = "ps1";
	filetype["py"] = "python";
	filetype["rb"] = "ruby";
    filetype["scad"] = "scad"; // seems to be something like 3d model files printed with e.g. reprap
    filetype["scala"] = "scala";
    filetype["scss"] = "scss"; // "sassy css"
    filetype["sql"] = "sql";
    filetype["svg"] = "svg";
    filetype["textile"] = "textile"; // related to markdown
	filetype["xml"] = "xml";

	if(filetype[ext]!=null){
		// Then it must be in the array, so load the custom syntax mode
		// Set the syntax mode
		OC.addScript('files_texteditor','aceeditor/mode-'+filetype[ext], function(){
			var SyntaxMode = require("ace/mode/"+filetype[ext]).Mode;
			window.aceEditor.getSession().setMode(new SyntaxMode());
		});
	}
}

function showControls(filename,writeperms){
	// Loads the control bar at the top.
	// Load the new toolbar.
	var editorbarhtml = '

'+filename+'

';
	if(writeperms=="true"){
		editorbarhtml += '<button id="editor_save">'+t('files_texteditor','Save')+'</button>

';
	}
	editorbarhtml += 'Go to line:<input stype="text" id="gotolineval">Search:<input type="text" name="editorsearchval" id="editorsearchval">

<button id="editor_close">'+t('files_texteditor','Close')+'</button>
';
	// Change breadcrumb classes
	$('#controls .last').removeClass('last');
	$('#controls').append(editorbarhtml);
	$('#editorcontrols').fadeIn('slow');
}

function bindControlEvents(){
	$("#editor_save").die('click',doFileSave).live('click',doFileSave);
	$('#editor_close').die('click',hideFileEditor).live('click',hideFileEditor);
	$('#gotolineval').die('keyup', goToLine).live('keyup', goToLine);
	$('#editorsearchval').die('keyup', doSearch).live('keyup', doSearch);
	$('#clearsearchbtn').die('click', resetSearch).live('click', resetSearch);
	$('#nextsearchbtn').die('click', nextSearchResult).live('click', nextSearchResult);
}

// returns true or false if the editor is in view or not
function editorIsShown(){
	// Not working as intended. Always returns true.
	return is_editor_shown;
}

// Moves the editor view to the line number speificed in #gotolineval
function goToLine(){
	// Go to the line specified
	window.aceEditor.gotoLine($('#gotolineval').val());

}

//resets the search
function resetSearch(){
	$('#editorsearchval').val('');
	$('#nextsearchbtn').remove();
	$('#clearsearchbtn').remove();
	window.aceEditor.gotoLine(0);
}

// moves the cursor to the next search resukt
function nextSearchResult(){
	window.aceEditor.findNext();
}
// Performs the initial search
function doSearch(){
	// check if search box empty?
	if($('#editorsearchval').val()==''){
		// Hide clear button
		window.aceEditor.gotoLine(0);
		$('#nextsearchbtn').remove();
		$('#clearsearchbtn').remove();
	} else {
		// New search
		// Reset cursor
		window.aceEditor.gotoLine(0);
		// Do search
		window.aceEditor.find($('#editorsearchval').val(),{
			backwards: false,
			wrap: false,
			caseSensitive: false,
			wholeWord: false,
			regExp: false
		});
		// Show next and clear buttons
		// check if already there
		if($('#nextsearchbtn').length==0){
			var nextbtnhtml = '<button id="nextsearchbtn">Next</button>';
			var clearbtnhtml = '<button id="clearsearchbtn">Clear</button>';
			$('#editorsearchval').after(nextbtnhtml).after(clearbtnhtml);
		}
	}
}

// Tries to save the file.
function doFileSave(){
	if(editorIsShown()){
		// Get file path
		var path = $('#editor').attr('data-dir')+'/'+$('#editor').attr('data-filename');
		// Get original mtime
		var mtime = $('#editor').attr('data-mtime');
		// Show saving spinner
		$("#editor_save").die('click',doFileSave);
		$('#save_result').remove();
		$('#editor_save').text(t('files_texteditor','Saving...'));//after('');
		// Get the data
		var filecontents = window.aceEditor.getSession().getValue();
		// Send the data
		$.post(OC.filePath('files_texteditor','ajax','savefile.php'), { filecontents: filecontents, path: path, mtime: mtime },function(jsondata){
			if(jsondata.status!='success'){
				// Save failed
				$('#editor_save').text(t('files_texteditor','Save'));
				$('#editor_save').after('
Failed to save file
');
				$("#editor_save").live('click',doFileSave);
			} else {
				// Save OK
				// Update mtime
				$('#editor').attr('data-mtime',jsondata.data.mtime);
				$('#editor_save').text(t('files_texteditor','Save'));
				$("#editor_save").live('click',doFileSave);
			}
		},'json');
	}
};

// Gives the editor focus
function giveEditorFocus(){
	window.aceEditor.focus();
};

// Loads the file editor. Accepts two parameters, dir and filename.
function showFileEditor(dir,filename){
	if(!editorIsShown()){
		// Loads the file editor and display it.
		$('#content').append('

');
		var data = $.getJSON(
			OC.filePath('files_texteditor','ajax','loadfile.php'),
			{file:filename,dir:dir},
			function(result){
				if(result.status == 'success'){
					// Save mtime
					$('#editor').attr('data-mtime', result.data.mtime);
					// Initialise the editor
					$('.actions,#file_action_panel').fadeOut('slow');
					$('table').fadeOut('slow', function() {
						// Show the control bar
						showControls(filename,result.data.write);
						// Update document title
						document.title = filename;
						$('#editor').text(result.data.filecontents);
						$('#editor').attr('data-dir', dir);
						$('#editor').attr('data-filename', filename);
						window.aceEditor = ace.edit("editor");
						aceEditor.setShowPrintMargin(false);
						if(result.data.write=='false'){
							aceEditor.setReadOnly(true);
						}
						setEditorSize();
						setSyntaxMode(getFileExtension(filename));
						OC.addScript('files_texteditor','aceeditor/theme-clouds', function(){
							window.aceEditor.setTheme("ace/theme/clouds");
						});
					});
				} else {
					// Failed to get the file.
					alert(result.data.message);
				}
			// End success
			}
		// End ajax
		);
		is_editor_shown = true;
	}
}

// Fades out the editor.
function hideFileEditor(){
	// Fades out editor controls
	$('#editorcontrols').fadeOut('slow',function(){
		$(this).remove();
		$(".crumb:last").addClass('last');
	});
	// Fade out editor
	$('#editor').fadeOut('slow', function(){
		$(this).remove();
		// Reset document title
		document.title = "ownCloud";
		var editorhtml = '

';
		$('table').after(editorhtml);
		$('.actions,#file_access_panel').fadeIn('slow');
		$('table').fadeIn('slow');
	});
	is_editor_shown = false;
}

// Keyboard Shortcuts
var ctrlBtn = false;

// TODO fix detection of ctrl keyup
// returns true if ctrl+s or cmd+s is being pressed
function checkForSaveKeyPress(e){
	if(e.which == 17 || e.which == 91) ctrlBtn=true;
	if(e.which == 83 && ctrlBtn == true) {
	e.preventDefault();
	$('#editor_save').trigger('click');
	return false;

	}
}

// resizes the editor window
$(window).resize(function() {
	setEditorSize();
});
var is_editor_shown = false;
$(document).ready(function(){
	if(typeof FileActions!=='undefined'){
		FileActions.register('text','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('text','Edit');
		FileActions.register('application/xml','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('application/xml','Edit');
	}
	OC.search.customResults.Text=function(row,item){
		var text=item.link.substr(item.link.indexOf('file=')+5);
		var a=row.find('a');
		a.data('file',text);
		a.attr('href','#');
		a.click(function(){
			var file=text.split('/').pop();
			var dir=text.substr(0,text.length-file.length-1);
			showFileEditor(dir,file);
		});
	};
	// Binds the file save and close editor events, and gotoline button
	bindControlEvents();
	$('#editor').remove();
	// Binds the save keyboard shortcut events
	//$(document).unbind('keydown').bind('keydown',checkForSaveKeyPress);
});
<commit_msg>update file extensions in editor<commit_after>function setEditorSize(){
	// Sets the size of the text editor window.
	fillWindow($('#editor'));
}

function getFileExtension(file){
	var parts=file.split('.');
	return parts[parts.length-1];
}

function setSyntaxMode(ext){
	// Loads the syntax mode files and tells the editor
	var filetype = new Array();
	// add file extensions like this: filetype["extension"] = "filetype":
    filetype["h"] = "c_cpp";
    filetype["c"] = "c_cpp";
    filetype["clj"] = "clojure";
    filetype["coffee"] = "coffee"; // coffescript can be compiled to javascript
    filetype["coldfusion"] = "cfc";
    filetype["cpp"] = "c_cpp";
    filetype["cs"] = "csharp";
	filetype["css"] = "css";
    filetype["groovy"] = "groovy";
   	filetype["haxe"] = "hx";
	filetype["html"] = "html";
    filetype["java"] = "java";
	filetype["js"] = "javascript";
    filetype["json"] = "json";
   	filetype["latex"] = "latex";
	filetype["ly"] = "latex";
	filetype["ily"] = "latex";
    filetype["lua"] = "lua";
    filetype["markdown"] = "markdown";
    filetype["md"] = "markdown";
    filetype["mdown"] = "markdown";
    filetype["mdwn"] = "markdown";
	filetype["mkd"] = "markdown";
    filetype["ml"] = "ocaml";
    filetype["mli"] = "ocaml";
	filetype["pl"] = "perl";
	filetype["php"] = "php";
	filetype["powershell"] = "ps1";
	filetype["py"] = "python";
	filetype["rb"] = "ruby";
    filetype["scad"] = "scad"; // seems to be something like 3d model files printed with e.g. reprap
    filetype["scala"] = "scala";
    filetype["scss"] = "scss"; // "sassy css"
    filetype["sql"] = "sql";
    filetype["svg"] = "svg";
    filetype["textile"] = "textile"; // related to markdown
	filetype["xml"] = "xml";

	if(filetype[ext]!=null){
		// Then it must be in the array, so load the custom syntax mode
		// Set the syntax mode
		OC.addScript('files_texteditor','aceeditor/mode-'+filetype[ext], function(){
			var SyntaxMode = require("ace/mode/"+filetype[ext]).Mode;
			window.aceEditor.getSession().setMode(new SyntaxMode());
		});
	}
}

function showControls(filename,writeperms){
	// Loads the control bar at the top.
	// Load the new toolbar.
	var editorbarhtml = '

'+filename+'

';
	if(writeperms=="true"){
		editorbarhtml += '<button id="editor_save">'+t('files_texteditor','Save')+'</button>

';
	}
	editorbarhtml += 'Go to line:<input stype="text" id="gotolineval">Search:<input type="text" name="editorsearchval" id="editorsearchval">

<button id="editor_close">'+t('files_texteditor','Close')+'</button>
';
	// Change breadcrumb classes
	$('#controls .last').removeClass('last');
	$('#controls').append(editorbarhtml);
	$('#editorcontrols').fadeIn('slow');
}

function bindControlEvents(){
	$("#editor_save").die('click',doFileSave).live('click',doFileSave);
	$('#editor_close').die('click',hideFileEditor).live('click',hideFileEditor);
	$('#gotolineval').die('keyup', goToLine).live('keyup', goToLine);
	$('#editorsearchval').die('keyup', doSearch).live('keyup', doSearch);
	$('#clearsearchbtn').die('click', resetSearch).live('click', resetSearch);
	$('#nextsearchbtn').die('click', nextSearchResult).live('click', nextSearchResult);
}

// returns true or false if the editor is in view or not
function editorIsShown(){
	// Not working as intended. Always returns true.
	return is_editor_shown;
}

// Moves the editor view to the line number speificed in #gotolineval
function goToLine(){
	// Go to the line specified
	window.aceEditor.gotoLine($('#gotolineval').val());

}

//resets the search
function resetSearch(){
	$('#editorsearchval').val('');
	$('#nextsearchbtn').remove();
	$('#clearsearchbtn').remove();
	window.aceEditor.gotoLine(0);
}

// moves the cursor to the next search resukt
function nextSearchResult(){
	window.aceEditor.findNext();
}
// Performs the initial search
function doSearch(){
	// check if search box empty?
	if($('#editorsearchval').val()==''){
		// Hide clear button
		window.aceEditor.gotoLine(0);
		$('#nextsearchbtn').remove();
		$('#clearsearchbtn').remove();
	} else {
		// New search
		// Reset cursor
		window.aceEditor.gotoLine(0);
		// Do search
		window.aceEditor.find($('#editorsearchval').val(),{
			backwards: false,
			wrap: false,
			caseSensitive: false,
			wholeWord: false,
			regExp: false
		});
		// Show next and clear buttons
		// check if already there
		if($('#nextsearchbtn').length==0){
			var nextbtnhtml = '<button id="nextsearchbtn">Next</button>';
			var clearbtnhtml = '<button id="clearsearchbtn">Clear</button>';
			$('#editorsearchval').after(nextbtnhtml).after(clearbtnhtml);
		}
	}
}

// Tries to save the file.
function doFileSave(){
	if(editorIsShown()){
		// Get file path
		var path = $('#editor').attr('data-dir')+'/'+$('#editor').attr('data-filename');
		// Get original mtime
		var mtime = $('#editor').attr('data-mtime');
		// Show saving spinner
		$("#editor_save").die('click',doFileSave);
		$('#save_result').remove();
		$('#editor_save').text(t('files_texteditor','Saving...'));
		// Get the data
		var filecontents = window.aceEditor.getSession().getValue();
		// Send the data
		$.post(OC.filePath('files_texteditor','ajax','savefile.php'), { filecontents: filecontents, path: path, mtime: mtime },function(jsondata){
			if(jsondata.status!='success'){
				// Save failed
				$('#editor_save').text(t('files_texteditor','Save'));
				$('#editor_save').after('
Failed to save file
');
				$("#editor_save").live('click',doFileSave);
			} else {
				// Save OK
				// Update mtime
				$('#editor').attr('data-mtime',jsondata.data.mtime);
				$('#editor_save').text(t('files_texteditor','Save'));
				$("#editor_save").live('click',doFileSave);
			}
		},'json');
	}
};

// Gives the editor focus
function giveEditorFocus(){
	window.aceEditor.focus();
};

// Loads the file editor. Accepts two parameters, dir and filename.
function showFileEditor(dir,filename){
	if(!editorIsShown()){
		// Loads the file editor and display it.
		$('#content').append('

');
		var data = $.getJSON(
			OC.filePath('files_texteditor','ajax','loadfile.php'),
			{file:filename,dir:dir},
			function(result){
				if(result.status == 'success'){
					// Save mtime
					$('#editor').attr('data-mtime', result.data.mtime);
					// Initialise the editor
					$('.actions,#file_action_panel').fadeOut('slow');
					$('table').fadeOut('slow', function() {
						// Show the control bar
						showControls(filename,result.data.write);
						// Update document title
						document.title = filename;
						$('#editor').text(result.data.filecontents);
						$('#editor').attr('data-dir', dir);
						$('#editor').attr('data-filename', filename);
						window.aceEditor = ace.edit("editor");
						aceEditor.setShowPrintMargin(false);
						if(result.data.write=='false'){
							aceEditor.setReadOnly(true);
						}
						setEditorSize();
						setSyntaxMode(getFileExtension(filename));
						OC.addScript('files_texteditor','aceeditor/theme-clouds', function(){
							window.aceEditor.setTheme("ace/theme/clouds");
						});
					});
				} else {
					// Failed to get the file.
					alert(result.data.message);
				}
			// End success
			}
		// End ajax
		);
		is_editor_shown = true;
	}
}

// Fades out the editor.
function hideFileEditor(){
	// Fades out editor controls
	$('#editorcontrols').fadeOut('slow',function(){
		$(this).remove();
		$(".crumb:last").addClass('last');
	});
	// Fade out editor
	$('#editor').fadeOut('slow', function(){
		$(this).remove();
		// Reset document title
		document.title = "ownCloud";
		var editorhtml = '

';
		$('table').after(editorhtml);
		$('.actions,#file_access_panel').fadeIn('slow');
		$('table').fadeIn('slow');
	});
	is_editor_shown = false;
}

// Keyboard Shortcuts
var ctrlBtn = false;

// TODO fix detection of ctrl keyup
// returns true if ctrl+s or cmd+s is being pressed
function checkForSaveKeyPress(e){
	if(e.which == 17 || e.which == 91) ctrlBtn=true;
	if(e.which == 83 && ctrlBtn == true) {
	e.preventDefault();
	$('#editor_save').trigger('click');
	return false;

	}
}

// resizes the editor window
$(window).resize(function() {
	setEditorSize();
});
var is_editor_shown = false;
$(document).ready(function(){
	if(typeof FileActions!=='undefined'){
		FileActions.register('text','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('text','Edit');
		FileActions.register('application/xml','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('application/xml','Edit');
	}
	OC.search.customResults.Text=function(row,item){
		var text=item.link.substr(item.link.indexOf('file=')+5);
		var a=row.find('a');
		a.data('file',text);
		a.attr('href','#');
		a.click(function(){
			var file=text.split('/').pop();
			var dir=text.substr(0,text.length-file.length-1);
			showFileEditor(dir,file);
		});
	};
	// Binds the file save and close editor events, and gotoline button
	bindControlEvents();
	$('#editor').remove();
	// Binds the save keyboard shortcut events
	//$(document).unbind('keydown').bind('keydown',checkForSaveKeyPress);
});
<|endoftext|>


<commit_before>function setEditorSize(){
	// Sets the size of the text editor window.
	fillWindow($('#editor'));
}

function getFileExtension(file){
	var parts=file.split('.');
	return parts[parts.length-1];
}

function setSyntaxMode(ext){
	// Loads the syntax mode files and tells the editor
	var filetype = new Array();
	// add file extensions like this: filetype["extension"] = "filetype":
	filetype["h"] = "c_cpp";
	filetype["c"] = "c_cpp";
	filetype["clj"] = "clojure";
	filetype["coffee"] = "coffee"; // coffescript can be compiled to javascript
	filetype["coldfusion"] = "cfc";
	filetype["cpp"] = "c_cpp";
	filetype["cs"] = "csharp";
	filetype["css"] = "css";
	filetype["groovy"] = "groovy";
	filetype["haxe"] = "hx";
	filetype["html"] = "html";
	filetype["java"] = "java";
	filetype["js"] = "javascript";
	filetype["json"] = "json";
	filetype["latex"] = "latex";
	filetype["ly"] = "latex";
	filetype["ily"] = "latex";
	filetype["lua"] = "lua";
	filetype["markdown"] = "markdown";
	filetype["md"] = "markdown";
	filetype["mdown"] = "markdown";
	filetype["mdwn"] = "markdown";
	filetype["mkd"] = "markdown";
	filetype["ml"] = "ocaml";
	filetype["mli"] = "ocaml";
	filetype["pl"] = "perl";
	filetype["php"] = "php";
	filetype["powershell"] = "ps1";
	filetype["py"] = "python";
	filetype["rb"] = "ruby";
	filetype["scad"] = "scad"; // seems to be something like 3d model files printed with e.g. reprap
	filetype["scala"] = "scala";
	filetype["scss"] = "scss"; // "sassy css"
	filetype["sql"] = "sql";
	filetype["svg"] = "svg";
	filetype["textile"] = "textile"; // related to markdown
	filetype["xml"] = "xml";

	if(filetype[ext]!=null){
		// Then it must be in the array, so load the custom syntax mode
		// Set the syntax mode
		OC.addScript('files_texteditor','aceeditor/mode-'+filetype[ext], function(){
			var SyntaxMode = require("ace/mode/"+filetype[ext]).Mode;
			window.aceEditor.getSession().setMode(new SyntaxMode());
		});
	}
}

function showControls(filename,writeperms){
	// Loads the control bar at the top.
	// Load the new toolbar.
	var editorbarhtml = '

'+filename+'

';
	if(writeperms=="true"){
		editorbarhtml += '<button id="editor_save">'+t('files_texteditor','Save')+'</button>

';
	}
	editorbarhtml += 'Go to line:<input stype="text" id="gotolineval">Search:<input type="text" name="editorsearchval" id="editorsearchval">

<button id="editor_close">'+t('files_texteditor','Close')+'</button>
';
	// Change breadcrumb classes
	$('#controls .last').removeClass('last');
	$('#controls').append(editorbarhtml);
	$('#editorcontrols').fadeIn('slow');
}

function bindControlEvents(){
	$("#editor_save").die('click',doFileSave).live('click',doFileSave);
	$('#editor_close').die('click',hideFileEditor).live('click',hideFileEditor);
	$('#gotolineval').die('keyup', goToLine).live('keyup', goToLine);
	$('#editorsearchval').die('keyup', doSearch).live('keyup', doSearch);
	$('#clearsearchbtn').die('click', resetSearch).live('click', resetSearch);
	$('#nextsearchbtn').die('click', nextSearchResult).live('click', nextSearchResult);
}

// returns true or false if the editor is in view or not
function editorIsShown(){
	// Not working as intended. Always returns true.
	return is_editor_shown;
}

// Moves the editor view to the line number speificed in #gotolineval
function goToLine(){
	// Go to the line specified
	window.aceEditor.gotoLine($('#gotolineval').val());

}

//resets the search
function resetSearch(){
	$('#editorsearchval').val('');
	$('#nextsearchbtn').remove();
	$('#clearsearchbtn').remove();
	window.aceEditor.gotoLine(0);
}

// moves the cursor to the next search resukt
function nextSearchResult(){
	window.aceEditor.findNext();
}
// Performs the initial search
function doSearch(){
	// check if search box empty?
	if($('#editorsearchval').val()==''){
		// Hide clear button
		window.aceEditor.gotoLine(0);
		$('#nextsearchbtn').remove();
		$('#clearsearchbtn').remove();
	} else {
		// New search
		// Reset cursor
		window.aceEditor.gotoLine(0);
		// Do search
		window.aceEditor.find($('#editorsearchval').val(),{
			backwards: false,
			wrap: false,
			caseSensitive: false,
			wholeWord: false,
			regExp: false
		});
		// Show next and clear buttons
		// check if already there
		if($('#nextsearchbtn').length==0){
			var nextbtnhtml = '<button id="nextsearchbtn">Next</button>';
			var clearbtnhtml = '<button id="clearsearchbtn">Clear</button>';
			$('#editorsearchval').after(nextbtnhtml).after(clearbtnhtml);
		}
	}
}

// Tries to save the file.
function doFileSave(){
	if(editorIsShown()){
		// Changed contents?
		if($('#editor').attr('data-edited')=='true'){
			// Get file path
			var path = $('#editor').attr('data-dir')+'/'+$('#editor').attr('data-filename');
			// Get original mtime
			var mtime = $('#editor').attr('data-mtime');
			// Show saving spinner
			$("#editor_save").die('click',doFileSave);
			$('#save_result').remove();
			$('#editor_save').text(t('files_texteditor','Saving...'));
			// Get the data
			var filecontents = window.aceEditor.getSession().getValue();
			// Send the data
			$.post(OC.filePath('files_texteditor','ajax','savefile.php'), { filecontents: filecontents, path: path, mtime: mtime },function(jsondata){
				if(jsondata.status!='success'){
					// Save failed
					$('#editor_save').text(t('files_texteditor','Save'));
					$('#editor_save').after('
Failed to save file
');
					$("#editor_save").live('click',doFileSave);
				} else {
					// Save OK
					// Update mtime
					$('#editor').attr('data-mtime',jsondata.data.mtime);
					$('#editor_save').text(t('files_texteditor','Save'));
					$("#editor_save").live('click',doFileSave);
					// Update titles
					$('#editor').attr('data-edited', 'false');
					$('#breadcrumb_file').text($('#editor').attr('data-filename'));
					document.title = $('#editor').attr('data-filename')+' - ownCloud';
				}
			},'json');
		}
	}
};

// Gives the editor focus
function giveEditorFocus(){
	window.aceEditor.focus();
};

// Loads the file editor. Accepts two parameters, dir and filename.
function showFileEditor(dir,filename){
	// Delete any old editors
	$('#editor').remove();
	if(!editorIsShown()){
		// Loads the file editor and display it.
		$('#content').append('

');
		var data = $.getJSON(
			OC.filePath('files_texteditor','ajax','loadfile.php'),
			{file:filename,dir:dir},
			function(result){
				if(result.status == 'success'){
					// Save mtime
					$('#editor').attr('data-mtime', result.data.mtime);
					// Initialise the editor
					$('.actions,#file_action_panel').fadeOut('slow');
					$('table').fadeOut('slow', function() {
						// Show the control bar
						showControls(filename,result.data.write);
						// Update document title
						document.title = filename+' - ownCloud';
						$('#editor').text(result.data.filecontents);
						$('#editor').attr('data-dir', dir);
						$('#editor').attr('data-filename', filename);
						$('#editor').attr('data-edited', 'false');
						window.aceEditor = ace.edit("editor");
						aceEditor.setShowPrintMargin(false);
						aceEditor.getSession().setUseWrapMode(true);
						if(result.data.write=='false'){
							aceEditor.setReadOnly(true);
						}
						setEditorSize();
						setSyntaxMode(getFileExtension(filename));
						OC.addScript('files_texteditor','aceeditor/theme-clouds', function(){
							window.aceEditor.setTheme("ace/theme/clouds");
						});
						window.aceEditor.getSession().on('change', function(){
							if($('#editor').attr('data-edited')!='true'){
								$('#editor').attr('data-edited', 'true');
								$('#breadcrumb_file').text($('#breadcrumb_file').text()+' *');
								document.title = $('#editor').attr('data-filename')+' * - ownCloud';
							}
						});
					});
				} else {
					// Failed to get the file.
					OC.dialogs.alert(result.data.message, t('files_texteditor','An error occurred!'));
				}
			// End success
			}
		// End ajax
		);
		is_editor_shown = true;
	}
}

// Fades out the editor.
function hideFileEditor(){
	if($('#editor').attr('data-edited') == 'true'){
		// Hide, not remove
		$('#editorcontrols').fadeOut('slow',function(){
			// Check if there is a folder in the breadcrumb
			if($('.crumb.ui-droppable').length){
				$('.crumb.ui-droppable:last').addClass('last');
			}
		});
		// Fade out editor
		$('#editor').fadeOut('slow', function(){
			// Reset document title
			document.title = "ownCloud";
			$('.actions,#file_access_panel').fadeIn('slow');
			$('table').fadeIn('slow');
		});
		$('#notification').text(t('files_texteditor','There were unsaved changes, click here to go back'));
		$('#notification').data('reopeneditor',true);
		$('#notification').fadeIn();
		is_editor_shown = false;
	} else {
		// Remove editor
		$('#editorcontrols').fadeOut('slow',function(){
			$(this).remove();
			$(".crumb:last").addClass('last');
		});
		// Fade out editor
		$('#editor').fadeOut('slow', function(){
			$(this).remove();
			// Reset document title
			document.title = "ownCloud";
			$('.actions,#file_access_panel').fadeIn('slow');
			$('table').fadeIn('slow');
		});
		is_editor_shown = false;
	}
}

// Reopens the last document
function reopenEditor(){
	$('.actions,#file_action_panel').fadeOut('slow');
	$('table').fadeOut('slow', function(){
		$('#controls .last').not('#breadcrumb_file').removeClass('last');
		$('#editor').fadeIn('fast');
		$('#editorcontrols').fadeIn('fast', function(){

		});
	});
	is_editor_shown  = true;
}

// resizes the editor window
$(window).resize(function() {
	setEditorSize();
});
var is_editor_shown = false;
$(document).ready(function(){
	if(typeof FileActions!=='undefined'){
		FileActions.register('text','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('text','Edit');
		FileActions.register('application/xml','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('application/xml','Edit');
	}
	OC.search.customResults.Text=function(row,item){
		var text=item.link.substr(item.link.indexOf('file=')+5);
		var a=row.find('a');
		a.data('file',text);
		a.attr('href','#');
		a.click(function(){
			var file=text.split('/').pop();
			var dir=text.substr(0,text.length-file.length-1);
			showFileEditor(dir,file);
		});
	};
	// Binds the file save and close editor events, and gotoline button
	bindControlEvents();
	$('#editor').remove();
	$('#notification').click(function(){
		if($('#notification').data('reopeneditor'))
		{
			reopenEditor();
		}
		$('#notification').fadeOut();
	});
});
<commit_msg>Give editor focus after saving<commit_after>function setEditorSize(){
	// Sets the size of the text editor window.
	fillWindow($('#editor'));
}

function getFileExtension(file){
	var parts=file.split('.');
	return parts[parts.length-1];
}

function setSyntaxMode(ext){
	// Loads the syntax mode files and tells the editor
	var filetype = new Array();
	// add file extensions like this: filetype["extension"] = "filetype":
	filetype["h"] = "c_cpp";
	filetype["c"] = "c_cpp";
	filetype["clj"] = "clojure";
	filetype["coffee"] = "coffee"; // coffescript can be compiled to javascript
	filetype["coldfusion"] = "cfc";
	filetype["cpp"] = "c_cpp";
	filetype["cs"] = "csharp";
	filetype["css"] = "css";
	filetype["groovy"] = "groovy";
	filetype["haxe"] = "hx";
	filetype["html"] = "html";
	filetype["java"] = "java";
	filetype["js"] = "javascript";
	filetype["json"] = "json";
	filetype["latex"] = "latex";
	filetype["ly"] = "latex";
	filetype["ily"] = "latex";
	filetype["lua"] = "lua";
	filetype["markdown"] = "markdown";
	filetype["md"] = "markdown";
	filetype["mdown"] = "markdown";
	filetype["mdwn"] = "markdown";
	filetype["mkd"] = "markdown";
	filetype["ml"] = "ocaml";
	filetype["mli"] = "ocaml";
	filetype["pl"] = "perl";
	filetype["php"] = "php";
	filetype["powershell"] = "ps1";
	filetype["py"] = "python";
	filetype["rb"] = "ruby";
	filetype["scad"] = "scad"; // seems to be something like 3d model files printed with e.g. reprap
	filetype["scala"] = "scala";
	filetype["scss"] = "scss"; // "sassy css"
	filetype["sql"] = "sql";
	filetype["svg"] = "svg";
	filetype["textile"] = "textile"; // related to markdown
	filetype["xml"] = "xml";

	if(filetype[ext]!=null){
		// Then it must be in the array, so load the custom syntax mode
		// Set the syntax mode
		OC.addScript('files_texteditor','aceeditor/mode-'+filetype[ext], function(){
			var SyntaxMode = require("ace/mode/"+filetype[ext]).Mode;
			window.aceEditor.getSession().setMode(new SyntaxMode());
		});
	}
}

function showControls(filename,writeperms){
	// Loads the control bar at the top.
	// Load the new toolbar.
	var editorbarhtml = '

'+filename+'

';
	if(writeperms=="true"){
		editorbarhtml += '<button id="editor_save">'+t('files_texteditor','Save')+'</button>

';
	}
	editorbarhtml += 'Go to line:<input stype="text" id="gotolineval">Search:<input type="text" name="editorsearchval" id="editorsearchval">

<button id="editor_close">'+t('files_texteditor','Close')+'</button>
';
	// Change breadcrumb classes
	$('#controls .last').removeClass('last');
	$('#controls').append(editorbarhtml);
	$('#editorcontrols').fadeIn('slow');
}

function bindControlEvents(){
	$("#editor_save").die('click',doFileSave).live('click',doFileSave);
	$('#editor_close').die('click',hideFileEditor).live('click',hideFileEditor);
	$('#gotolineval').die('keyup', goToLine).live('keyup', goToLine);
	$('#editorsearchval').die('keyup', doSearch).live('keyup', doSearch);
	$('#clearsearchbtn').die('click', resetSearch).live('click', resetSearch);
	$('#nextsearchbtn').die('click', nextSearchResult).live('click', nextSearchResult);
}

// returns true or false if the editor is in view or not
function editorIsShown(){
	// Not working as intended. Always returns true.
	return is_editor_shown;
}

// Moves the editor view to the line number speificed in #gotolineval
function goToLine(){
	// Go to the line specified
	window.aceEditor.gotoLine($('#gotolineval').val());

}

//resets the search
function resetSearch(){
	$('#editorsearchval').val('');
	$('#nextsearchbtn').remove();
	$('#clearsearchbtn').remove();
	window.aceEditor.gotoLine(0);
}

// moves the cursor to the next search resukt
function nextSearchResult(){
	window.aceEditor.findNext();
}
// Performs the initial search
function doSearch(){
	// check if search box empty?
	if($('#editorsearchval').val()==''){
		// Hide clear button
		window.aceEditor.gotoLine(0);
		$('#nextsearchbtn').remove();
		$('#clearsearchbtn').remove();
	} else {
		// New search
		// Reset cursor
		window.aceEditor.gotoLine(0);
		// Do search
		window.aceEditor.find($('#editorsearchval').val(),{
			backwards: false,
			wrap: false,
			caseSensitive: false,
			wholeWord: false,
			regExp: false
		});
		// Show next and clear buttons
		// check if already there
		if($('#nextsearchbtn').length==0){
			var nextbtnhtml = '<button id="nextsearchbtn">Next</button>';
			var clearbtnhtml = '<button id="clearsearchbtn">Clear</button>';
			$('#editorsearchval').after(nextbtnhtml).after(clearbtnhtml);
		}
	}
}

// Tries to save the file.
function doFileSave(){
	if(editorIsShown()){
		// Changed contents?
		if($('#editor').attr('data-edited')=='true'){
			// Get file path
			var path = $('#editor').attr('data-dir')+'/'+$('#editor').attr('data-filename');
			// Get original mtime
			var mtime = $('#editor').attr('data-mtime');
			// Show saving spinner
			$("#editor_save").die('click',doFileSave);
			$('#save_result').remove();
			$('#editor_save').text(t('files_texteditor','Saving...'));
			// Get the data
			var filecontents = window.aceEditor.getSession().getValue();
			// Send the data
			$.post(OC.filePath('files_texteditor','ajax','savefile.php'), { filecontents: filecontents, path: path, mtime: mtime },function(jsondata){
				if(jsondata.status!='success'){
					// Save failed
					$('#editor_save').text(t('files_texteditor','Save'));
					$('#editor_save').after('
Failed to save file
');
					$("#editor_save").live('click',doFileSave);
				} else {
					// Save OK
					// Update mtime
					$('#editor').attr('data-mtime',jsondata.data.mtime);
					$('#editor_save').text(t('files_texteditor','Save'));
					$("#editor_save").live('click',doFileSave);
					// Update titles
					$('#editor').attr('data-edited', 'false');
					$('#breadcrumb_file').text($('#editor').attr('data-filename'));
					document.title = $('#editor').attr('data-filename')+' - ownCloud';
				}
			},'json');
		}
	}
	giveEditorFocus();
};

// Gives the editor focus
function giveEditorFocus(){
	window.aceEditor.focus();
};

// Loads the file editor. Accepts two parameters, dir and filename.
function showFileEditor(dir,filename){
	// Delete any old editors
	$('#editor').remove();
	if(!editorIsShown()){
		// Loads the file editor and display it.
		$('#content').append('

');
		var data = $.getJSON(
			OC.filePath('files_texteditor','ajax','loadfile.php'),
			{file:filename,dir:dir},
			function(result){
				if(result.status == 'success'){
					// Save mtime
					$('#editor').attr('data-mtime', result.data.mtime);
					// Initialise the editor
					$('.actions,#file_action_panel').fadeOut('slow');
					$('table').fadeOut('slow', function() {
						// Show the control bar
						showControls(filename,result.data.write);
						// Update document title
						document.title = filename+' - ownCloud';
						$('#editor').text(result.data.filecontents);
						$('#editor').attr('data-dir', dir);
						$('#editor').attr('data-filename', filename);
						$('#editor').attr('data-edited', 'false');
						window.aceEditor = ace.edit("editor");
						aceEditor.setShowPrintMargin(false);
						aceEditor.getSession().setUseWrapMode(true);
						if(result.data.write=='false'){
							aceEditor.setReadOnly(true);
						}
						setEditorSize();
						setSyntaxMode(getFileExtension(filename));
						OC.addScript('files_texteditor','aceeditor/theme-clouds', function(){
							window.aceEditor.setTheme("ace/theme/clouds");
						});
						window.aceEditor.getSession().on('change', function(){
							if($('#editor').attr('data-edited')!='true'){
								$('#editor').attr('data-edited', 'true');
								$('#breadcrumb_file').text($('#breadcrumb_file').text()+' *');
								document.title = $('#editor').attr('data-filename')+' * - ownCloud';
							}
						});
					});
				} else {
					// Failed to get the file.
					OC.dialogs.alert(result.data.message, t('files_texteditor','An error occurred!'));
				}
			// End success
			}
		// End ajax
		);
		is_editor_shown = true;
	}
}

// Fades out the editor.
function hideFileEditor(){
	if($('#editor').attr('data-edited') == 'true'){
		// Hide, not remove
		$('#editorcontrols').fadeOut('slow',function(){
			// Check if there is a folder in the breadcrumb
			if($('.crumb.ui-droppable').length){
				$('.crumb.ui-droppable:last').addClass('last');
			}
		});
		// Fade out editor
		$('#editor').fadeOut('slow', function(){
			// Reset document title
			document.title = "ownCloud";
			$('.actions,#file_access_panel').fadeIn('slow');
			$('table').fadeIn('slow');
		});
		$('#notification').text(t('files_texteditor','There were unsaved changes, click here to go back'));
		$('#notification').data('reopeneditor',true);
		$('#notification').fadeIn();
		is_editor_shown = false;
	} else {
		// Remove editor
		$('#editorcontrols').fadeOut('slow',function(){
			$(this).remove();
			$(".crumb:last").addClass('last');
		});
		// Fade out editor
		$('#editor').fadeOut('slow', function(){
			$(this).remove();
			// Reset document title
			document.title = "ownCloud";
			$('.actions,#file_access_panel').fadeIn('slow');
			$('table').fadeIn('slow');
		});
		is_editor_shown = false;
	}
}

// Reopens the last document
function reopenEditor(){
	$('.actions,#file_action_panel').fadeOut('slow');
	$('table').fadeOut('slow', function(){
		$('#controls .last').not('#breadcrumb_file').removeClass('last');
		$('#editor').fadeIn('fast');
		$('#editorcontrols').fadeIn('fast', function(){

		});
	});
	is_editor_shown  = true;
}

// resizes the editor window
$(window).resize(function() {
	setEditorSize();
});
var is_editor_shown = false;
$(document).ready(function(){
	if(typeof FileActions!=='undefined'){
		FileActions.register('text','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('text','Edit');
		FileActions.register('application/xml','Edit','',function(filename){
			showFileEditor($('#dir').val(),filename);
		});
		FileActions.setDefault('application/xml','Edit');
	}
	OC.search.customResults.Text=function(row,item){
		var text=item.link.substr(item.link.indexOf('file=')+5);
		var a=row.find('a');
		a.data('file',text);
		a.attr('href','#');
		a.click(function(){
			var file=text.split('/').pop();
			var dir=text.substr(0,text.length-file.length-1);
			showFileEditor(dir,file);
		});
	};
	// Binds the file save and close editor events, and gotoline button
	bindControlEvents();
	$('#editor').remove();
	$('#notification').click(function(){
		if($('#notification').data('reopeneditor'))
		{
			reopenEditor();
		}
		$('#notification').fadeOut();
	});
});
<|endoftext|>


<commit_before>$(document).ready(function(){

	if (typeof FileActions !== 'undefined') {
		// Add versions button to 'files/index.php'
		FileActions.register(
			'file'
			, t('files_versions', 'Versions')
			, OC.PERMISSION_UPDATE
			, function() {
				// Specify icon for hitory button
				return OC.imagePath('core','actions/history');
			}
			,function(filename){
				// Action to perform when clicked
				if (scanFiles.scanning){return;}//workaround to prevent additional http request block scanning feedback

				var file = $('#dir').val()+'/'+filename;
				var createDropDown = true;
				// Check if drop down is already visible for a different file
				if (($('#dropdown').length > 0) ) {
					if ( $('#dropdown').hasClass('drop-versions') && file == $('#dropdown').data('file')) {
						createDropDown = false;
					}
					$('#dropdown').remove();
					$('tr').removeClass('mouseOver');
				}

				if(createDropDown === true) {
					createVersionsDropdown(filename, file);
				}
			}
		);
	}

	$(document).on("click", 'span[class="revertVersion"]', function() {
		var revision = $(this).attr('id');
		var file = $(this).attr('value');
		revertFile(file, revision);
	});

});

function revertFile(file, revision) {

	$.ajax({
		type: 'GET',
		url: OC.linkTo('files_versions', 'ajax/rollbackVersion.php'),
		dataType: 'json',
		data: {file: file, revision: revision},
		async: false,
		success: function(response) {
			if (response.status === 'error') {
				OC.Notification.show( t('files_version', 'Failed to revert {file} to revision {timestamp}.', {file:file, timestamp:formatDate(revision * 1000)}) );
			} else {
				$('#dropdown').hide('blind', function() {
					$('#dropdown').remove();
					$('tr').removeClass('mouseOver');
					// TODO also update the modified time in the web ui
				});
			}
		}
	});

}

function goToVersionPage(url){
	window.location.assign(url);
}

function createVersionsDropdown(filename, files) {

	var start = 0;

	var html = '
';
	html += '
';
	html += '
';
	html += '
';
	html += '
';
	html += '<input type="button" value="'+ t('files_versions', 'More versions...') + '" name="show-more-versions" id="show-more-versions" style="display: none;" />';

	if (filename) {
		$('tr').filterAttr('data-file',filename).addClass('mouseOver');
		$(html).appendTo($('tr').filterAttr('data-file',filename).find('td.filename'));
	} else {
		$(html).appendTo($('thead .share'));
	}

	getVersions(start);
	start = start + 5;

	$("#show-more-versions").click(function() {
		//get more versions
		getVersions(start);
		start = start + 5;
	});

	function getVersions(start) {
		$.ajax({
			type: 'GET',
			url: OC.filePath('files_versions', 'ajax', 'getVersions.php'),
			dataType: 'json',
			data: {source: files, start: start},
			async: false,
			success: function(result) {
				var versions = result.data.versions;
				if (result.data.endReached === true) {
					document.getElementById("show-more-versions").style.display="none";
				} else {
					document.getElementById("show-more-versions").style.display="block";
				}
				if (versions) {
					$.each(versions, function(index, row) {
						addVersion(row);
					});
				} else {
					$('
'+ t('files_versions', 'No other versions available') + '
').appendTo('#dropdown');
				}
				$('#found_versions').change(function() {
					var revision = parseInt($(this).val());
					revertFile(files, revision);
				});
			}
		});
	}

	function addVersion( revision ) {
		title = formatDate(revision.version*1000);
		name ='' + revision.humanReadableTimestamp + '';

		path = OC.filePath('files_versions', '', 'download.php');

		download ='';
		download+='';
		download+=name;
		download+='';

		revert='';
		revert+=''+t('files_versions', 'Restore')+'';

		var version=$('
');
		version.attr('value', revision.version);
		version.html(download + revert);

		version.appendTo('#found_versions');
	}

	$('tr').filterAttr('data-file',filename).addClass('mouseOver');
	$('#dropdown').show('blind');

}

$(this).click(
	function(event) {
	if ($('#dropdown').has(event.target).length === 0 && $('#dropdown').hasClass('drop-versions')) {
		$('#dropdown').hide('blind', function() {
			$('#dropdown').remove();
			$('tr').removeClass('mouseOver');
		});
	}

	}
);
<commit_msg>remove unused code; use jquery<commit_after>$(document).ready(function(){

	if (typeof FileActions !== 'undefined') {
		// Add versions button to 'files/index.php'
		FileActions.register(
			'file'
			, t('files_versions', 'Versions')
			, OC.PERMISSION_UPDATE
			, function() {
				// Specify icon for hitory button
				return OC.imagePath('core','actions/history');
			}
			,function(filename){
				// Action to perform when clicked
				if (scanFiles.scanning){return;}//workaround to prevent additional http request block scanning feedback

				var file = $('#dir').val()+'/'+filename;
				var createDropDown = true;
				// Check if drop down is already visible for a different file
				if (($('#dropdown').length > 0) ) {
					if ( $('#dropdown').hasClass('drop-versions') && file == $('#dropdown').data('file')) {
						createDropDown = false;
					}
					$('#dropdown').remove();
					$('tr').removeClass('mouseOver');
				}

				if(createDropDown === true) {
					createVersionsDropdown(filename, file);
				}
			}
		);
	}

	$(document).on("click", 'span[class="revertVersion"]', function() {
		var revision = $(this).attr('id');
		var file = $(this).attr('value');
		revertFile(file, revision);
	});

});

function revertFile(file, revision) {

	$.ajax({
		type: 'GET',
		url: OC.linkTo('files_versions', 'ajax/rollbackVersion.php'),
		dataType: 'json',
		data: {file: file, revision: revision},
		async: false,
		success: function(response) {
			if (response.status === 'error') {
				OC.Notification.show( t('files_version', 'Failed to revert {file} to revision {timestamp}.', {file:file, timestamp:formatDate(revision * 1000)}) );
			} else {
				$('#dropdown').hide('blind', function() {
					$('#dropdown').remove();
					$('tr').removeClass('mouseOver');
					// TODO also update the modified time in the web ui
				});
			}
		}
	});

}

function goToVersionPage(url){
	window.location.assign(url);
}

function createVersionsDropdown(filename, files) {

	var start = 0;

	var html = '
';
	html += '
';
	html += '
';
	html += '
';
	html += '
';
	html += '<input type="button" value="'+ t('files_versions', 'More versions...') + '" name="show-more-versions" id="show-more-versions" style="display: none;" />';

	if (filename) {
		$('tr').filterAttr('data-file',filename).addClass('mouseOver');
		$(html).appendTo($('tr').filterAttr('data-file',filename).find('td.filename'));
	} else {
		$(html).appendTo($('thead .share'));
	}

	getVersions(start);
	start = start + 5;

	$("#show-more-versions").click(function() {
		//get more versions
		getVersions(start);
		start = start + 5;
	});

	function getVersions(start) {
		$.ajax({
			type: 'GET',
			url: OC.filePath('files_versions', 'ajax', 'getVersions.php'),
			dataType: 'json',
			data: {source: files, start: start},
			async: false,
			success: function(result) {
				var versions = result.data.versions;
				if (result.data.endReached === true) {
					$("#show-more-versions").css("display", "none");
				} else {
					$("#show-more-versions").css("display", "block");
				}
				if (versions) {
					$.each(versions, function(index, row) {
						addVersion(row);
					});
				} else {
					$('
'+ t('files_versions', 'No other versions available') + '
').appendTo('#dropdown');
				}
				$('#found_versions').change(function() {
					var revision = parseInt($(this).val());
					revertFile(files, revision);
				});
			}
		});
	}

	function addVersion( revision ) {
		title = formatDate(revision.version*1000);
		name ='' + revision.humanReadableTimestamp + '';

		path = OC.filePath('files_versions', '', 'download.php');

		download ='';
		download+='';
		download+=name;
		download+='';

		revert='';
		revert+=''+t('files_versions', 'Restore')+'';

		var version=$('
');
		version.attr('value', revision.version);
		version.html(download + revert);

		version.appendTo('#found_versions');
	}

	$('tr').filterAttr('data-file',filename).addClass('mouseOver');
	$('#dropdown').show('blind');

}

$(this).click(
	function(event) {
	if ($('#dropdown').has(event.target).length === 0 && $('#dropdown').hasClass('drop-versions')) {
		$('#dropdown').hide('blind', function() {
			$('#dropdown').remove();
			$('tr').removeClass('mouseOver');
		});
	}

	}
);
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

if (!window['Gaia'])
  var Gaia = {};

(function() {

  var lastDragPosition = -1;
  var isKeyDown = false;

  Gaia.TaskManager = {

    _isActive: false,

    get isActive() {
      return this._isActive;
    },

    set isActive(value) {
      this._isActive = value;

      var runningApps = Gaia.AppManager.runningApps;

      if (value) {
        this.element.classList.add('active');
        for (var i = 0; i < runningApps.length; i++) {
          var classList = runningApps[i].window.classList;
          classList.add('active');
          classList.add('noTransition');
        }
      } else {
        this.element.classList.remove('active');
        for (var i = 0; i < runningApps.length; i++) {
          var classList = runningApps[i].window.classList;
          classList.remove('active');
          classList.remove('noTransition');
        }
      }
    },

    get element() {
      delete this.element;

      return this.element = document.getElementById('taskManager');
    },

    get listElement() {
      delete this.listElement;

      return this.listElement = this.element.getElementsByTagName('ul')[0];
    },

    init: function() {
      window.addEventListener('keypress', this);
      window.addEventListener('keydown', this);
      window.addEventListener('keyup', this);

      var listElement = this.listElement;
      listElement.addEventListener('touchstart', this);
      listElement.addEventListener('touchmove', this);
      listElement.addEventListener('touchend', this);
    },

    handleEvent: function(evt) {
      switch (evt.type) {
        case 'keydown':
          if (evt.keyCode !== evt.DOM_VK_ESCAPE || isKeyDown)
            return;

          isKeyDown = true;

          if (this.isActive)
            this.isActive = false;
          else {
            setTimeout(function(self) {
              if (isKeyDown)
                self.isActive = true;
            }, 1000, this);
          }
          break;
        case 'keyup':
          if (evt.keyCode !== evt.DOM_VK_ESCAPE)
            return;

          isKeyDown = false;
          break;
        case 'touchstart':
          var touches = evt.changedTouches;

          if (touches.length !== 1)
            return;

          var touch = touches[0];
          lastDragPosition = touch.pageX;
          break;
        case 'touchmove':
          if (lastDragPosition === -1)
            return;

          var touches = evt.changedTouches;

          if (touches.length !== 1)
            return;

          var touch = touches[0];
          this.listElement.scrollLeft -= touch.pageX - lastDragPosition;
          lastDragPosition = touch.pageX;
          break;
        case 'touchend':
          lastDragPosition = -1;
          break;
        default:
          throw new Error('Unhandled event in TaskManager');
          break;
      }
    },

    add: function(id) {
      var item = document.createElement('li');
      item.id = 'task_' + id;
      item.setAttribute('style', 'background: -moz-element(#app_' + id + ') no-repeat');
      this.listElement.appendChild(item);
      return item;
    },

    remove: function(id) {
      var listElement = this.listElement;
      var item = listElement.getElementById('task_' + id);
      listElement.removeChild(item);
    }

  };

  window.addEventListener('load', function(evt) {
    Gaia.TaskManager.init();
  });

})();<commit_msg>Cleaned up unused code.<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

if (!window['Gaia'])
  var Gaia = {};

(function() {

  var lastDragPosition = -1;
  var isKeyDown = false;

  Gaia.TaskManager = {

    _isActive: false,

    get isActive() {
      return this._isActive;
    },

    set isActive(value) {
      this._isActive = value;

      var runningApps = Gaia.AppManager.runningApps;

      if (value) {
        this.element.classList.add('active');
        for (var i = 0; i < runningApps.length; i++) {
          var classList = runningApps[i].window.classList;
          classList.add('active');
          classList.add('noTransition');
        }
      } else {
        this.element.classList.remove('active');
        for (var i = 0; i < runningApps.length; i++) {
          var classList = runningApps[i].window.classList;
          classList.remove('active');
          classList.remove('noTransition');
        }
      }
    },

    get element() {
      delete this.element;

      return this.element = document.getElementById('taskManager');
    },

    get listElement() {
      delete this.listElement;

      return this.listElement = this.element.getElementsByTagName('ul')[0];
    },

    init: function() {
      window.addEventListener('keydown', this);
      window.addEventListener('keyup', this);

      var listElement = this.listElement;
      listElement.addEventListener('touchstart', this);
      listElement.addEventListener('touchmove', this);
      listElement.addEventListener('touchend', this);
    },

    handleEvent: function(evt) {
      switch (evt.type) {
        case 'keydown':
          if (evt.keyCode !== evt.DOM_VK_ESCAPE || isKeyDown)
            return;

          isKeyDown = true;

          if (this.isActive)
            this.isActive = false;
          else {
            setTimeout(function(self) {
              if (isKeyDown)
                self.isActive = true;
            }, 1000, this);
          }
          break;
        case 'keyup':
          if (evt.keyCode !== evt.DOM_VK_ESCAPE)
            return;

          isKeyDown = false;
          break;
        case 'keypress':
          // if (evt.keyCode !== evt.DOM_VK_ESCAPE)
          //             return;
          //
          //           this.isActive = !this.isActive;
          //           evt.preventDefault();
          break;
        case 'touchstart':
          var touches = evt.changedTouches;

          if (touches.length !== 1)
            return;

          var touch = touches[0];
          lastDragPosition = touch.pageX;
          break;
        case 'touchmove':
          if (lastDragPosition === -1)
            return;

          var touches = evt.changedTouches;

          if (touches.length !== 1)
            return;

          var touch = touches[0];
          this.listElement.scrollLeft -= touch.pageX - lastDragPosition;
          lastDragPosition = touch.pageX;
          break;
        case 'touchend':
          lastDragPosition = -1;
          break;
        default:
          throw new Error('Unhandled event in TaskManager');
          break;
      }
    },

    add: function(id) {
      var item = document.createElement('li');
      item.id = 'task_' + id;
      item.setAttribute('style', 'background: -moz-element(#app_' + id + ') no-repeat');
      this.listElement.appendChild(item);
      return item;
    },

    remove: function(id) {
      var listElement = this.listElement;
      var item = listElement.getElementById('task_' + id);
      listElement.removeChild(item);
    }

  };

  window.addEventListener('load', function(evt) {
    Gaia.TaskManager.init();
  });

})();<|endoftext|>


<commit_before><commit_msg>fix(ccAutoRefreshFn): incorrect http cancellation classification<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed create new ruleset on edit ruleset page<commit_after><|endoftext|>


<commit_before>define([
  'jquery',
  'angular',
  '../core_module',
],
function ($, angular, coreModule) {
  'use strict';

  var editViewMap = {
    'settings':    { src: 'public/app/features/dashboard/partials/settings.html'},
    'annotations': { src: 'public/app/features/annotations/partials/editor.html'},
    'templating':  { src: 'public/app/features/templating/partials/editor.html'},
    'history':     { html: '<gf-dashboard-history dashboard="dashboard"></gf-dashboard-history>'},
    'timepicker':  { src: 'public/app/features/dashboard/timepicker/dropdown.html' },
    'import':      { html: '<dash-import></dash-import>' }
  };

  coreModule.default.directive('dashEditorView', function($compile, $location, $rootScope) {
    return {
      restrict: 'A',
      link: function(scope, elem) {
        var editorScope;
        var lastEditView;

        function hideEditorPane(hideToShowOtherView) {
          if (editorScope) {
            editorScope.dismiss(hideToShowOtherView);
            scope.appEvent('dash-editor-hidden');
          }
        }

        function showEditorPane(evt, options) {
          if (options.editview) {
            options.src = editViewMap[options.editview].src;
            options.html = editViewMap[options.editview].html;
          }

          if (lastEditView === options.editview) {
            hideEditorPane(false);
            return;
          }

          hideEditorPane(true);

          lastEditView = options.editview;
          editorScope = options.scope ? options.scope.$new() : scope.$new();

          editorScope.dismiss = function(hideToShowOtherView) {
            editorScope.$destroy();
            lastEditView = null;
            editorScope = null;
            elem.removeClass('dash-edit-view--open');

            if (!hideToShowOtherView) {
              setTimeout(function() {
                elem.empty();
              }, 250);
            }

            if (options.editview) {
              var urlParams = $location.search();
              if (options.editview === urlParams.editview) {
                delete urlParams.editview;
                $location.search(urlParams);
              }
            }
          };

          if (options.editview === 'import') {
            var modalScope = $rootScope.$new();
            modalScope.$on("$destroy", function() {
              editorScope.dismiss();
            });

            $rootScope.appEvent('show-modal', {
              templateHtml: '<dash-import></dash-import>',
              scope: modalScope,
              backdrop: 'static'
            });

            return;
          }

          var view;
          if (options.src)  {
            view = angular.element(document.createElement('div'));
            view.html('

');
          } else {
            view = angular.element(document.createElement('div'));
            view.addClass('tabbed-view');
            view.html(options.html);
          }

          $compile(view)(editorScope);

          setTimeout(function() {
            elem.empty();
            elem.append(view);
            setTimeout(function() {
              elem.addClass('dash-edit-view--open');
            }, 10);
          }, 10);
        }

        scope.$watch("dashboardViewState.state.editview", function(newValue, oldValue) {
          if (newValue) {
            showEditorPane(null, {editview: newValue});
          } else if (oldValue) {
            if (lastEditView === oldValue) {
              hideEditorPane();
            }
          }
        });

        scope.$on("$destroy", hideEditorPane);
        scope.onAppEvent('hide-dash-editor', function() {
          hideEditorPane(false);
        });

        scope.onAppEvent('show-dash-editor', showEditorPane);
      }
    };
  });
});
<commit_msg>ux: close edit views when opening panel in edit mode<commit_after>define([
  'jquery',
  'angular',
  '../core_module',
],
function ($, angular, coreModule) {
  'use strict';

  var editViewMap = {
    'settings':    { src: 'public/app/features/dashboard/partials/settings.html'},
    'annotations': { src: 'public/app/features/annotations/partials/editor.html'},
    'templating':  { src: 'public/app/features/templating/partials/editor.html'},
    'history':     { html: '<gf-dashboard-history dashboard="dashboard"></gf-dashboard-history>'},
    'timepicker':  { src: 'public/app/features/dashboard/timepicker/dropdown.html' },
    'import':      { html: '<dash-import></dash-import>' }
  };

  coreModule.default.directive('dashEditorView', function($compile, $location, $rootScope) {
    return {
      restrict: 'A',
      link: function(scope, elem) {
        var editorScope;
        var lastEditView;

        function hideEditorPane(hideToShowOtherView) {
          if (editorScope) {
            editorScope.dismiss(hideToShowOtherView);
            scope.appEvent('dash-editor-hidden');
          }
        }

        function showEditorPane(evt, options) {
          if (options.editview) {
            options.src = editViewMap[options.editview].src;
            options.html = editViewMap[options.editview].html;
          }

          if (lastEditView === options.editview) {
            hideEditorPane(false);
            return;
          }

          hideEditorPane(true);

          lastEditView = options.editview;
          editorScope = options.scope ? options.scope.$new() : scope.$new();

          editorScope.dismiss = function(hideToShowOtherView) {
            editorScope.$destroy();
            lastEditView = null;
            editorScope = null;
            elem.removeClass('dash-edit-view--open');

            if (!hideToShowOtherView) {
              setTimeout(function() {
                elem.empty();
              }, 250);
            }

            if (options.editview) {
              var urlParams = $location.search();
              if (options.editview === urlParams.editview) {
                delete urlParams.editview;
                $location.search(urlParams);
              }
            }
          };

          if (options.editview === 'import') {
            var modalScope = $rootScope.$new();
            modalScope.$on("$destroy", function() {
              editorScope.dismiss();
            });

            $rootScope.appEvent('show-modal', {
              templateHtml: '<dash-import></dash-import>',
              scope: modalScope,
              backdrop: 'static'
            });

            return;
          }

          var view;
          if (options.src)  {
            view = angular.element(document.createElement('div'));
            view.html('

');
          } else {
            view = angular.element(document.createElement('div'));
            view.addClass('tabbed-view');
            view.html(options.html);
          }

          $compile(view)(editorScope);

          setTimeout(function() {
            elem.empty();
            elem.append(view);
            setTimeout(function() {
              elem.addClass('dash-edit-view--open');
            }, 10);
          }, 10);
        }

        scope.$watch("dashboardViewState.state.editview", function(newValue, oldValue) {
          if (newValue) {
            showEditorPane(null, {editview: newValue});
          } else if (oldValue) {
            if (lastEditView === oldValue) {
              hideEditorPane();
            }
          }
        });

        scope.$on("$destroy", hideEditorPane);

        scope.onAppEvent('hide-dash-editor', function() {
          hideEditorPane(false);
        });

        scope.onAppEvent('show-dash-editor', showEditorPane);

        scope.onAppEvent('panel-fullscreen-enter', function() {
          scope.appEvent('hide-dash-editor');
        });
      }
    };
  });
});

<|endoftext|>


<commit_before><commit_msg>mark priority queue properties as private<commit_after><|endoftext|>


<commit_before><commit_msg>Allow to export css rules from code manager<commit_after><|endoftext|>