skin.js 18.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
define("op/skin", ['openPlatform', 'lz-string', 'jquery'], function (op, LZ) {
    var common = require("components/common");
    var template = '\
{@each data as skin}\
<section class="skin-card" data-id="${skin.id}">\
    {@if !skin.previewImg}\
        <img src="/mobilemode/images/e9/default-pic2.png" class="default">\
    {@else}\
        <img src="${skin.previewImg}">\
    {@/if}\
    <div class="skin-detail">\
        <h4>${skin.name}</h4>\
        <p>系统默认样式</p>\
    </div>\
</section>\
{@/each}';

    var pluginTmp = '\
{@each data as category}\
<li data-category="${category.categoryName}">\
    {@each category.items as plugin}\
    <i class="icon-plugin-default icon-plugin-${plugin.id} disabled" data-id="${plugin.id}" data-tip="${plugin.text}"></i>\
    {@/each}\
</li>\
{@/each}';

    var searchTmp = '\
<div class="plug-search-panel">\
    <div class="plug-search">\
        <div>\
            <label>'+SystemEnv.getHtmlNoteName(5013)+':</label>\
            <div class="search">\
                <input value="" />\
                <a href="javascript:;" class="clean-icon"><i class="iconfont icon-del fa-normal-1x"></i></a>\
                <a href="javascript:;" class="search-icon"><i class="iconfont icon-search fa-normal-1x"></i></a>\
            </div>\
        </div>\
    </div>\
    <div class="plug-classify">\
        <div>\
            <label>'+SystemEnv.getHtmlNoteName(5008)+':</label>\
            <div class="categories">\
                <span data-classify="-1" class="selected">'+SystemEnv.getHtmlNoteName(3407)+'</span> \
                {@each categories as category}\
                <span data-classify="${category.name}">${category.text}</span>\
                {@/each}\
            </div>\
        </div>\
    </div>\
</div>';//5013插件,5008类型,3407全部

    var cls_prefix = ".wev-comp-";
    var def = {
        page: {
            html: {
                code: ""
            },
            css: { 
                external: [
                    "/mobilemode/mobile/dist/css/mobile.css",
                    "/mobilemode/admin/src/openPlatform/modules/skin/clsPicker.css",
                    "/mobilemode/admin/dep/highlight/theme/monokai-sublime.css",
                    "/mobilemode/admin/dep/perfect-scrollbar/css/perfect-scrollbar.min.css"
                ],
                code: "",
                inbody: true
            }, 
            javascript: {
                external: [
                    "/mobilemode/admin/dep/highlight/highlight.js",
                    "/mobilemode/admin/dep/perfect-scrollbar/perfect-scrollbar.min.js",
                    "/mobilemode/mobile/dist/js/lib/require/require.min_wev8.js",
                    "/mobilemode/mobile/dist/js/main_demo/main.js",
                    "/mobilemode/admin/dep/fabric/fabric.min.js",
                    "/mobilemode/admin/src/openPlatform/modules/skin/clsPicker.js"
                ],
                code: ""
            }
        },
        layout: {
            editor: {
                readonly: ["javascript", "html"],
                max: "css",
                onresize: maximization
            }
        }
    };
    var editor = {
        cssEditor: null,
        getEditor: function () {
            if (!this.cssEditor) {
                this.cssEditor = op.getEditor("css");
            }
            
            return this.cssEditor;
        },
        init: function(skinid) { // 初始化编辑器的皮肤样式代码
            return common.api("skin", {
                action: 'css', 
                data: { id: skinid },
                type: "get"
            }).then(function(res) {
                var data = res.data;
                var cfg = $.extend(true, {}, def);

                cfg.page.css.code = data.css;
                cfg.ecVersion = data.ecVersion;
                op.initEditor(op.RUN_MODE, cfg);
            });
        },
        renderRTPlug: function(pId) { // 渲染运行时插件效果
            var t = this;

            return op.callOpApi("getPluginDemoHtml", { id: pId }, function(res) {
                var data = res.data;
                var cfg = $.extend(true, {}, def);

                cfg.page.css.code = t.getEditor().getValue();
                cfg.page.html.code = data.html;
                cfg.page.javascript.code = data.script;
                cfg.layout.editor.initializes = "javascript html";
                op.initEditor(op.RUN_MODE, cfg);
            });
        },
        unbindEvents: function() {
            this.getEditor().selection.off("changeCursor", this.handler);
            return this;
        },
        bindEvents: function() {
            this.getEditor().selection.on("changeCursor", this.handler);
        },
        handler: function(e, u) {
            var lines = u.doc.$lines;
            var row = u.lead.row, lineText;

            while(row >= 0) {
                lineText = lines[row];

                if (~lineText.indexOf(cls_prefix) || ~lineText.indexOf("(#")) {
                    var type = ~lineText.indexOf("(#") ? lineText.replace(/.*\(#(.*?)\).*/g, "$1") : 
                        lineText.replace(/(.*?)\.wev-comp-([^ \[:{}]*)[#\[{:\. ].*/g, "$2");
                    var cursorPosition = u.getCursor();

                    pluginList.selectPlugIcon(type, function() {
                        // 选择插件之后, 编辑器会重新初始化, 导致光标位置被重置, 需要手动移动到之前光标的坐标
                        u.moveCursorToPosition(cursorPosition);
                    });
                    break;
                }
                row--;
            }
        },
        insertPlugCssCode: function(plugin) { // 在编辑器中定位或者插入插件类名
            var cssEditor = this.getEditor();
            var prefixEnter = "\n\n"; // 前置换行
            var clsName = cls_prefix + plugin.id;
            var lastRow = cssEditor.getLastVisibleRow();
            var isexist = cssEditor.find("(#" + plugin.id + ")") || cssEditor.find(clsName); // 编辑器中是否已经存在该类型的插件样式,并移动到该行
            var tmpl = "/* " + plugin.text + "(#" + plugin.id +") */\n::focus";

            if(isexist) return;

            // 如果最后一行有代码则换两行, 最后一行没有代码则换一行, 为第一行且没有代码则换行
            if(!cssEditor.session.getLine(lastRow)) { // 获取最后一行的长度
                prefixEnter = lastRow !== 0 ? "\n" : "";
            }

            tmpl = prefixEnter + tmpl;

            cssEditor.navigateFileEnd();
            cssEditor.insertSnippet(tmpl);
        }
    };

    var plugins = {};
    var pluginList = (function(){
        var $plugList =  $("#skin-panel").find(".plugin-list");
        var currId = "";
        var components = null, categories = null, plugs = [];
        var events = {
            "click": function(e, triggerHanlder) {
                var $icon = $(this),
                    $list = $(e.delegateTarget);
                
                currId = $icon.data("id");
                $list.find(".active").removeClass("active");
                $icon.addClass("active").removeClass("disabled");
                // 初始化插件运行时效果      
                editor.unbindEvents();
                editor.renderRTPlug(currId).then(function() {
                    // 开启了自动运行 需要关闭 否则插入插件类名后会再次刷新一次(即插件Demo会刷新两次)
                    var isAutoRun = op.getAutoRun();
                    
                    op.setAutoRun(false);

                    if(!triggerHanlder) {
                        editor.insertPlugCssCode(plugins[currId]);
                    } else {
                        triggerHanlder();
                    }

                    editor.bindEvents();
                    isAutoRun && op.setAutoRun(true);
                });
            },
            "mouseenter": function() {
                var $icon = $(this);
    
                require(["modal"], function(modal) {
                    modal.tips($icon.data("tip"), $icon, "right");
                });
            },
            "mouseleave": function() {
                require(["modal"], function(modal) {
                    modal.closeAll('tips'); // 鼠标离开关闭tips
                });
            }
        };
        var getComponents = function() {
            if(components) return $.Deferred().resolve(components);

            return common.api("designer", {
                action: "getComponents",
                type: "get",
                force: false
            }, function(res) {
                components = res;
            });
        };
        var render = function() {
            // 插件列表初始化
            getComponents().then(function(components) {
                var html = juicer(pluginTmp, components);
                
                $plugList.find("ul").html(html).on(events, "i");
                // 将插件列表数组转化为对象
                components.data.forEach(function (category) {
                    // 初始化plugins 对象
                    category.items.forEach(function (item) {
                        plugins[item.id] = item;
                        plugs.push(item.id);
                    });
                });
            });
        };

        render();
        return {
            initIcons: function() {
                var cssCode = editor.getEditor().getValue();
                
                this.resetIcons();

                $plugList.find("ul i").addClass("disabled").removeClass("active");

                Object.keys(plugins).forEach(function(pId) {
                    var isdisabled = !~cssCode.indexOf(cls_prefix + pId) && !~cssCode.indexOf("(#" + pId + ")");

                    $plugList.find(".icon-"+pId).toggleClass("disabled", isdisabled);
                });
            },
            selectPlugIcon: function(type, callback) {
                if (currId && currId == type) return;
                if (!~plugs.indexOf(type)) return; // 不存在该插件

                $plugList.find(".icon-"+type).trigger("click", callback);
            },
            resetCurrId: function() {
                currId = "";
            },
            getCategories: function() {
                if(categories) return $.Deferred().resolve(categories);

                return getComponents().then(function(coms) {
                    categories = coms.data.map(function (category) {
                        return {
                            name: category.categoryName,
                            text: category.categoryText,
                            items: category.items
                        };
                    });
                    return categories;
                });
            },
            resetIcons: function () {
                var $panel = $(".plug-search-panel");

                if (!$panel.length) return;

                $panel.find("[data-classify='-1']").trigger("click");
                $panel.find(".clean-icon").trigger("click");
            }
        };
    })();

    return {
        list: {
            initialized: false,
            activeDataId: "",
            module: "skin",
            action: "list",
            template: template,
            afterRender: function ($panel, skinlist, isreload) {
                if (isreload) return;

                var that = this;

                $panel.on("click", ".skin-card", function (e) {
                    var $card = $(this), skinid = $card.data("id");

			        window.location.hash = op_changeURLHash('refId', skinid);
                    // 用于保存皮肤
                    that.activeDataId = skinid;
                    // 选中皮肤卡片
                    $card.addClass("active").siblings().removeClass("active");
                    // 弹出插件列表
                    $("#main-container").addClass("skin-editing");
                    // 初始化开放平台编辑器
                    pluginList.resetCurrId();
                    editor.unbindEvents().bindEvents();
                    editor.init(skinid).then(function() {
                        // 初始化所有插件图标
                        pluginList.initIcons();
                    });

                    op.toggleSaveIcon(true);
                });

                $panel.find(".plugin-search-icon").on("click", function (e) {
                    var $searchPanel = $(".plug-search-panel");
                    var $icon = $(this);

                    e.stopPropagation();
                    if ($searchPanel.length) return $searchPanel.toggle();

                    pluginList.getCategories().then(function(categories) {
                        var tmp = juicer(searchTmp, {categories: categories});
                        
                        $searchPanel = $(tmp);
                        $(document.body).append($searchPanel);

                        var name = "", type = -1;
                        var filter = function() {
                            var $list = $(".plugin-list");
                            var regex = new RegExp(name.split("").join(".*"), "g");
                            var cts = categories.filter(function(category) {
                                return category.name == type || type == -1;
                            });

                            $list.find("[data-category]").hide();
                            cts.forEach(function(ct, index) {
                                var $category = $list.find("[data-category=" + ct.name + "]");
                                
                                $category.show().find("i").hide();
                                ct.items.forEach(function (item) {
                                    if(~item.text.toLowerCase().indexOf(name) || item.text_py.toLowerCase().match(regex)) {
                                        $category.find("[data-id=" + item.id + "]").show();
                                    }
                                });
                            });
                        };
                        // 插件搜索
                        $searchPanel.find("input").on("input", function() {
                            var value = $(this).val();

                            $(this).attr("value", value);
                            name = value.toLowerCase();
                            filter();
                        });
                        // 清空搜索框
                        $searchPanel.find(".clean-icon").on("click", function() {
                            $searchPanel.find("input").val("").trigger("input").focus();
                        });
                        // 插件类型选择
                        $searchPanel.find(".categories").on("click", "span", function() {
                            var $classify = $(this);

                            if($classify.hasClass("selected")) return;
                               
                            $classify.addClass("selected").siblings(".selected").removeClass("selected");
                            type = $classify.data("classify");
                            filter();
                        });
                        // 定位
                        var ioffset = $icon.offset();
                        var left, top;
                        
                        left = ioffset.left + $icon.outerWidth();
                        top = ioffset.top + $icon.outerHeight() / 2 - $searchPanel.outerHeight() / 2;
                        
                        $searchPanel.css({
                            left: left,
                            top: top
                        }).on("click", function(e) {
                            e.stopPropagation();
                        });

                        $("body").on("click.searchPanel", function () {
                            $searchPanel.hide();
                        });
                    });
                });
            }
        },
        action: {
            onSave: function(id, settings) {
                settings.action = "saveCss";
                settings.data = {
                    id: id,
                    css: LZ.compress(editor.getEditor().getValue())
                };
                
                return common.api("skin", settings);
            },
            onBeforeChange: function () {
                $("#main-container").removeClass("skin-editing");
            },
            onSearch: function (val, $panel) {
                var $cards = $panel.find(".skin-card").show();

                if (!val) return;

                $cards.each(function () {
                    var $card = $(this);
                    var name = $card.find("h4").text().toLowerCase();
                    var ismatch = ~name.indexOf(val);
                    
                    $card.toggle(!!ismatch);
                });
            }
        },
        creator: {
            initialized: false,
            $panel: null,
            init: function() {
                var $panel = this.$panel;

                $panel.find("[name=name]").on("input", function() {
                    $panel.find(".errMsg").hide();
                });

                $panel.find("[name=previewImg]").on("change", function(e) {
                    var $input = $(this),
                        $img = $input.siblings("img");
                    var files = this.files;

                    if(!files.length) return;

                    var reader = new FileReader();

                    reader.readAsDataURL(files[0]);
                    reader.onload = function(e) {
                        var dataUrl = e.target.result;

                        $img.attr("src", dataUrl);
                    };
                });
            },
            onOpen: function() {
                return this.$panel.find("input[name=name]").select().focus();
            },
            onClose: function() {
                var $panel = this.$panel;

                $panel.find("input[name=name]").val("");
                $panel.find("img").removeAttr("src");
                $panel.find("errMsg").hide();
            },
            onOk: function() {
                var $panel = this.$panel;
                var name = $panel.find("input[name=name]").val().trim();

                if(!name) return $panel.find(".errMsg").show() && false;

                var thrunk = $.Deferred();
                
                require(['UUID'], function() {
                    var skinid = new UUID().toString();

                    common.api("skin", {
                        action: "save",
                        data: {
                            id: skinid,
                            name: name,
                            previewImg: $panel.find("img").attr("src")
                        }
                    }).then(function() {
                        thrunk.resolve({ data: { id: skinid } });
                    });
                });

                return thrunk;
            }
        }
    };
});