<commit_before>/*
 * grunt-phpunit
 * https://github.com/SaschaGalley/grunt-phpunit
 *
 * Copyright (c) 2013 Sascha Galley
 * http://xash.at
 * Licensed under the MIT license.
 */
'use strict';

// External libs.
var path = require('path');
var exec = require('child_process').exec;

exports.init = function(grunt) {

    var exports  = {},
        defaults = {
            // Default options
            bin: 'phpcs',
            extensions: false,
            ignore: false,
            severity: false,
            standard: false,
            verbose: false,
            reportFile: false,
            report: 'full',
            maxBuffer: 200*1024,
            ignoreExitCode: false
        },
        cmd    = null,
        done   = null,
        config = {};

    /**
     * Builds phpunit command
     *
     * @return string
     */
    var buildCommand = function(dir) {

        var cmd = path.normalize(config.bin);

        if (grunt.option('extensions') || config.extensions) {
            // A comma separated list of file extensions to check
            cmd += ' --extensions=' + config.extensions;
        }

        if (grunt.option('ignore') || config.ignore) {
            // A comma separated list of patterns to ignore files and directories.
            cmd += ' --ignore=' + config.ignore;
        }

        if (grunt.option('severity') || config.severity) {
            // The minimum severity required to display an error or warning
            cmd += ' --severity=' + config.severity;
        }

        if (grunt.option('warning-severity') || config.warningSeverity) {
            // The minimum severity required to display an error or warning
            cmd += ' --warning-severity=' + config.warningSeverity;
        }

        if (grunt.option('standard') || config.standard) {
            // Define the code sniffer standard.
            cmd += ' --standard=' + config.standard;
        }

        if (grunt.option('report-file') || config.reportFile) {
            // Define the file to write the report to.
            cmd += ' --report-file=' + config.reportFile;
        }

        if (grunt.option('report') || config.report) {
            // Define the style of the report.
            cmd += ' --report=' + config.report;
        }

        if (grunt.option('verbose') || config.verbose === true) {
            // Output more verbose information.
            cmd += ' -v';
        }
        return cmd;
    };

    /**
     * Setup task before running it
     *
     * @param Object runner
     */
    exports.setup = function(runner) {

        var dir = path.normalize(runner.data.dir);
        config  = runner.options(defaults);
        cmd     = buildCommand(dir) + ' ' + dir;

        grunt.log.writeln('Starting phpcs (target: ' + runner.target.cyan + ') in ' + dir.cyan);
        grunt.verbose.writeln('Exec: ' + cmd);

        done    = runner.async();
    };

    /**
     * Runs phpunit command with options
     *
     */
    exports.run = function() {
        var cmdOptions = {
            maxBuffer: config.maxBuffer
        };

        exec(cmd, cmdOptions, function(err, stdout, stderr) {

            if (stdout) {
                grunt.log.write(stdout);
            }

            if (err) {
                if (! config.ignoreExitCode) {
                    grunt.fatal(err);
                }
            }
            done();
        });
    };

    return exports;
};
<commit_msg>Fix support for CLI options<commit_after>/*
 * grunt-phpunit
 * https://github.com/SaschaGalley/grunt-phpunit
 *
 * Copyright (c) 2013 Sascha Galley
 * http://xash.at
 * Licensed under the MIT license.
 */
'use strict';

// External libs.
var path = require('path');
var exec = require('child_process').exec;

exports.init = function(grunt) {

    var exports  = {},
        defaults = {
            // Default options
            bin: 'phpcs',
            extensions: false,
            ignore: false,
            standard: false,
            verbose: false,
            reportFile: false,
            report: 'full',
            maxBuffer: 200*1024,
            ignoreExitCode: false
        },
        cliOptions = {
            errorSeverity: grunt.option('error-severity'),
            extensions: grunt.option('extensions'),
            ignore: grunt.option('ignore'),
            report: grunt.option('report'),
            reportFile: grunt.option('report-file'),
            severity: grunt.option('severity'),
            standard: grunt.option('standard'),
            warningSeverity: grunt.option('warning-severity'),
            verbose: grunt.option('verbose')
        },
        cmd    = null,
        done   = null,
        config = {};

    /**
     * Builds phpunit command
     *
     * @return string
     */
    var buildCommand = function(dir) {

        var cmd = path.normalize(config.bin);

        if (config.errorSeverity !== undefined) {
            // The minimum severity required to display an error or warning
            cmd += ' --error-severity=' + config.errorSeverity;
        }

        if (config.extensions) {
            // A comma separated list of file extensions to check
            cmd += ' --extensions=' + config.extensions;
        }

        if (config.ignore) {
            // A comma separated list of patterns to ignore files and directories.
            cmd += ' --ignore=' + config.ignore;
        }

        if (config.severity !== undefined) {
            // The minimum severity required to display an error or warning
            cmd += ' --severity=' + config.severity;
        }

        if (config.warningSeverity !== undefined) {
            // The minimum severity required to display an error or warning
            cmd += ' --warning-severity=' + config.warningSeverity;
        }

        if (config.standard) {
            // Define the code sniffer standard.
            cmd += ' --standard=' + config.standard;
        }

        if (config.reportFile) {
            // Define the file to write the report to.
            cmd += ' --report-file=' + config.reportFile;
        }

        if (config.report) {
            // Define the style of the report.
            cmd += ' --report=' + config.report;
        }

        if (config.verbose === true) {
            // Output more verbose information.
            cmd += ' -v';
        }
        return cmd;
    };

    /**
     * Setup task before running it
     *
     * @param Object runner
     */
    exports.setup = function(runner) {

        var dir = path.normalize(runner.data.dir),
            attr;
        config  = runner.options(defaults);

        for (attr in cliOptions) {
            if (cliOptions[attr] !== undefined) {
                config[attr] = cliOptions[attr];
            }
        }

        cmd     = buildCommand(dir) + ' ' + dir;

        grunt.log.writeln('Starting phpcs (target: ' + runner.target.cyan + ') in ' + dir.cyan);
        grunt.verbose.writeln('Exec: ' + cmd);

        done    = runner.async();
    };

    /**
     * Runs phpunit command with options
     *
     */
    exports.run = function() {
        var cmdOptions = {
            maxBuffer: config.maxBuffer
        };

        exec(cmd, cmdOptions, function(err, stdout, stderr) {

            if (stdout) {
                grunt.log.write(stdout);
            }

            if (err) {
                if (! config.ignoreExitCode) {
                    grunt.fatal(err);
                }
            }
            done();
        });
    };

    return exports;
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

	var wd = require('wd');
	var Batch = require('batch');
	var request = require('request');
	var SauceTunnel = require('sauce-tunnel');
	var mkdirp = require('mkdirp');
	var path = require('path');
	var fs = require('fs');
	var testResultsPath = path.join(__dirname, '../test/results');
	var UA = require('../lib/UA');

	grunt.registerMultiTask('saucelabs', 'Perform tests on Sauce', function() {
		var gruntDone = this.async();
		var nameSuffix = process.env.TRAVIS_BUILD_NUMBER ? "-travis-build:" + process.env.TRAVIS_BUILD_NUMBER : ':' + (new Date()).toUTCString();
		var tunnelId = 'SauceTunnel-' + nameSuffix;

		var options = this.options({
			name: 'grunt-test' + nameSuffix,
			build: null,
			username: process.env.SAUCE_USER_NAME,
			key: process.env.SAUCE_API_KEY,
			browsers: [],
			url: {},
			concurrency: 3,
			tags: [],
			video: true,
			screenshots: true,
			cibuild: false
		});

		var batch = new Batch();
		batch.concurrency(options.concurrency);

		var tunnel = new SauceTunnel(options.username, options.key, tunnelId, true);

		// Create a new job to pass into the Batch runner, returns a function
		function newTestJob(url, urlName, conf) {
			return function testJob(done) {

				// initialize remote connection to Sauce Labs
				var sauceConnectPort = 4445;
				var browser = wd.remote("127.0.0.1", sauceConnectPort, options.username, options.key);

				browser.init(conf, function() {

					browser.get(url, function(err) {
						var refreshed = false;
						var retries = 0;

						if (err) {
							console.log(err);
							return done(err);
						}

						// Wait until results are available
						(function waitOnResults() {

							browser.eval('window.global_test_results', function(err, data) {

								if (!data) {
									if (!refreshed) {
										browser.refresh(function(err) {
											refreshed = true;
											setTimeout(waitOnResults, 1500);
										});
										return;
									} else {
										if (retries > 10) {
											browser.quit();
											process.nextTick(function() {
												done(null, { status: 'failed', uaString: data ? data.uaString || '??' : '??', id: browser.sessionID, name: conf.browserName, version: conf.version, failed: '??', total: '??'});
											});
											return;
										}
										setTimeout(function() { retries++; waitOnResults(); }, 1500);
										return;
									}
								}

								browser.quit();
								process.nextTick(function() {
									if (!options.cibuild) {
										done(null, { status: 'ok' });
									} else {
										done(null, {
											status: data && (data.failed > 0) ? 'failed' : 'passed',
											id: browser.sessionID,
											name: conf.browserName,
											version: conf.version,
											failed: data.failed || '??',
											total: data.total,
											uaString: data.uaString
										});
									}
								});

								request({
									method: "PUT",
									uri: ["https://", options.username, ":", options.key, "@saucelabs.com/rest", "/v1/", options.username, "/jobs/", browser.sessionID].join(''),
									headers: {'Content-Type': 'application/json'},
									body: JSON.stringify({
										'custom-data': { custom: data },
										'passed': !data.failed
									})
								}, function (err, res, body) {
									if (!options.cibuild) {
										mkdirp(testResultsPath, function(err) {
											if (err) {
												throw err;
											}

											var file = path.join(testResultsPath, 'results.json')

											fs.readFile(file, function(err, filedata) {
												if (err) {
													// If ENOENT, continue as
													// writeFile will create
													// it
													if (err.code !== 'ENOENT') {
														throw err;
													}
												}

												var testResults  = filedata ? JSON.parse(filedata) : {};
												var browserName = UA.normalizeName(conf.browserName) || conf.browserName;

												if (!testResults[browserName]) {
													testResults[browserName] = {};
												}

												if (!testResults[browserName][conf.version]) {
													testResults[browserName][conf.version]	= {};
												}

												testResults[browserName][conf.version][urlName] = {
													passed: data.passed,
													failed: data.failed,
													failingSuites: Object.keys(data.failingSuites),
													testedSuites: data.testedSuites
												};

												fs.writeFile(file, JSON.stringify(testResults, null, 2), function(err) {
													if (err) {
														console.log(err);
														throw err;
													}
												});
											});
										});
									}
								});
							});
						}());
					});
				});
			};
		}

		grunt.log.writeln('Opening tunnel to Sauce Labs');
		tunnel.start(function(status) {

			grunt.log.writeln("Tunnel Started");
			if (status !== true)  {
				gruntDone(status);
			}

			options.browsers.forEach(function(conf) {
				conf['name'] = options.name;
				conf['record-video'] = options.video;
				conf['record-screenshots'] = options.screenshots;
				conf['tunnel-identifier'] = tunnelId;
				if (options.tags) conf['tags'] = options.tags;
				if (options.build) conf['build'] = options.build;

				Object.keys(options.urls).forEach(function(urlName) {
					var url = options.urls[urlName];
					batch.push(newTestJob(url, urlName, conf));
				});
			});

			grunt.log.writeln("Starting test jobs");
			batch.end(function(err, status) {
				console.log("Jobs complete");
				tunnel.stop(function() {
					if (!options.cibuild) {
						gruntDone(null, true);
						return;
					}

					var failed = false;
					console.log("Failed tests:")
					status.forEach(function(state) {
						if (state.status === 'failed') {
							failed = true;
							console.log("--");
							console.log("Useragent string: ", state.uaString);
							console.log(state.name + "/" + state.version, ':', state.failed + '/' + state.total + ' failed - ' + 'https://saucelabs.com/tests/' + state.id);
						}
					});

					if (!failed) {
						console.log("No failed tests");
					}

					gruntDone(!failed, failed);
				});
			});
		});
	});
};
<commit_msg>Extract function<commit_after>'use strict';

