clsPicker.js 15.9 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
!(function () {
    var def = {
        angle: 60, // 线条角度
        selector: "",
        container: "",
        position: "bottom right",
        skew: [2, 0], // 容器 x, y轴的偏移量 倍数关系 x: 默认偏移容器宽度的一半 即width / 2, y: 默认不偏移 在selector的顶部或者底部
        lineYSkew: 10, // 线条y轴偏移量 
        type: "" // 插件类型
    };

    function clsPicker(opts) {
        if (!opts.selector) return;

        this.pos = opts.position;
        this.opts = $.extend({}, def, opts);

        opts = this.opts;

        opts.skew = opts.skew || [2, 1];
        opts.skew[0] = opts.skew[0] || 2;
        opts.skew[1] = opts.skew[1] || 0;

        this.$el = $("<section class='clspicker'></section>");
        this.canvas = document.createElement("canvas");

        this.$el.append(this.canvas);

        var $selector = $(opts.selector);
        var isvisible = $selector.css("display") !== "none" && ($selector.height() || $selector.width());

        if ( !isvisible ) return;

        this.$selector = $(opts.selector);
        this.$container = $(opts.container || opts.selector);

        this.canvas.height = opts.height || 200;

        this.fabric = new fabric.Canvas(this.canvas, { selection: false });

        this.$container.append(this.$el).css("position", "relative");

        this.textbox = clsBox(opts.selector, opts.text);

        this.$el.append(this.textbox);
        this.render();
    }

    clsPicker.golalSetting = function (settings) {
        $.extend(def, settings);
    };

    clsPicker.prototype = {
        render: function () {
            var that = this;

            this.setPos();
            this.position();
            
            setTimeout(function () { // 避免容器长度不准
                that.renderTextbox(that.makeLine());
            });
        },
        setPos: function () {
            var position = this.pos;

            if (position) return (this.pos = position.split(" "));

            var $container = this.$container,
                $selector = this.$selector;
            var soffset = $selector.offset(),
                coffset = $container.offset();
            var skew = this.opts.skew;

            position = this.opts.position.split(" ");

            if ($container.height() / 2 > (soffset.top + $selector.height() / 2 - coffset.top)) {
                position[0] = "top";
            }

            if ($container.width() / 2 < (soffset.left + $selector.width() / skew[0] - coffset.left)) {
                position[1] = "left";
            }

            return (this.pos = position);
        },
        position: function () {
            var position = this.pos;
            var $el = this.$el,
                $selector = this.$selector,
                $container = this.$container;
            var soffset = $selector.offset(),
                coffset = $container.offset();
            var skew = this.opts.skew;
            var pos = {
                left: "inherit",
                right: "inherit",
                top: "inherit",
                bottom: "inherit"
            };

            var yskew = skew[1] && $selector.height() / skew[1];
            if (position[0] == "bottom") {
                pos.top = soffset.top - coffset.top + $selector.height() - yskew;
            } else {
                pos.bottom = $container.height() - soffset.top + coffset.top - yskew;
            }

            if (position[1] == "right") {
                pos.left = soffset.left + $selector.width() / skew[0];
            } else {
                pos.right = $container.width() - soffset.left - $selector.width() / skew[0];
            }

            this.$el.css(pos);
            return this;
        },
        renderTextbox: function (endpoint) {
            var INHERIT = "inherit";
            var position = this.pos,
                pos = {
                    top: INHERIT,
                    right: INHERIT,
                    bottom: INHERIT,
                    left: INHERIT
                };
            var $textbox = $(this.textbox);


            if (position[0] == "bottom") {
                pos.top = endpoint[1] - $textbox.height() / 2;
            } else {
                pos.bottom = this.$el.height() - endpoint[1] - $textbox.height() / 2;
            }

            if (position[1] == "right") {
                pos.left = endpoint[0];
            } else {
                pos.right = this.$el.width() - endpoint[0];
            }

            $textbox.css(pos);
        },
        makeLine: function () {
            var position = this.pos;
            var radian = this.opts.angle * Math.PI / 180;
            var $el = this.$el,
                $selector = this.$selector,
                $container = this.$container;
            var soffset = $selector.offset(),
                coffset = $container.offset();
            var lineYSkew = this.opts.lineYSkew,
                point1 = [], point2 = [];
            var x1, y1, x2, y, yskew;
            var isbottom = position[0] == "bottom";

            if (isbottom) {
                point1 = [0, 0];
                y1 = coffset.top + $container.height() - soffset.top - $selector.height() + lineYSkew;
            } else { // "top"
                point1 = [0, $el.height()];
                y = soffset.top - coffset.top + lineYSkew;
                y1 = $el.height() - y;
            }

            yskew = isbottom ? y1 : y;

            if (position[1] == "right") {
                x1 = parseInt(yskew / Math.tan(radian)) + 0.5;
                x2 = x1 + 20;
            } else { // "left"
                point1[0] = $el.width();
                x1 = $el.width() - parseInt(yskew / Math.tan(radian)) - 0.5;
                x2 = x1 - 20;
            }

            point1.push(x1);
            point1.push(y1);
            point2 = [x1, y1, x2, y1];

            this.fabric.add(
                Line(point1),
                Line(point2)
            );

            return [x2, y1];
        }
    };

    function Line(coords) {
        return new fabric.Line(coords, {
            stroke: 'red',
            selectable: false
        });
    }

    function clsBox(selector, text) {
        var $textbox = $("<div class='clsbox'></div>");
        var $selector = $(selector);
        var content = "<span style='color:#df7bdd;'>" + $selector[0].nodeName.toLowerCase() + "</span>" + (text || selector);

        $textbox.html(content).on({
            mouseenter: function (e) {
                clsBox.inspecter.toggle(selector, true);
            },
            mouseleave: function (e) {
                clsBox.inspecter.toggle(selector, false);
            },
            click: function (e) {
                clsBox.cssRule.render(selector, $textbox)
            }
        });

        return $textbox[0];
    }

    // 元素审查
    clsBox.inspecters = {};
    clsBox.inspecter = {
        render: function (el) {
            var $el = $(el);
            var offset = $el.offset();
            var contentbox = "<div class='clsbox-inspecter content-box'></div>",
                $paddingbox = $("<div class='clsbox-inspecter padding-box'>" + contentbox + "</div>");

            $marginbox = $("<div class='clsbox-inspecter margin-box'></div>");

            $marginbox.append($paddingbox);
            $(document.body).append($marginbox);

            var ml = parseInt($el.css("margin-left")),
                mt = parseInt($el.css("margin-top")),
                pl = parseInt($el.css("padding-left")),
                pt = parseInt($el.css("padding-top"));

            $marginbox.css({
                left: offset.left - (ml < 0 ? ml + pl : ml),
                top: offset.top - (mt < 0 ? mt + pt : mt),
                width: $el[0].offsetWidth,
                height: $el[0].offsetHeight,
                padding: $el.css("margin"),
            });
            $paddingbox.css({
                padding: $el.css("padding"),
            });
            
            clsBox.inspecters[el] = $marginbox;
        },
        toggle: function (el, isshow) {
            var $marginbox = clsBox.inspecters[el];

            if (!$marginbox) return this.render(el);

            $marginbox.toggle(!!isshow);
        }
    };

    // 样式规则依赖
    clsBox.cssRules = {};
    clsBox.cssRule = {
        render: function (selector, $clsbox) {
            var that = this;
            var $rulebox = clsBox.cssRules[selector];

            if ($rulebox) return $rulebox.show();

            var $closebtn = $("<div class='rule-close'>&#215</div>");

            $rulebox = $("<div class='clsbox-rule'><div class='rule-box'><div class='rule-container'></div></div></div>");

            $(document.body).append($rulebox);

            var rules = this.getRule($(selector)[0]);
            var styles = [], classes = [], lens = [];

            rules = rules.filter(function (r, i) {
                if (r.indexOf("*") === 0) return false; // 过滤 * {}的样式

                var style = r.match(/(?= )([^{};]*?)(?=;)/g);
                
                if (!style) return false; // 过滤空样式

                styles.push.apply(styles, style);
                classes.push.apply(classes, r.match(/([^{};]+?)(?={)/g));
                lens.push(style.length + (lens[lens.length - 1] || 0));
                return true;
            });

            rules = rules.reduce(function (prev, r) {
                return prev + r.trim();
            }, "");

            rules = rules.replace(/({|;)/g, "$1&nbsp;&nbsp;"); // 对{和;进行换行处理
            rules = rules.replace(/&nbsp;&nbsp; }/g, "}").replace(/(}(?!$))/g, "$1</br>"); // 对非最后一个的}进行换行处理

            var $ruleContainer = $rulebox.find(".rule-container");

            $rulebox.on("click", function (e) {
                if(e.target != this) return;
                that.hide(selector);
            });

            $ruleContainer.on("click", function (e) {
                var iscloseBtn = $(e.target).hasClass("rule-close");

                iscloseBtn && that.hide(selector);
                e.stopPropagation();
            }).html(rules).on("click.transfer", ".transfer-icon", function (e) {
                var index = $ruleContainer.find(".transfer-icon").index(this),
                    len = index + 1, clsIndex;
                var _sort = function (a, b) { return a - b; };

                lens.push(len);
                clsIndex = lens.sort(_sort).indexOf(len);
                lens.splice(clsIndex, 1);
                that.transferToEditor(classes[clsIndex], styles[index]);
            });
            
            var fmtHtml = "";

            hljs.configure({
                useBR: true,
                language: "css"
            });
            hljs.highlightBlock($ruleContainer[0]);
            fmtHtml = $ruleContainer.html();
            fmtHtml = fmtHtml.replace(/(&nbsp;&nbsp;[\s\S]*?;)/g, "<div class='cls-property'>$1<span class='transfer-icon'><span></div>");
            $ruleContainer.html(fmtHtml);

            clsBox.cssRules[selector] = $rulebox;

            var $box = $rulebox.find(".rule-box");

            $box.show().css("position", "relative");
            Ps.initialize($box[0], {
                wheelSpeed: 1,
                suppressScrollX: true,
                wheelPropagation: false,
                swipePropagation: false,
                theme: 'lighter'
            });
            $ruleContainer[0].offsetHeight = $box.height();
            $ruleContainer.append($closebtn);
        },
        hide: function (el) {
            var $rulebox = clsBox.cssRules[el];

            $rulebox.hide();
        },
        transferToEditor: function (clsName, style) {
            if (!parent.codeEditor) return;

            var editor = parent.codeEditor.getEditor("css");
            var matchLen = editor.findAll(clsName + "{"), tstyle;
        
            style = style.trim();
            tstyle = "  " + style + ";";
            property = style.split(" ")[0];

            var lines = editor.session.doc.$lines,
                row = editor.selection.lead.row,
                len = lines.length - 1, 
                i = 0, lineText;
            /**
             * none 当前插件不存在该类
             * exsit 当前类型插件下存在该类
             * other 非当前类插件下存在该类
             */
            var clsStatus = "none";

            var handler = editor.selection._eventRegistry.changeCursor[1];
            
            handler && editor.selection.off("changeCursor", handler);

            if (matchLen) {
                while (i < matchLen) {
                    var rang = editor.find(clsName + "{");
                    var regx = /\(#(.*?)\)/g;
                    var j = rang.start.row, result;

                    while (j > 0) {
                        result = lines[j].match(regx);

                        if (result) {
                            clsStatus = result[0].replace(regx, "$1") === def.type ? "exsit" : "other";
                            break;
                        }
                        j--;
                    }

                    if (clsStatus === "exsit") break;
                    i++;
                }
            }

            handler && editor.selection.on("changeCursor", handler);

            if (clsStatus !== "none") { // 如果存在类样式
                while (row <= len) {
                    lineText = lines[row] || "";
                    if (~lineText.indexOf(style)) { // 如果该样式已存在则定位到该行
                        editor.find(style);
                        break;
                    } else if (lineText.trim().indexOf(property) === 0) { // 如果该样式经过改动 则选中样式属性并定位到该行
                        editor.find(lineText);
                        break;
                    }

                    if(lineText.match(/{.*?}/g)) { // '{'和'}'在同一行 如: .xxx{color:#fff}
                        var r = lineText.replace("}", "\n" + tstyle + "\n}");
                        
                        editor.find(lineText);
                        editor.replace(r);
                        editor.clearSelection();
                        editor.moveCursorTo(row + 1, tstyle.length);
                        editor.focus();
                        break;
                    }

                    if (~lineText.indexOf("}")) { // 如果该样式不存在, 则生成到样式类的最后一行
                        editor.gotoLine(row + 1, 0);
                        editor.insertSnippet(tstyle + "::focus\n");
                        break;
                    }
                    row++;
                }
                return;
            }

            var isPlugExist = editor.find("(#" + def.type + ")");
            var clsTmpl = "\n" + clsName + "{\n" + tstyle + "::focus\n}\n";
            var _insertToLastLine = function () {
                editor.navigateFileEnd();
                editor.insertSnippet(clsTmpl);
            };

            // 如果不存在该插件的样式"(#type)", 生成到编辑器的最后一行
            if (!isPlugExist) return _insertToLastLine();

            row = editor.selection.lead.row; //重新获取行
            while (++row <= len) {
                if (lines[row].match(/\(#.*?\)/g)) {
                    editor.gotoLine(row, lines[row].length);
                    editor.insertSnippet(clsTmpl);
                    return;
                }
            }

            _insertToLastLine();
        },
        getRule: function (el) {
            var sheets = document.styleSheets, o = [];

            el.matches = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector;

            for (var i in sheets) {
                var rules = sheets[i].rules || sheets[i].cssRules;

                for (var r in rules) {
                    if (el.matches(rules[r].selectorText)) {
                        o.push(rules[r].cssText);
                    }
                }
            }

            return o;
        }
    };

    window.clsPicker = clsPicker;
}());