module.exports = function(grunt) {

	var wd = require('wd');
	var Batch = require('batch');
	var request = require('request');
	var SauceTunnel = require('sauce-tunnel');
	var mkdirp = require('mkdirp');
	var path = require('path');
	var fs = require('fs');
	var testResultsPath = path.join(__dirname, '../test/results');
	var UA = require('../lib/UA');

	grunt.registerMultiTask('saucelabs', 'Perform tests on Sauce', function() {
		var gruntDone = this.async();
		var nameSuffix = process.env.TRAVIS_BUILD_NUMBER ? "-travis-build:" + process.env.TRAVIS_BUILD_NUMBER : ':' + (new Date()).toUTCString();
		var tunnelId = 'SauceTunnel-' + nameSuffix;

		var options = this.options({
			name: 'grunt-test' + nameSuffix,
			build: null,
			username: process.env.SAUCE_USER_NAME,
			key: process.env.SAUCE_API_KEY,
			browsers: [],
			url: {},
			concurrency: 3,
			tags: [],
			video: true,
			screenshots: true,
			cibuild: false
		});

		var batch = new Batch();
		batch.concurrency(options.concurrency);

		var tunnel = new SauceTunnel(options.username, options.key, tunnelId, true);

		function getBrowserConnection() {
			var sauceConnectPort = 4445;
			return wd.remote("127.0.0.1", sauceConnectPort, options.username, options.key);
		}

		// Create a new job to pass into the Batch runner, returns a function
		function newTestJob(url, urlName, conf) {
			return function testJob(done) {

				var browser = getBrowserConnection();

				browser.init(conf, function() {

					browser.get(url, function(err) {
						var refreshed = false;
						var retries = 0;

						if (err) {
							console.log(err);
							return done(err);
						}

						// Wait until results are available
						(function waitOnResults() {

							browser.eval('window.global_test_results', function(err, data) {

								if (!data) {
									if (!refreshed) {
										browser.refresh(function(err) {
											refreshed = true;
											setTimeout(waitOnResults, 1500);
										});
										return;
									} else {
										if (retries > 10) {
											browser.quit();
											process.nextTick(function() {
												done(null, { status: 'failed', uaString: data ? data.uaString || '??' : '??', id: browser.sessionID, name: conf.browserName, version: conf.version, failed: '??', total: '??'});
											});
											return;
										}
										setTimeout(function() { retries++; waitOnResults(); }, 1500);
										return;
									}
								}

								browser.quit();
								process.nextTick(function() {
									if (!options.cibuild) {
										done(null, { status: 'ok' });
									} else {
										done(null, {
											status: data && (data.failed > 0) ? 'failed' : 'passed',
											id: browser.sessionID,
											name: conf.browserName,
											version: conf.version,
											failed: data.failed || '??',
											total: data.total,
											uaString: data.uaString
										});
									}
								});

								request({
									method: "PUT",
									uri: ["https://", options.username, ":", options.key, "@saucelabs.com/rest", "/v1/", options.username, "/jobs/", browser.sessionID].join(''),
									headers: {'Content-Type': 'application/json'},
									body: JSON.stringify({
										'custom-data': { custom: data },
										'passed': !data.failed
									})
								}, function (err, res, body) {
									if (!options.cibuild) {
										mkdirp(testResultsPath, function(err) {
											if (err) {
												throw err;
											}

											var file = path.join(testResultsPath, 'results.json')

											fs.readFile(file, function(err, filedata) {
												if (err) {
													// If ENOENT, continue as
													// writeFile will create
													// it
													if (err.code !== 'ENOENT') {
														throw err;
													}
												}

												var testResults  = filedata ? JSON.parse(filedata) : {};
												var browserName = UA.normalizeName(conf.browserName) || conf.browserName;

												if (!testResults[browserName]) {
													testResults[browserName] = {};
												}

												if (!testResults[browserName][conf.version]) {
													testResults[browserName][conf.version]	= {};
												}

												testResults[browserName][conf.version][urlName] = {
													passed: data.passed,
													failed: data.failed,
													failingSuites: Object.keys(data.failingSuites),
													testedSuites: data.testedSuites
												};

												fs.writeFile(file, JSON.stringify(testResults, null, 2), function(err) {
													if (err) {
														console.log(err);
														throw err;
													}
												});
											});
										});
									}
								});
							});
						}());
					});
				});
			};
		}

		grunt.log.writeln('Opening tunnel to Sauce Labs');
		tunnel.start(function(status) {

			grunt.log.writeln("Tunnel Started");
			if (status !== true)  {
				gruntDone(status);
			}

			options.browsers.forEach(function(conf) {
				conf['name'] = options.name;
				conf['record-video'] = options.video;
				conf['record-screenshots'] = options.screenshots;
				conf['tunnel-identifier'] = tunnelId;
				if (options.tags) conf['tags'] = options.tags;
				if (options.build) conf['build'] = options.build;

				Object.keys(options.urls).forEach(function(urlName) {
					var url = options.urls[urlName];
					batch.push(newTestJob(url, urlName, conf));
				});
			});

			grunt.log.writeln("Starting test jobs");
			batch.end(function(err, status) {
				console.log("Jobs complete");
				tunnel.stop(function() {
					if (!options.cibuild) {
						gruntDone(null, true);
						return;
					}

					var failed = false;
					console.log("Failed tests:")
					status.forEach(function(state) {
						if (state.status === 'failed') {
							failed = true;
							console.log("--");
							console.log("Useragent string: ", state.uaString);
							console.log(state.name + "/" + state.version, ':', state.failed + '/' + state.total + ' failed - ' + 'https://saucelabs.com/tests/' + state.id);
						}
					});

					if (!failed) {
						console.log("No failed tests");
					}

					gruntDone(!failed, failed);
				});
			});
		});
	});
};
<|endoftext|>


<commit_before>/**
 * grunt-webfont: common stuff
 *
 * @author Artem Sapegin (http://sapegin.me)
 */

var exports = {};

/**
 * Unicode Private Use Area start.
 * http://en.wikipedia.org/wiki/Private_Use_(Unicode)
 * @type {Number}
 */
exports.UNICODE_PUA_START = 0xE001;

/**
 * @font-face’s src values generation rules.
 * @type {Object}
 */
exports.fontsSrcsMap = {
	eot: [
		{
			ext: '.eot'
		},
		{
			ext: '.eot?#iefix',
			format: 'embedded-opentype'
		}
	],
	woff: [
		false,
		{
			ext: '.woff',
			format: 'woff',
			embeddable: true
		},
	],
	ttf: [
		false,
		{
			ext: '.ttf',
			format: 'truetype',
			embeddable: true
		},
	],
	svg: [
		false,
		{
			ext: '.svg?#{fontBaseName}',
			format: 'svg'
		},
	]
};

/**
 * CSS fileaname prefixes: _icons.scss.
 * @type {Object}
 */
exports.cssFilePrefixes = {
	_default: '',
	sass: '_',
	scss: '_'
};

/**
 * @font-face’s src parts seperators.
 * @type {Object}
 */
exports.fontSrcSeparators = {
	_default: ',\n\t\t',
	styl: ', '
};

/**
 * List of available font formats.
 * @type {String}
 */
exports.fontFormats = 'eot,woff,ttf,svg';

/**
 * Glob mask for all available font formats.
 * @type {String}
 */
exports.fontFileMask = '*.{' + exports.fontFormats + '}';

// Expose
module.exports = exports;
<commit_msg>Change start codepoint to more safe.<commit_after>/**
 * grunt-webfont: common stuff
 *
 * @author Artem Sapegin (http://sapegin.me)
 */

var exports = {};

/**
 * Unicode Private Use Area start.
 * http://en.wikipedia.org/wiki/Private_Use_(Unicode)
 * @type {Number}
 */
exports.UNICODE_PUA_START = 0xF101;

/**
 * @font-face’s src values generation rules.
 * @type {Object}
 */
exports.fontsSrcsMap = {
	eot: [
		{
			ext: '.eot'
		},
		{
			ext: '.eot?#iefix',
			format: 'embedded-opentype'
		}
	],
	woff: [
		false,
		{
			ext: '.woff',
			format: 'woff',
			embeddable: true
		},
	],
	ttf: [
		false,
		{
			ext: '.ttf',
			format: 'truetype',
			embeddable: true
		},
	],
	svg: [
		false,
		{
			ext: '.svg?#{fontBaseName}',
			format: 'svg'
		},
	]
};

/**
 * CSS fileaname prefixes: _icons.scss.
 * @type {Object}
 */
exports.cssFilePrefixes = {
	_default: '',
	sass: '_',
	scss: '_'
};

/**
 * @font-face’s src parts seperators.
 * @type {Object}
 */
exports.fontSrcSeparators = {
	_default: ',\n\t\t',
	styl: ', '
};

/**
 * List of available font formats.
 * @type {String}
 */
exports.fontFormats = 'eot,woff,ttf,svg';

/**
 * Glob mask for all available font formats.
 * @type {String}
 */
exports.fontFileMask = '*.{' + exports.fontFormats + '}';

// Expose
module.exports = exports;
<|endoftext|>


<commit_before>///import core
///import plugins/inserthtml.js
///import plugins/undo.js
///import plugins/serialize.js
///commands 粘贴
///commandsName  PastePlain
///commandsTitle  纯文本粘贴模式
/*
 ** @description 粘贴
 * @author zhanyi
 */
UE.plugins['paste'] = function() {
    function getClipboardData( callback ) {
        var doc = this.document;
        if ( doc.getElementById( 'baidu_pastebin' ) ) {
            return;
        }
        var range = this.selection.getRange(),
            bk = range.createBookmark(),
        //创建剪贴的容器div
            pastebin = doc.createElement( 'div' );
        pastebin.id = 'baidu_pastebin';
        // Safari 要求div必须有内容，才能粘贴内容进来
        browser.webkit && pastebin.appendChild( doc.createTextNode( domUtils.fillChar + domUtils.fillChar ) );
        doc.body.appendChild( pastebin );
        //trace:717 隐藏的span不能得到top
        //bk.start.innerHTML = ' ';
        bk.start.style.display = '';
        pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
            //要在现在光标平行的位置加入，否则会出现跳动的问题
            domUtils.getXY( bk.start ).y + 'px';

        range.selectNodeContents( pastebin ).select( true );

        setTimeout( function() {
            if (browser.webkit) {
                for(var i=0,pastebins = doc.querySelectorAll('#baidu_pastebin'),pi;pi=pastebins[i++];){
                    if(domUtils.isEmptyNode(pi)){
                        domUtils.remove(pi);
                    }else{
                        pastebin = pi;
                        break;
                    }
                }
            }
            try{
                pastebin.parentNode.removeChild(pastebin);
            }catch(e){}
            range.moveToBookmark( bk ).select(true);
            callback( pastebin );
        }, 0 );
    }

    var me = this;

    var txtContent,htmlContent,address;

    function filter(div){
        var html;
        if ( div.firstChild ) {
            //去掉cut中添加的边界值
            var nodes = domUtils.getElementsByTagName(div,'span');
              for(var i=0,ni;ni=nodes[i++];){
                if(ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end'){
                    domUtils.remove(ni);
                }
            }

            if(browser.webkit){

                var brs = div.querySelectorAll('div br');
                for(var i=0,bi;bi=brs[i++];){
                    var pN = bi.parentNode;
                    if(pN.tagName == 'DIV' && pN.childNodes.length ==1){
                        pN.innerHTML = '

';
                        domUtils.remove(pN);
                    }
                }
                var divs = div.querySelectorAll('#baidu_pastebin');
                for(var i=0,di;di=divs[i++];){
                    var tmpP = me.document.createElement('p');
                    di.parentNode.insertBefore(tmpP,di);
                    while(di.firstChild){
                        tmpP.appendChild(di.firstChild);
                    }
                    domUtils.remove(di);
                }

                var metas = div.querySelectorAll('meta');
                for(var i=0,ci;ci=metas[i++];){
                    domUtils.remove(ci);
                }

                var brs = div.querySelectorAll('br');
                for(i=0;ci=brs[i++];){
                    if(/^apple-/i.test(ci.className)){
                        domUtils.remove(ci);
                    }
                }
            }
            if(browser.gecko){
                var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
                for(i=0;ci=dirtyNodes[i++];){
                    ci.removeAttribute( '_moz_dirty' );
                }
            }
            if(!browser.ie ){
                var spans = div.querySelectorAll('span.Apple-style-span');
                for(var i=0,ci;ci=spans[i++];){
                    domUtils.remove(ci,true);
                }
            }

            //ie下使用innerHTML会产生多余的\r\n字符，也会产生 这里过滤掉
            html = div.innerHTML.replace(/>(?:(\s| )*?)</g,'><');

            //过滤word粘贴过来的冗余属性
            html = UE.filterWord(html);
            var root = UE.htmlparser(html,true);
            //如果给了过滤规则就先进行过滤
            if(me.options.filterRules){
                UE.filterNode(root,me.options.filterRules);
            }
            //执行默认的处理
            me.filterInputRule(root);
            //针对chrome的处理
            if(browser.webkit){
                var br = root.lastChild();
                if(br && br.type == 'element' && br.tagName == 'br'){
                    root.removeChild(br)
                }
                utils.each(me.body.querySelectorAll('div'),function(node){
                    if(domUtils.isEmptyBlock(node)){
                        domUtils.remove(node)
                    }
                })
            }
            html = {'html':root.toHtml()};
            me.fireEvent('beforepaste',html);
            root = UE.htmlparser(html.html);
            //如果开启了纯文本模式
            if(me.queryCommandState('pasteplain')){
                me.execCommand( 'insertHtml',UE.filterNode(root,me.options.filterTxtRules).toHtml(),true);
            }else{
                //文本模式
                UE.filterNode(root,me.options.filterTxtRules);
                txtContent = root.toHtml();
                //完全模式
                htmlContent = html.html;
                address = me.selection.getRange().createAddress(true);
                me.execCommand( 'insertHtml',htmlContent,true);
            }
            me.fireEvent("afterpaste");
        }
    }

    me.addListener('pasteTransfer',function(cmd,plainType){
        if(address && txtContent && htmlContent && txtContent != htmlContent){
            var range = me.selection.getRange();
            range.moveToAddress(address,true).deleteContents();
            range.select(true);
            me.__hasEnterExecCommand = true;
            var html = htmlContent;
            if(plainType === 2){
                html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi,function(a,b,tagName,attrs){
                    tagName = tagName.toLowerCase();
                    if({img:1}[tagName]){
                        return a;
                    }
                    attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi,function(str,atr,val){
                        if({
                            'src':1,
                            'href':1,
                            'name':1
                        }[atr.toLowerCase()]){
                            return atr + '=' + val + ' '
                        }
                        return ''
                    });
                    if({
                        'span':1,
                        'div':1
                    }[tagName]){
                        return ''
                    }else{

                        return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
                    }

                });
            }else if(plainType){
                html = txtContent;
            }
            me.execCommand('inserthtml',html,true);
            me.__hasEnterExecCommand = false;
            var tmpAddress = me.selection.getRange().createAddress(true);
            address.endAddress = tmpAddress.startAddress;
        }
    });
    me.addListener('ready',function(){
        domUtils.on(me.body,'cut',function(){
            var range = me.selection.getRange();
            if(!range.collapsed && me.undoManger){
                me.undoManger.save();
            }
        });

        //ie下beforepaste在点击右键时也会触发，所以用监控键盘才处理
        domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste',function(e){
            if((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')){
                return;
            }
            getClipboardData.call( me, function( div ) {
                filter(div);
            } );
        });

    });
};

<commit_msg>by zhanyi<commit_after>///import core
///import plugins/inserthtml.js
///import plugins/undo.js
///import plugins/serialize.js
///commands 粘贴
///commandsName  PastePlain
///commandsTitle  纯文本粘贴模式
/*
 ** @description 粘贴
 * @author zhanyi
 */
UE.plugins['paste'] = function() {
    function getClipboardData( callback ) {
        var doc = this.document;
        if ( doc.getElementById( 'baidu_pastebin' ) ) {
            return;
        }
        var range = this.selection.getRange(),
            bk = range.createBookmark(),
        //创建剪贴的容器div
            pastebin = doc.createElement( 'div' );
        pastebin.id = 'baidu_pastebin';
        // Safari 要求div必须有内容，才能粘贴内容进来
        browser.webkit && pastebin.appendChild( doc.createTextNode( domUtils.fillChar + domUtils.fillChar ) );
        doc.body.appendChild( pastebin );
        //trace:717 隐藏的span不能得到top
        //bk.start.innerHTML = ' ';
        bk.start.style.display = '';
        pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
            //要在现在光标平行的位置加入，否则会出现跳动的问题
            domUtils.getXY( bk.start ).y + 'px';

        range.selectNodeContents( pastebin ).select( true );

        setTimeout( function() {
            if (browser.webkit) {
                for(var i=0,pastebins = doc.querySelectorAll('#baidu_pastebin'),pi;pi=pastebins[i++];){
                    if(domUtils.isEmptyNode(pi)){
                        domUtils.remove(pi);
                    }else{
                        pastebin = pi;
                        break;
                    }
                }
            }
            try{
                pastebin.parentNode.removeChild(pastebin);
            }catch(e){}
            range.moveToBookmark( bk ).select(true);
            callback( pastebin );
        }, 0 );
    }

    var me = this;

    var txtContent,htmlContent,address;

    function filter(div){
        var html;
        if ( div.firstChild ) {
            //去掉cut中添加的边界值
            var nodes = domUtils.getElementsByTagName(div,'span');
              for(var i=0,ni;ni=nodes[i++];){
                if(ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end'){
                    domUtils.remove(ni);
                }
            }

            if(browser.webkit){

                var brs = div.querySelectorAll('div br');
                for(var i=0,bi;bi=brs[i++];){
                    var pN = bi.parentNode;
                    if(pN.tagName == 'DIV' && pN.childNodes.length ==1){
                        pN.innerHTML = '

';
                        domUtils.remove(pN);
                    }
                }
                var divs = div.querySelectorAll('#baidu_pastebin');
                for(var i=0,di;di=divs[i++];){
                    var tmpP = me.document.createElement('p');
                    di.parentNode.insertBefore(tmpP,di);
                    while(di.firstChild){
                        tmpP.appendChild(di.firstChild);
                    }
                    domUtils.remove(di);
                }

                var metas = div.querySelectorAll('meta');
                for(var i=0,ci;ci=metas[i++];){
                    domUtils.remove(ci);
                }

                var brs = div.querySelectorAll('br');
                for(i=0;ci=brs[i++];){
                    if(/^apple-/i.test(ci.className)){
                        domUtils.remove(ci);
                    }
                }
            }
            if(browser.gecko){
                var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
                for(i=0;ci=dirtyNodes[i++];){
                    ci.removeAttribute( '_moz_dirty' );
                }
            }
            if(!browser.ie ){
                var spans = div.querySelectorAll('span.Apple-style-span');
                for(var i=0,ci;ci=spans[i++];){
                    domUtils.remove(ci,true);
                }
            }

            //ie下使用innerHTML会产生多余的\r\n字符，也会产生 这里过滤掉
            html = div.innerHTML.replace(/>(?:(\s| )*?)</g,'><');

            //过滤word粘贴过来的冗余属性
            html = UE.filterWord(html);
            var root = UE.htmlparser(html,true);
            //如果给了过滤规则就先进行过滤
            if(me.options.filterRules){
                UE.filterNode(root,me.options.filterRules);
            }
            //执行默认的处理
            me.filterInputRule(root);
            //针对chrome的处理
            if(browser.webkit){
                var br = root.lastChild();
                if(br && br.type == 'element' && br.tagName == 'br'){
                    root.removeChild(br)
                }
                utils.each(me.body.querySelectorAll('div'),function(node){
                    if(domUtils.isEmptyBlock(node)){
                        domUtils.remove(node)
                    }
                })
            }
            html = {'html':root.toHtml()};
            me.fireEvent('beforepaste',html,root);
            root = UE.htmlparser(html.html);
            //如果开启了纯文本模式
            if(me.queryCommandState('pasteplain')){
                me.execCommand( 'insertHtml',UE.filterNode(root,me.options.filterTxtRules).toHtml(),true);
            }else{
                //文本模式
                UE.filterNode(root,me.options.filterTxtRules);
                txtContent = root.toHtml();
                //完全模式
                htmlContent = html.html;
                address = me.selection.getRange().createAddress(true);
                me.execCommand( 'insertHtml',htmlContent,true);
            }
            me.fireEvent("afterpaste");
        }
    }

    me.addListener('pasteTransfer',function(cmd,plainType){
        if(address && txtContent && htmlContent && txtContent != htmlContent){
            var range = me.selection.getRange();
            range.moveToAddress(address,true).deleteContents();
            range.select(true);
            me.__hasEnterExecCommand = true;
            var html = htmlContent;
            if(plainType === 2){
                html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi,function(a,b,tagName,attrs){
                    tagName = tagName.toLowerCase();
                    if({img:1}[tagName]){
                        return a;
                    }
                    attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi,function(str,atr,val){
                        if({
                            'src':1,
                            'href':1,
                            'name':1
                        }[atr.toLowerCase()]){
                            return atr + '=' + val + ' '
                        }
                        return ''
                    });
                    if({
                        'span':1,
                        'div':1
                    }[tagName]){
                        return ''
                    }else{

                        return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
                    }

                });
            }else if(plainType){
                html = txtContent;
            }
            me.execCommand('inserthtml',html,true);
            me.__hasEnterExecCommand = false;
            var tmpAddress = me.selection.getRange().createAddress(true);
            address.endAddress = tmpAddress.startAddress;
        }
    });
    me.addListener('ready',function(){
        domUtils.on(me.body,'cut',function(){
            var range = me.selection.getRange();
            if(!range.collapsed && me.undoManger){
                me.undoManger.save();
            }
        });

        //ie下beforepaste在点击右键时也会触发，所以用监控键盘才处理
        domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste',function(e){
            if((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')){
                return;
            }
            getClipboardData.call( me, function( div ) {
                filter(div);
            } );
        });

    });
};

<|endoftext|>


<commit_before>///import core
///import plugins/inserthtml.js
///import plugins/undo.js
///import plugins/serialize.js
///commands 粘贴
///commandsName  PastePlain
///commandsTitle  纯文本粘贴模式
/*
 ** @description 粘贴
 * @author zhanyi
 */
(function() {
    function getClipboardData( callback ) {

        var doc = this.document;

        if ( doc.getElementById( 'baidu_pastebin' ) ) {
            return;
        }

        var range = this.selection.getRange(),
            bk = range.createBookmark(),
        //创建剪贴的容器div
            pastebin = doc.createElement( 'div' );

        pastebin.id = 'baidu_pastebin';

        // Safari 要求div必须有内容，才能粘贴内容进来
        browser.webkit && pastebin.appendChild( doc.createTextNode( domUtils.fillChar + domUtils.fillChar ) );
        doc.body.appendChild( pastebin );
        //trace:717 隐藏的span不能得到top
        //bk.start.innerHTML = ' ';
        bk.start.style.display = '';
        pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
            //要在现在光标平行的位置加入，否则会出现跳动的问题
            domUtils.getXY( bk.start ).y + 'px';

        range.selectNodeContents( pastebin ).select( true );

        setTimeout( function() {

            if (browser.webkit) {

                for(var i=0,pastebins = doc.querySelectorAll('#baidu_pastebin'),pi;pi=pastebins[i++];){
                    if(domUtils.isEmptyNode(pi)){
                        domUtils.remove(pi);
                    }else{
                        pastebin = pi;
                        break;
                    }
                }

            }

            try{
                pastebin.parentNode.removeChild(pastebin);
            }catch(e){}

            range.moveToBookmark( bk ).select(true);
            callback( pastebin );
        }, 0 );

    }

    UE.plugins['paste'] = function() {
        var me = this;
        var word_img_flag = {flag:""};

        var pasteplain = me.options.pasteplain === true;
        var modify_num = {flag:""};
        me.commands['pasteplain'] = {
            queryCommandState: function (){
                return pasteplain;
            },
            execCommand: function (){
                pasteplain = !pasteplain|0;
            },
            notNeedUndo : 1
        };
        var txtContent,bkRange,htmlContent;
        function filter(div){

            var html;
            if ( div.firstChild ) {
                //去掉cut中添加的边界值
                var nodes = domUtils.getElementsByTagName(div,'span');
                for(var i=0,ni;ni=nodes[i++];){
                    if(ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end'){
                        domUtils.remove(ni);
                    }
                }

                if(browser.webkit){

                    var brs = div.querySelectorAll('div br');
                    for(var i=0,bi;bi=brs[i++];){
                        var pN = bi.parentNode;
                        if(pN.tagName == 'DIV' && pN.childNodes.length ==1){
                            pN.innerHTML = '

';

                            domUtils.remove(pN);
                        }
                    }
                    var divs = div.querySelectorAll('#baidu_pastebin');
                    for(var i=0,di;di=divs[i++];){
                        var tmpP = me.document.createElement('p');
                        di.parentNode.insertBefore(tmpP,di);
                        while(di.firstChild){
                            tmpP.appendChild(di.firstChild);
                        }
                        domUtils.remove(di);
                    }

                    var metas = div.querySelectorAll('meta');
                    for(var i=0,ci;ci=metas[i++];){
                        domUtils.remove(ci);
                    }

                    var brs = div.querySelectorAll('br');
                    for(i=0;ci=brs[i++];){
                        if(/^apple-/.test(ci)){
                            domUtils.remove(ci);
                        }
                    }

                }
                if(browser.gecko){
                    var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
                    for(i=0;ci=dirtyNodes[i++];){
                        ci.removeAttribute( '_moz_dirty' );
                    }
                }
                if(!browser.ie ){
                    var spans = div.querySelectorAll('span.Apple-style-span');
                    for(var i=0,ci;ci=spans[i++];){
                        domUtils.remove(ci,true);
                    }
                }

                html = div.innerHTML;

                var f = me.serialize;
                if(f){
                    //如果过滤出现问题，捕获它，直接插入内容，避免出现错误导致粘贴整个失败
                    try{
                        var node =  f.transformInput(
                            f.parseHTML(
                                //todo: 暂时不走dtd的过滤
                                f.word(html)//, true
                            ),word_img_flag
                        );
                        //trace:924
                        //纯文本模式也要保留段落
                        node = f.filter(node,pasteplain ? {
                            whiteList: {
                                'p': {'br':1,'BR':1,$:{}},
                                'br':{'$':{}},
                                'div':{'br':1,'BR':1,'$':{}},
                                'li':{'$':{}},
                                'tr':{'td':1,'$':{}},
                                'td':{'$':{}}

                            },
                            blackList: {
                                'style':1,
                                'script':1,
                                'object':1
                            }
                        } : null, !pasteplain ? modify_num : null);

                        if(browser.webkit){
                            var length = node.children.length,
                                child;
                            while((child = node.children[length-1]) && child.tag == 'br'){
                                node.children.splice(length-1,1);
                                length = node.children.length;
                            }
                        }

                        html = f.toHTML(node,pasteplain);
                        txtContent = f.filter(node,{
                            whiteList: {
                                'p': {'br':1,'BR':1,$:{}},
                                'br':{'$':{}},
                                'div':{'br':1,'BR':1,'$':{},'table':1,'ul':1,'ol':1},
                                'li':{'$':{}},
                                'ul':{'li':1,'$':{}},
                                'ol':{'li':1,'$':{}},
                                'tr':{'td':1,'$':{}},
                                'td':{'$':{}},
                                'table': {'tr':1,'tbody':1,'td':1,'$':{}},
                                'tbody': {'tr':1,'td':1,'$':{}},
                                h1:{'$':{}},h2:{'$':{}},h3:{'$':{}},h4:{'$':{}},h5:{'$':{}},h6:{'$':{}}
                            },
                            blackList: {
                                'style':1,
                                'script':1,
                                'object':1
                            }
                        });

                        txtContent = f.toHTML(txtContent,true)

                    }catch(e){}

                }

                //自定义的处理
                html = {'html':html};

                me.fireEvent('beforepaste',html);
                //不用在走过滤了
                if(html.html){
                    clearBk();
                    txtContent = '\ufeff'
                        + txtContent + '\ufeff';
                    htmlContent =  '\ufeff'
                        + html.html + '\ufeff';
                    me.execCommand( 'insertHtml',htmlContent,true);
                    me.addListener('mouseup keydown',clearBk);
                    me.fireEvent("afterpaste");
                }

            }
        }
        function clearBk(){
            var bk,flag = 0;
            while(bk = me.document.getElementById('_ue_paste_id_start')){
                flag = 1;
                domUtils.remove(bk)
            }
            while(bk = me.document.getElementById('_ue_paste_id_end')){
                domUtils.remove(bk)
            }
            if(flag){
                me.removeListener('mouseup keydown',arguments.callee)
            }
        }
        var startAddr,endAddr;
        me.addListener('beforegetscene',function(){

            var start = me.document.getElementById('_ue_paste_id_start');
            if(start){
                startAddr = domUtils.getAddr(start);

            }
            var end = me.document.getElementById('_ue_paste_id_end');
            if(end){
                endAddr = domUtils.getAddr(end);

            }
            if(start && end){
                domUtils.remove(start);
                domUtils.remove(end)
            }
        });
        me.addListener('aftergetscene',function(){
            var span = domUtils.createElement(me.document,'span',{
                'style' : "display:none;line-height:0px;",
                'id'  : "_ue_paste_id_start",
                'innerHTML' : domUtils.fillChar
            });
            if(startAddr){
                domUtils.setAddr(span,startAddr);
                startAddr = null;
            }
            if(endAddr){
                span = span.cloneNode(true);
                span.id = '_ue_paste_id_end';
                domUtils.setAddr(span,endAddr);
                endAddr = null;
            }
        });
        me.addListener('pasteTransfer',function(cmd,plainType){

            var range = me.selection.getRange();
            var start = me.document.getElementById('_ue_paste_id_start');
            var end = me.document.getElementById('_ue_paste_id_end');
            if(start && end && txtContent && htmlContent && txtContent != htmlContent){

                range.setStartAfter(start).setEndAfter(end).deleteContents();
                range.setStartBefore(start).collapse(true);
                domUtils.remove(start);
                range.select(true);

                me.__hasEnterExecCommand = true;
                me.execCommand('inserthtml',plainType ? txtContent : htmlContent,true);
                me.__hasEnterExecCommand = false;
                me.addListener('mouseup keydown',clearBk)
            }
        });
        me.addListener('ready',function(){
            domUtils.on(me.body,'cut',function(){

                var range = me.selection.getRange();
                if(!range.collapsed && me.undoManger){
                    me.undoManger.save();
                }

            });
            //ie下beforepaste在点击右键时也会触发，所以用监控键盘才处理
            domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste',function(e){

                if((browser.ie || browser.opera) && (!e.ctrlKey || e.keyCode != '86')){
                    return;
                }

                getClipboardData.call( me, function( div ) {

                    filter(div);
                } );

            });

        });

    };

})();

<commit_msg>by zhanyi<commit_after>///import core
///import plugins/inserthtml.js
///import plugins/undo.js
///import plugins/serialize.js
///commands 粘贴
///commandsName  PastePlain
///commandsTitle  纯文本粘贴模式
/*
 ** @description 粘贴
 * @author zhanyi
 */
(function() {
    function getClipboardData( callback ) {

        var doc = this.document;

        if ( doc.getElementById( 'baidu_pastebin' ) ) {
            return;
        }

        var range = this.selection.getRange(),
            bk = range.createBookmark(),
        //创建剪贴的容器div
            pastebin = doc.createElement( 'div' );

        pastebin.id = 'baidu_pastebin';

        // Safari 要求div必须有内容，才能粘贴内容进来
        browser.webkit && pastebin.appendChild( doc.createTextNode( domUtils.fillChar + domUtils.fillChar ) );
        doc.body.appendChild( pastebin );
        //trace:717 隐藏的span不能得到top
        //bk.start.innerHTML = ' ';
        bk.start.style.display = '';
        pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
            //要在现在光标平行的位置加入，否则会出现跳动的问题
            domUtils.getXY( bk.start ).y + 'px';

        range.selectNodeContents( pastebin ).select( true );

        setTimeout( function() {

            if (browser.webkit) {

                for(var i=0,pastebins = doc.querySelectorAll('#baidu_pastebin'),pi;pi=pastebins[i++];){
                    if(domUtils.isEmptyNode(pi)){
                        domUtils.remove(pi);
                    }else{
                        pastebin = pi;
                        break;
                    }
                }

            }

            try{
                pastebin.parentNode.removeChild(pastebin);
            }catch(e){}

            range.moveToBookmark( bk ).select(true);
            callback( pastebin );
        }, 0 );

    }

    UE.plugins['paste'] = function() {
        var me = this;
        var word_img_flag = {flag:""};

        var pasteplain = me.options.pasteplain === true;
        var modify_num = {flag:""};
        me.commands['pasteplain'] = {
            queryCommandState: function (){
                return pasteplain;
            },
            execCommand: function (){
                pasteplain = !pasteplain|0;
            },
            notNeedUndo : 1
        };
        var txtContent,bkRange,htmlContent;
        function filter(div){

            var html;
            if ( div.firstChild ) {
                //去掉cut中添加的边界值
                var nodes = domUtils.getElementsByTagName(div,'span');
                for(var i=0,ni;ni=nodes[i++];){
                    if(ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end'){
                        domUtils.remove(ni);
                    }
                }

                if(browser.webkit){

                    var brs = div.querySelectorAll('div br');
                    for(var i=0,bi;bi=brs[i++];){
                        var pN = bi.parentNode;
                        if(pN.tagName == 'DIV' && pN.childNodes.length ==1){
                            pN.innerHTML = '

';

                            domUtils.remove(pN);
                        }
                    }
                    var divs = div.querySelectorAll('#baidu_pastebin');
                    for(var i=0,di;di=divs[i++];){
                        var tmpP = me.document.createElement('p');
                        di.parentNode.insertBefore(tmpP,di);
                        while(di.firstChild){
                            tmpP.appendChild(di.firstChild);
                        }
                        domUtils.remove(di);
                    }

                    var metas = div.querySelectorAll('meta');
                    for(var i=0,ci;ci=metas[i++];){
                        domUtils.remove(ci);
                    }

                    var brs = div.querySelectorAll('br');
                    for(i=0;ci=brs[i++];){
                        if(/^apple-/.test(ci)){
                            domUtils.remove(ci);
                        }
                    }

                    utils.each(domUtils.getElementsByTagName(div,'span',function(node){
                        if(node.style.cssText){
                            node.style.cssText =  node.style.cssText.replace(/white-space[^;]+;/g,'');
                            if(!node.style.cssText){
                                domUtils.removeAttributes(node,'style');
                                if(domUtils.hasNoAttributes(node)){
                                    return 1
                                }
                            }
                        }
                        return 0
                    }),function(si){
                        domUtils.remove(si,true)
                    })
                }
                if(browser.gecko){
                    var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
                    for(i=0;ci=dirtyNodes[i++];){
                        ci.removeAttribute( '_moz_dirty' );
                    }
                }
                if(!browser.ie ){
                    var spans = div.querySelectorAll('span.Apple-style-span');
                    for(var i=0,ci;ci=spans[i++];){
                        domUtils.remove(ci,true);
                    }
                }

                html = div.innerHTML;

                var f = me.serialize;
                if(f){
                    //如果过滤出现问题，捕获它，直接插入内容，避免出现错误导致粘贴整个失败
                    try{
                        var node =  f.transformInput(
                            f.parseHTML(
                                //todo: 暂时不走dtd的过滤
                                f.word(html)//, true
                            ),word_img_flag
                        );
                        //trace:924
                        //纯文本模式也要保留段落
                        node = f.filter(node,pasteplain ? {
                            whiteList: {
                                'p': {'br':1,'BR':1,$:{}},
                                'br':{'$':{}},
                                'div':{'br':1,'BR':1,'$':{}},
                                'li':{'$':{}},
                                'tr':{'td':1,'$':{}},
                                'td':{'$':{}}

                            },
                            blackList: {
                                'style':1,
                                'script':1,
                                'object':1
                            }
                        } : null, !pasteplain ? modify_num : null);

                        if(browser.webkit){
                            var length = node.children.length,
                                child;
                            while((child = node.children[length-1]) && child.tag == 'br'){
                                node.children.splice(length-1,1);
                                length = node.children.length;
                            }
                        }

                        html = f.toHTML(node,pasteplain);
                        txtContent = f.filter(node,{
                            whiteList: {
                                'p': {'br':1,'BR':1,$:{}},
                                'br':{'$':{}},
                                'div':{'br':1,'BR':1,'$':{},'table':1,'ul':1,'ol':1},
                                'li':{'$':{}},
                                'ul':{'li':1,'$':{}},
                                'ol':{'li':1,'$':{}},
                                'tr':{'td':1,'$':{}},
                                'td':{'$':{}},
                                'table': {'tr':1,'tbody':1,'td':1,'$':{}},
                                'tbody': {'tr':1,'td':1,'$':{}},
                                h1:{'$':{}},h2:{'$':{}},h3:{'$':{}},h4:{'$':{}},h5:{'$':{}},h6:{'$':{}}
                            },
                            blackList: {
                                'style':1,
                                'script':1,
                                'object':1
                            }
                        });

                        txtContent = f.toHTML(txtContent,true)

                    }catch(e){}

                }

                //自定义的处理
                html = {'html':html};

                me.fireEvent('beforepaste',html);
                //不用在走过滤了
                if(html.html){
                    clearBk();
                    txtContent = '\ufeff'
                        + txtContent + '\ufeff';
                    htmlContent =  '\ufeff'
                        + html.html + '\ufeff';
                    me.execCommand( 'insertHtml',htmlContent,true);
                    me.addListener('mouseup keydown',clearBk);
                    me.fireEvent("afterpaste");
                }

            }
        }
        function clearBk(){
            var bk,flag = 0;
            while(bk = me.document.getElementById('_ue_paste_id_start')){
                flag = 1;
                domUtils.remove(bk)
            }
            while(bk = me.document.getElementById('_ue_paste_id_end')){
                domUtils.remove(bk)
            }
            if(flag){
                me.removeListener('mouseup keydown',arguments.callee)
            }
        }
        var startAddr,endAddr;
        me.addListener('beforegetscene',function(){

            var start = me.document.getElementById('_ue_paste_id_start');
            if(start){
                startAddr = domUtils.getAddr(start);

            }
            var end = me.document.getElementById('_ue_paste_id_end');
            if(end){
                endAddr = domUtils.getAddr(end);

            }
            if(start && end){
                domUtils.remove(start);
                domUtils.remove(end)
            }
        });
        me.addListener('aftergetscene',function(){
            var span = domUtils.createElement(me.document,'span',{
                'style' : "display:none;line-height:0px;",
                'id'  : "_ue_paste_id_start",
                'innerHTML' : domUtils.fillChar
            });
            if(startAddr){
                domUtils.setAddr(span,startAddr);
                startAddr = null;
            }
            if(endAddr){
                span = span.cloneNode(true);
                span.id = '_ue_paste_id_end';
                domUtils.setAddr(span,endAddr);
                endAddr = null;
            }
        });
        me.addListener('pasteTransfer',function(cmd,plainType){

            var range = me.selection.getRange();
            var start = me.document.getElementById('_ue_paste_id_start');
            var end = me.document.getElementById('_ue_paste_id_end');
            if(start && end && txtContent && htmlContent && txtContent != htmlContent){

                range.setStartAfter(start).setEndAfter(end).deleteContents();
                range.setStartBefore(start).collapse(true);
                domUtils.remove(start);
                range.select(true);

                me.__hasEnterExecCommand = true;
                me.execCommand('inserthtml',plainType ? txtContent : htmlContent,true);
                me.__hasEnterExecCommand = false;
                me.addListener('mouseup keydown',clearBk)
            }
        });
        me.addListener('ready',function(){
            domUtils.on(me.body,'cut',function(){

                var range = me.selection.getRange();
                if(!range.collapsed && me.undoManger){
                    me.undoManger.save();
                }

            });
            //ie下beforepaste在点击右键时也会触发，所以用监控键盘才处理
            domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste',function(e){

                if((browser.ie || browser.opera) && (!e.ctrlKey || e.keyCode != '86')){
                    return;
                }

                getClipboardData.call( me, function( div ) {

                    filter(div);
                } );

            });

        });

    };

})();

<|endoftext|>


<commit_before>const parse = require("./parser.js");
const loaderUtils = require('loader-utils');

const postcss = require("postcss");
const lessSyntax = require('postcss-less');

const path = require('path');
const hash = require('hash-sum');
const qs = require('querystring');
const fs = require("fs");

const componentNormalizerPath = require.resolve('./lib/componentNormalizer.js');

const { attrsToQuery } = require('./utils.js')

const { genHotReloadCode } = require('./hotReload.js');

module.exports = async function (source) {
	const loaderContext = this;

	const stringifyRequest = r => loaderUtils.stringifyRequest(loaderContext, r);

	const {
		target,
		request,
		minimize,
		sourceMap,
		rootContext,
		resourcePath,
		resourceQuery
	} = loaderContext;

	const rawQuery = resourceQuery.slice(1);
	const inheritQuery = `&${rawQuery}`;
	const incomingQuery = qs.parse(rawQuery || loaderContext.query);
	const options = loaderUtils.getOptions(loaderContext) || {};

	let server = options.server;

	let profiles = server.configService.getColorProfiles();

	const getColorSets = (profileName) => {
		let unsetDefault = {
			primary: "#2196f3",
			secondary: "#03a9f4",
			tertiary: "#00bcd4",
			success: "#81c784",
			warning: "#f4511e",
			info: "#2196f3",
			danger: "#e91e63",
			background: {
				dark: "#1a1a1a",
				light: "#f5f5f5"
			}
		};

		let mapping = {
			primary: "websomPrimary",
			secondary: "websomSecondary",
			tertiary: "websomTertiary",
			background: "websomBackground",
			success: "websomSuccess",
			danger: "websomDanger",
			warning: "websomWarning",
			info: "websomInfo"
		};

		let profile = profiles[profileName] || {};
		let props = [];

		for (let k in mapping) {
			let col = profile[k] || unsetDefault[k];
			let light, dark;

			if (typeof col == "string") {
				light = dark = col;
			}else{
				light = col.light;
				dark = col.dark;
			}

			props.push(`@${mapping[k]}Dark: ${dark};`);
			props.push(`@${mapping[k]}Light: ${light};`);
		}

		return props.join("\n");
	};

	const isServer = target === 'node';
	const isShadow = !!options.shadowMode;
	const isProduction = options.productionMode || minimize || process.env.NODE_ENV === 'production';
	const filename = path.basename(resourcePath);
	const context = rootContext || process.cwd();
	const sourceRoot = path.dirname(path.relative(context, resourcePath));

	const rawShortFilePath = path
		.relative(context, resourcePath)
		.replace(/^(\.\.[\/\\])+/, '');

	const shortFilePath = rawShortFilePath.replace(/\\/g, '/') + resourceQuery;

	const id = hash(isProduction ? (shortFilePath + '\n' + source) : shortFilePath);

	let blocks = parse(source);
	let info = {};
	let type = "";

	const needsHotReload = (
		!isServer &&
		!isProduction
	);

	let types = [
		"component",
		"effect",
		"script",
		"style",
		"page",
		"state"
	];

	try {
		info = JSON.parse(`{${blocks.info.block}}`);

		if (!info) {
			throw new Error("No info block provided");
		}

		if (!info.name || info.name == "") {
			throw new Error("View name must be set in info");
		}

		if (!info.type || info.type == "") {
			throw new Error("View type must be set in info");
		}

		type = info.type;

		if (types.indexOf(info.type) == -1) {
			throw new Error("Unknown type " + info.type + ". Allowed values are: " + JSON.stringify(types));
		}
	}catch(e) {
		throw new Error("JSON syntax error while parsing info block: " + e + "\n" + blocks.info.block);
	}

	let thisFile = path.join(__dirname, "loader.js");

	if (incomingQuery["extract-style"]) {
		if (blocks.style) {
			let usePostCSS = false;
			if (usePostCSS) {
				let lessOutput = postcss.parse(blocks.style.block, { syntax: lessSyntax });

				for (let nde of lessOutput.nodes) {
					if (nde.type != "rule")
						continue;

					let isComponent = false;

					if (nde.selectors[0].substr(0, 1) == "[") {
						if (nde.selectors[0].length > 11 && nde.selectors[0].substr(0, 11) == "[component]") {
							isComponent = true;
						}
					}

					if (isComponent) {
						let newSelectors = [];

						for (let [i, selector] of nde.selectors.entries()) {
							if (i == 0) {
								if (selector.substr(0, 1) == "[" && selector.length > 11 && selector.substr(0, 11) == "[component]")
									selector = nde.selectors[0].substr(11, nde.selectors[0].length);
							}
							newSelectors.push(`body:not(.${incomingQuery.package}-${info.name}-disabled):not(.${incomingQuery.package}-disabled).package-${incomingQuery.package}-${info.name}-on ${selector}`);
							newSelectors.push(`body:not(.${incomingQuery.package}-${info.name}-disabled):not(.${incomingQuery.package}-disabled) ${selector}`);
						}

						nde.selectors = newSelectors;
					}
				}

				return lessOutput.toResult().css;
			}else{
				return `
					${fs.readFileSync(path.resolve(__dirname, "../tools.less"))}

					@component: ~"body:not(.${incomingQuery.package}-${info.name}-disabled):not(.${incomingQuery.package}-disabled).package-${incomingQuery.package}-${info.name}-on, body:not(.${incomingQuery.package}-${info.name}-disabled):not(.${incomingQuery.package}-disabled)";

					${getColorSets("default")}

					${blocks.style.block};
				`;
			}

		}else{
			return "";
		}
	}

	if (incomingQuery["extract-info"]) {
		return `export default {${blocks.info.block}};`;
	}

	if (incomingQuery["extract-script"]) {
		if (blocks.script)
			return blocks.script.block;
		else
			return `
				throw new Error("No script block included in effect ${info.name}");
				export default {}
			`;
	}

	if (incomingQuery["extract-config"]) {
		if (blocks.config)
			return `export default {${blocks.config.block}};`;
		else
			return `
				export default {options: []}
			`;
	}

	// template
	let templateImport = `var render, staticRenderFns`;
	let templateRequest;
	if (blocks.template) {
		const src = blocks.template.block;
		const idQuery = `&id=${id}`;
		const scopedQuery = ``;
		const attrsQuery = attrsToQuery({});
		const query = `?vue&type=template${idQuery}${scopedQuery}${attrsQuery}${inheritQuery}`;
		const request = templateRequest = stringifyRequest(src + query);
		templateImport = (
			`import render from "!vue-loader?vue&type=template!${thisFile.replace(/\\/g, "/")}?type=script!${this.resourcePath.replace(/\\/g, "/")}"\n`
		);
	}

	// script
	let scriptImport = `var script = {}`;
	if (blocks.script) {
		const src = blocks.script.block || resourcePath;
		const attrsQuery = attrsToQuery(blocks.script.options || {}, 'js');
		const query = `?vue&type=script${attrsQuery}${inheritQuery}`;
		const request = stringifyRequest(src + query);
		scriptImport = (
			`import script from "!babel-loader!${thisFile.replace(/\\/g, "/")}?type=script!${this.resourcePath.replace(/\\/g, "/")}"\n`
		);
	}

	if (!blocks.template) {
		throw new Error("Component or page views must have a template block.");
	}

	if (rawQuery.includes("vue")) {
	return `

<template>
${blocks.template.block}
</template>

<script>
${blocks.script ? blocks.script.block : "export default {}"}
</script>

`;
	}

	return `
	const configOptions = {${blocks.config ? blocks.config.block : ""}};

	import vvv from "${this.resourcePath.replace(/\\/g, "/")}?vue"\n

	let oldRender = vvv.render;

	vvv.render = function (createElement) {
		let that = this;

		let configSets = {};

		for (let k in configOptions.options) {
			let val = this.$store.state.websom.data.config["${incomingQuery.packageType}.${incomingQuery.package.toLowerCase()}.${info.name}." + k];

			if (val)
				configSets[k] = val;
		}

		if (!this.$createElementOverride) {
			this.$createElementOverride = true;

			let old = this._c;
			this._c = function (a, b, c, d) {
				let cls = {};

				if (b && b.staticClass)
					for (let n of b.staticClass.split(" "))
						cls[n] = true;

				/*else if (typeof obj.class == "object") {
					cls = obj.class;
				}else if (typeof obj.class == "array") {
					for (let n of obj.class) {
						if (typeof n == "object")
							cls = {cls, ...n};
						else
							cls[n] = true;
					}
				}*/

				if (that && that.$root.$options.injects && that.$root.$options.injects["${info.name}"]) {
					let exts = that.$root.$options.injects["${info.name}"];

					for (let ext of exts) {
						if (!cls[ext.info.prependTo.replace(".", "")])
							continue;

						if (!that.$websomInjections) {
							that.$websomInjections = {};
						}

						if (!that.$websomInjections[ext.info.name]) {
							that.$websomInjections[ext.info.name] = new ext.vue._Ctor[0]();
						}

						if (that.$websomInjections)
							c.unshift(that.$websomInjections[ext.info.name]._render(createElement));
					}
				}

				return old(a, b, c, d);
			};
		}

		let res = oldRender.call(this, createElement);
		if (!res.data)
			res.data = {};

		if (!res.data.normalizedStyle)
			res.data.normalizedStyle = {};

		if (!res.data.style)
			res.data.style = "";

		let styles = "";
		for (const [key, value] of Object.entries(configOptions.options || {})) {
			let setValue = configSets[key] || value.default || "";
			if (this.config) {
				setValue = this.config[key] || setValue;
			}
			let kebab = key.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
			res.data.normalizedStyle["--" + kebab] = setValue;
			styles += "--" + kebab + ":" + setValue + ";";
		}

		res.data.style = styles + res.data.style;

		return res;
	};

	if (!vvv.props) {
		vvv.props = {};
	}

	if (Array.isArray(vvv.props))
		console.error("Do not use arrays for view prop definitions. Use {} instead.");

	let defaults = {};

	for (let key in (configOptions.options || {})) {
		if (configOptions.options.hasOwnProperty(key))
			defaults[key] = configOptions.options[key].default || "";
	}

	const view = {
		info: {${blocks.info.block}},
		package: ${JSON.stringify(incomingQuery.package) || "\"unknown\""},
		packageType: ${JSON.stringify(incomingQuery.packageType) || "\"unknown\""},
		vue: vvv,
		config: configOptions,
		defaultConfigOptions: defaults
	};

	vvv.props.config = {
		type: Object,
		required: false,
		default: () => { return {}; }
	};

	vvv.props.websomView = {
		type: Object,
		required: false,
		default() {
			return view;
		}
	};

	vvv.$view = view;

	export default view;`;

	let stylesCode = "";

	let outputCode = `
	${templateImport}
	${scriptImport}

	import normalizer from ${stringifyRequest(`!${componentNormalizerPath}`)}
	var component = normalizer(
		script,
		render,
		staticRenderFns,
		false,
		${/injectStyles/.test(stylesCode) ? `injectStyles` : `null`},
		null,
		${isServer ? JSON.stringify(hash(request)) : `null`}
		${isShadow ? `,true` : ``}
	)
	`.trim() + `\n`;

	if (needsHotReload) {
		outputCode += `\n` + genHotReloadCode(id, false, templateRequest);
	}

	if (!isProduction) {
		outputCode += `\ncomponent.options.__file = ${JSON.stringify(rawShortFilePath.replace(/\\/g, '/'))}`;
	} else if (options.exposeFilename) {
		// Libraries can opt-in to expose their components' filenames in production builds.
		// For security reasons, only expose the file's basename in production.
		outputCode += `\ncomponent.options.__file = ${JSON.stringify(filename)}`;
	}

	outputCode += `\nexport default component.exports`;

	return outputCode;
};<commit_msg>Fixed color defaults.<commit_after>const parse = require("./parser.js");
const loaderUtils = require('loader-utils');

const postcss = require("postcss");
const lessSyntax = require('postcss-less');

const path = require('path');
const hash = require('hash-sum');
const qs = require('querystring');
const fs = require("fs");

const componentNormalizerPath = require.resolve('./lib/componentNormalizer.js');

const { attrsToQuery } = require('./utils.js')

const { genHotReloadCode } = require('./hotReload.js');

module.exports = async function (source) {
	const loaderContext = this;

	const stringifyRequest = r => loaderUtils.stringifyRequest(loaderContext, r);

	const {
		target,
		request,
		minimize,
		sourceMap,
		rootContext,
		resourcePath,
		resourceQuery
	} = loaderContext;

	const rawQuery = resourceQuery.slice(1);
	const inheritQuery = `&${rawQuery}`;
	const incomingQuery = qs.parse(rawQuery || loaderContext.query);
	const options = loaderUtils.getOptions(loaderContext) || {};

	let server = options.server;

	let profiles = server.configService.getColorProfiles();

	const getColorSets = (profileName) => {
		let unsetDefault = {
			primary: "#2196f3",
			secondary: "#03a9f4",
			tertiary: "#00bcd4",
			success: "#81c784",
			warning: "#f4511e",
			info: "#2196f3",
			danger: "#e91e63",
			background: {
				dark: "#1a1a1a",
				light: "#f5f5f5"
			}
		};

		let mapping = {
			primary: "websomPrimary",
			secondary: "websomSecondary",
			tertiary: "websomTertiary",
			background: "websomBackground",
			success: "websomSuccess",
			danger: "websomDanger",
			warning: "websomWarning",
			info: "websomInfo"
		};

		let profile = profiles[profileName] || {};
		let props = [];

		for (let k in mapping) {
			let col = profile[k] || unsetDefault[k];
			let light, dark;

			if (typeof col == "string") {
				light = dark = col;
			}else{
				light = col.light || unsetDefault[k].light || col;
				dark = col.dark || unsetDefault[k].dark || col;
			}

			props.push(`@${mapping[k]}Dark: ${dark};`);
			props.push(`@${mapping[k]}Light: ${light};`);
		}

		return props.join("\n");
	};

	const isServer = target === 'node';
	const isShadow = !!options.shadowMode;
	const isProduction = options.productionMode || minimize || process.env.NODE_ENV === 'production';
	const filename = path.basename(resourcePath);
	const context = rootContext || process.cwd();
	const sourceRoot = path.dirname(path.relative(context, resourcePath));

	const rawShortFilePath = path
		.relative(context, resourcePath)
		.replace(/^(\.\.[\/\\])+/, '');

	const shortFilePath = rawShortFilePath.replace(/\\/g, '/') + resourceQuery;

	const id = hash(isProduction ? (shortFilePath + '\n' + source) : shortFilePath);

	let blocks = parse(source);
	let info = {};
	let type = "";

	const needsHotReload = (
		!isServer &&
		!isProduction
	);

	let types = [
		"component",
		"effect",
		"script",
		"style",
		"page",
		"state"
	];

	try {
		info = JSON.parse(`{${blocks.info.block}}`);

		if (!info) {
			throw new Error("No info block provided");
		}

		if (!info.name || info.name == "") {
			throw new Error("View name must be set in info");
		}

		if (!info.type || info.type == "") {
			throw new Error("View type must be set in info");
		}

		type = info.type;

		if (types.indexOf(info.type) == -1) {
			throw new Error("Unknown type " + info.type + ". Allowed values are: " + JSON.stringify(types));
		}
	}catch(e) {
		throw new Error("JSON syntax error while parsing info block: " + e + "\n" + blocks.info.block);
	}

	let thisFile = path.join(__dirname, "loader.js");

	if (incomingQuery["extract-style"]) {
		if (blocks.style) {
			let usePostCSS = false;
			if (usePostCSS) {
				let lessOutput = postcss.parse(blocks.style.block, { syntax: lessSyntax });

				for (let nde of lessOutput.nodes) {
					if (nde.type != "rule")
						continue;

					let isComponent = false;

					if (nde.selectors[0].substr(0, 1) == "[") {
						if (nde.selectors[0].length > 11 && nde.selectors[0].substr(0, 11) == "[component]") {
							isComponent = true;
						}
					}

					if (isComponent) {
						let newSelectors = [];

						for (let [i, selector] of nde.selectors.entries()) {
							if (i == 0) {
								if (selector.substr(0, 1) == "[" && selector.length > 11 && selector.substr(0, 11) == "[component]")
									selector = nde.selectors[0].substr(11, nde.selectors[0].length);
							}
							newSelectors.push(`body:not(.${incomingQuery.package}-${info.name}-disabled):not(.${incomingQuery.package}-disabled).package-${incomingQuery.package}-${info.name}-on ${selector}`);
							newSelectors.push(`body:not(.${incomingQuery.package}-${info.name}-disabled):not(.${incomingQuery.package}-disabled) ${selector}`);
						}

						nde.selectors = newSelectors;
					}
				}

				return lessOutput.toResult().css;
			}else{
				return `
					${fs.readFileSync(path.resolve(__dirname, "../tools.less"))}

					@component: ~"body:not(.${incomingQuery.package}-${info.name}-disabled):not(.${incomingQuery.package}-disabled).package-${incomingQuery.package}-${info.name}-on, body:not(.${incomingQuery.package}-${info.name}-disabled):not(.${incomingQuery.package}-disabled)";

					${getColorSets("default")}

					${blocks.style.block};
				`;
			}

		}else{
			return "";
		}
	}

	if (incomingQuery["extract-info"]) {
		return `export default {${blocks.info.block}};`;
	}

	if (incomingQuery["extract-script"]) {
		if (blocks.script)
			return blocks.script.block;
		else
			return `
				throw new Error("No script block included in effect ${info.name}");
				export default {}
			`;
	}

	if (incomingQuery["extract-config"]) {
		if (blocks.config)
			return `export default {${blocks.config.block}};`;
		else
			return `
				export default {options: []}
			`;
	}

	// template
	let templateImport = `var render, staticRenderFns`;
	let templateRequest;
	if (blocks.template) {
		const src = blocks.template.block;
		const idQuery = `&id=${id}`;
		const scopedQuery = ``;
		const attrsQuery = attrsToQuery({});
		const query = `?vue&type=template${idQuery}${scopedQuery}${attrsQuery}${inheritQuery}`;
		const request = templateRequest = stringifyRequest(src + query);
		templateImport = (
			`import render from "!vue-loader?vue&type=template!${thisFile.replace(/\\/g, "/")}?type=script!${this.resourcePath.replace(/\\/g, "/")}"\n`
		);
	}

	// script
	let scriptImport = `var script = {}`;
	if (blocks.script) {
		const src = blocks.script.block || resourcePath;
		const attrsQuery = attrsToQuery(blocks.script.options || {}, 'js');
		const query = `?vue&type=script${attrsQuery}${inheritQuery}`;
		const request = stringifyRequest(src + query);
		scriptImport = (
			`import script from "!babel-loader!${thisFile.replace(/\\/g, "/")}?type=script!${this.resourcePath.replace(/\\/g, "/")}"\n`
		);
	}

	if (!blocks.template) {
		throw new Error("Component or page views must have a template block.");
	}

	if (rawQuery.includes("vue")) {
	return `

<template>
${blocks.template.block}
</template>

<script>
${blocks.script ? blocks.script.block : "export default {}"}
</script>

`;
	}

	return `
	const configOptions = {${blocks.config ? blocks.config.block : ""}};

	import vvv from "${this.resourcePath.replace(/\\/g, "/")}?vue"\n

	let oldRender = vvv.render;

	vvv.render = function (createElement) {
		let that = this;

		let configSets = {};

		for (let k in configOptions.options) {
			let val = this.$store.state.websom.data.config["${incomingQuery.packageType}.${incomingQuery.package.toLowerCase()}.${info.name}." + k];

			if (val)
				configSets[k] = val;
		}

		if (!this.$createElementOverride) {
			this.$createElementOverride = true;

			let old = this._c;
			this._c = function (a, b, c, d) {
				let cls = {};

				if (b && b.staticClass)
					for (let n of b.staticClass.split(" "))
						cls[n] = true;

				/*else if (typeof obj.class == "object") {
					cls = obj.class;
				}else if (typeof obj.class == "array") {
					for (let n of obj.class) {
						if (typeof n == "object")
							cls = {cls, ...n};
						else
							cls[n] = true;
					}
				}*/

				if (that && that.$root.$options.injects && that.$root.$options.injects["${info.name}"]) {
					let exts = that.$root.$options.injects["${info.name}"];

					for (let ext of exts) {
						if (!cls[ext.info.prependTo.replace(".", "")])
							continue;

						if (!that.$websomInjections) {
							that.$websomInjections = {};
						}

						if (!that.$websomInjections[ext.info.name]) {
							that.$websomInjections[ext.info.name] = new ext.vue._Ctor[0]();
						}

						if (that.$websomInjections)
							c.unshift(that.$websomInjections[ext.info.name]._render(createElement));
					}
				}

				return old(a, b, c, d);
			};
		}

		let res = oldRender.call(this, createElement);
		if (!res.data)
			res.data = {};

		if (!res.data.normalizedStyle)
			res.data.normalizedStyle = {};

		if (!res.data.style)
			res.data.style = "";

		let styles = "";
		for (const [key, value] of Object.entries(configOptions.options || {})) {
			let setValue = configSets[key] || value.default || "";
			if (this.config) {
				setValue = this.config[key] || setValue;
			}
			let kebab = key.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
			res.data.normalizedStyle["--" + kebab] = setValue;
			styles += "--" + kebab + ":" + setValue + ";";
		}

		res.data.style = styles + res.data.style;

		return res;
	};

	if (!vvv.props) {
		vvv.props = {};
	}

	if (Array.isArray(vvv.props))
		console.error("Do not use arrays for view prop definitions. Use {} instead.");

	let defaults = {};

	for (let key in (configOptions.options || {})) {
		if (configOptions.options.hasOwnProperty(key))
			defaults[key] = configOptions.options[key].default || "";
	}

	const view = {
		info: {${blocks.info.block}},
		package: ${JSON.stringify(incomingQuery.package) || "\"unknown\""},
		packageType: ${JSON.stringify(incomingQuery.packageType) || "\"unknown\""},
		vue: vvv,
		config: configOptions,
		defaultConfigOptions: defaults
	};

	vvv.props.config = {
		type: Object,
		required: false,
		default: () => { return {}; }
	};

	vvv.props.websomView = {
		type: Object,
		required: false,
		default() {
			return view;
		}
	};

	vvv.$view = view;

	export default view;`;

	let stylesCode = "";

	let outputCode = `
	${templateImport}
	${scriptImport}

	import normalizer from ${stringifyRequest(`!${componentNormalizerPath}`)}
	var component = normalizer(
		script,
		render,
		staticRenderFns,
		false,
		${/injectStyles/.test(stylesCode) ? `injectStyles` : `null`},
		null,
		${isServer ? JSON.stringify(hash(request)) : `null`}
		${isShadow ? `,true` : ``}
	)
	`.trim() + `\n`;

	if (needsHotReload) {
		outputCode += `\n` + genHotReloadCode(id, false, templateRequest);
	}

	if (!isProduction) {
		outputCode += `\ncomponent.options.__file = ${JSON.stringify(rawShortFilePath.replace(/\\/g, '/'))}`;
	} else if (options.exposeFilename) {
		// Libraries can opt-in to expose their components' filenames in production builds.
		// For security reasons, only expose the file's basename in production.
		outputCode += `\ncomponent.options.__file = ${JSON.stringify(filename)}`;
	}

	outputCode += `\nexport default component.exports`;

	return outputCode;
};<|endoftext|>