<commit_before>function deleteCheckSubmit() {

    if (confirm('Are you sure?')) {
        document.forms['deletemenuform'].submit();
    } else {
        return false;
    }
}

function HutLocation(name, lat, lng, imgurl, showurl, linktext, description) {
    this.name = name;
    this.lat = lat;
    this.lng = lng;
    this.showurl = showurl;
    this.imgurl = imgurl;
    this.linktext = linktext;
    this.description = description;
}

function toggleMapList() {
    var oldList = document.getElementById("oldlist");
    var map = document.getElementById("map");

    if (map.style.display == "none") {
        map.style.display = "";
        oldList.style.display = "none";
    } else {
        map.style.display = "none";
        oldList.style.display = "";
    }
}

function toggleMapView() {
    var img = document.getElementById("hutimg");
    var map = document.getElementById("map");

    if (map.style.display == "none") {
        map.style.display = "";
        img.style.display = "none";
    } else {
        map.style.display = "none";
        img.style.display = "";
    }
}

function initializeMaps(hutlocs) {
    //    var norway = new GLatLng(64.830253743883, 16.2158203125);
    var norway = new GLatLng(60, 10.7);

    if (GBrowserIsCompatible()) {
        var map = new google.maps.Map2(document.getElementById("map"));

        map.setCenter(norway, 7);

        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
    } else {
        toggleMapList();
    }

    for (name in hutlocs) {
        var hutloc = hutlocs[name];

        var marker = getMarker(hutloc);

        map.addOverlay(marker);
    }
}

function initializeSingleMap(lat, lng) {
    var point = new GLatLng(lat, lng);

    if (GBrowserIsCompatible()) {
        var map = new google.maps.Map2(document.getElementById("map"));

        map.setCenter(point, 7);

        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
    }

    if (document.getElementById("hutimg")) {
        toggleMapView();
    }

    var marker = new GMarker(point);

    map.addOverlay(marker);
}

function getMarker(hutloc) {
    var marker = new GMarker(new GLatLng(hutloc.lat, hutloc.lng));

    var popup = "
" + hutloc.name + "
";

    if (hutloc.imgurl) {
        popup += "";
    }

    popup += "
" + hutloc.description + "
";
    popup += "
" + hutloc.linktext + "
";

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(popup);
    });

    return marker;
}
<commit_msg>[svn] Back port rescale of map<commit_after>function deleteCheckSubmit() {

    if (confirm('Are you sure?')) {
        document.forms['deletemenuform'].submit();
    } else {
        return false;
    }
}

function HutLocation(name, lat, lng, imgurl, showurl, linktext, description) {
    this.name = name;
    this.lat = lat;
    this.lng = lng;
    this.showurl = showurl;
    this.imgurl = imgurl;
    this.linktext = linktext;
    this.description = description;
}

function toggleMapList() {
    var oldList = document.getElementById("oldlist");
    var map = document.getElementById("map");

    if (map.style.display == "none") {
        map.style.display = "";
        oldList.style.display = "none";
    } else {
        map.style.display = "none";
        oldList.style.display = "";
    }
}

function toggleMapView() {
    var img = document.getElementById("hutimg");
    var map = document.getElementById("map");

    if (map.style.display == "none") {
        map.style.display = "";
        img.style.display = "none";
    } else {
        map.style.display = "none";
        img.style.display = "";
    }
}

function initializeMaps(hutlocs) {
    //    var norway = new GLatLng(64.830253743883, 16.2158203125);
    var norway = new GLatLng(60, 10.7);

    if (GBrowserIsCompatible()) {
        var map = new google.maps.Map2(document.getElementById("map"));

        map.setCenter(norway, 7);

        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
    } else {
        toggleMapList();
    }

    var bounds = new GLatLngBounds();

    for (name in hutlocs) {
        var hutloc = hutlocs[name];

        var marker = getMarker(hutloc, bounds);

        map.addOverlay(marker);
    }

    map.setZoom(map.getBoundsZoomLevel(bounds));

    map.setCenter(bounds.getCenter());
}

function initializeSingleMap(lat, lng) {
    var point = new GLatLng(lat, lng);

    if (GBrowserIsCompatible()) {
        var map = new google.maps.Map2(document.getElementById("map"));

        map.setCenter(point, 7);

        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
    }

    if (document.getElementById("hutimg")) {
        toggleMapView();
    }

    var marker = new GMarker(point);

    map.addOverlay(marker);
}

function getMarker(hutloc, bounds) {
    var latlng = new GLatLng(hutloc.lat, hutloc.lng)
    var marker = new GMarker(latlng);

    bounds.extend(latlng);

    var popup = "
" + hutloc.name + "
";

    if (hutloc.imgurl) {
        popup += "";
    }

    popup += "
" + hutloc.description + "
";
    popup += "
" + hutloc.linktext + "
";

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(popup);
    });

    return marker;
}
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const merge = require('webpack-merge');
const forEach = require('lodash/forEach');
const hasJsonLoader = require('./utils/hasJsonLoader');
const getWebpackVersion = require('./utils/getWebpackVersion');
const mergeWebpackConfig = require('./utils/mergeWebpackConfig');
const StyleguidistOptionsPlugin = require('./utils/StyleguidistOptionsPlugin');

const RENDERER_REGEXP = /Renderer$/;

const isWebpack1 = getWebpackVersion() < 2;
const sourceDir = path.resolve(__dirname, '../lib');
const htmlLoader = require.resolve('html-webpack-plugin/lib/loader');

module.exports = function(config, env) {
	process.env.NODE_ENV = process.env.NODE_ENV || env;

	const isProd = env === 'production';

	let webpackConfig = {
		entry: config.require.concat([path.resolve(sourceDir, 'index')]),
		output: {
			path: config.styleguideDir,
			filename: 'build/[name].bundle.js',
			chunkFilename: 'build/[name].js',
		},
		resolve: {
			extensions: isWebpack1 ? ['.js', '.jsx', '.json', ''] : ['.js', '.jsx', '.json'],
			alias: {
				'rsg-codemirror-theme.css': `codemirror/theme/${config.highlightTheme}.css`,
			},
		},
		plugins: [
			new StyleguidistOptionsPlugin(config),
			new HtmlWebpackPlugin({
				title: config.title,
				template: `!!${htmlLoader}!${config.template}`,
				inject: true,
			}),
			new webpack.DefinePlugin({
				'process.env': {
					NODE_ENV: JSON.stringify(env),
				},
			}),
		],
		performance: {
			hints: false,
		},
	};

	if (isProd) {
		webpackConfig = merge(webpackConfig, {
			output: {
				filename: 'build/bundle.[chunkhash:8].js',
				chunkFilename: 'build/[name].[chunkhash:8].js',
			},
			plugins: [
				new webpack.optimize.OccurrenceOrderPlugin(),
				new webpack.optimize.UglifyJsPlugin({
					compress: {
						keep_fnames: true,
						screw_ie8: true,
						warnings: false,
					},
					output: {
						comments: false,
					},
					mangle: {
						keep_fnames: true,
					},
				}),
				new CleanWebpackPlugin(['build'], {
					root: config.styleguideDir,
					verbose: config.verbose,
				}),
				new CopyWebpackPlugin([
					{
						from: config.assetsDir,
					},
				]),
			],
		});
		if (isWebpack1) {
			webpackConfig.plugins.push(new webpack.optimize.DedupePlugin());
		}
	} else {
		webpackConfig = merge(webpackConfig, {
			entry: [require.resolve('react-dev-utils/webpackHotDevClient')],
			stats: {
				colors: true,
				reasons: true,
			},
			plugins: [new webpack.HotModuleReplacementPlugin()],
		});
	}

	if (config.webpackConfig) {
		webpackConfig = mergeWebpackConfig(webpackConfig, config.webpackConfig, env);
	}

	// Add JSON loader if user config has no one (Webpack 2 includes it by default)
	if (isWebpack1 && !hasJsonLoader(webpackConfig)) {
		webpackConfig = merge(webpackConfig, {
			module: {
				loaders: [
					{
						test: /\.json$/,
						loader: 'json-loader',
					},
				],
			},
		});
	}

	// Custom style guide components
	if (config.styleguideComponents) {
		forEach(config.styleguideComponents, (filepath, name) => {
			const fullName = name.match(RENDERER_REGEXP)
				? `${name.replace(RENDERER_REGEXP, '')}/${name}`
				: name;
			webpackConfig.resolve.alias[`rsg-components/${fullName}`] = filepath;
		});
	}

	// Add components folder alias at the end so users can override our components to customize the style guide
	// (their aliases should be before this one)
	webpackConfig.resolve.alias['rsg-components'] = path.resolve(sourceDir, 'rsg-components');

	if (config.dangerouslyUpdateWebpackConfig) {
		webpackConfig = config.dangerouslyUpdateWebpackConfig(webpackConfig, env);
	}

	return webpackConfig;
};
<commit_msg>Fix: Skip CopyWebpackPlugin when assetsDir config option is not defined<commit_after>'use strict';

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const merge = require('webpack-merge');
const forEach = require('lodash/forEach');
const hasJsonLoader = require('./utils/hasJsonLoader');
const getWebpackVersion = require('./utils/getWebpackVersion');
const mergeWebpackConfig = require('./utils/mergeWebpackConfig');
const StyleguidistOptionsPlugin = require('./utils/StyleguidistOptionsPlugin');

const RENDERER_REGEXP = /Renderer$/;

const isWebpack1 = getWebpackVersion() < 2;
const sourceDir = path.resolve(__dirname, '../lib');
const htmlLoader = require.resolve('html-webpack-plugin/lib/loader');

module.exports = function(config, env) {
	process.env.NODE_ENV = process.env.NODE_ENV || env;

	const isProd = env === 'production';

	let webpackConfig = {
		entry: config.require.concat([path.resolve(sourceDir, 'index')]),
		output: {
			path: config.styleguideDir,
			filename: 'build/[name].bundle.js',
			chunkFilename: 'build/[name].js',
		},
		resolve: {
			extensions: isWebpack1 ? ['.js', '.jsx', '.json', ''] : ['.js', '.jsx', '.json'],
			alias: {
				'rsg-codemirror-theme.css': `codemirror/theme/${config.highlightTheme}.css`,
			},
		},
		plugins: [
			new StyleguidistOptionsPlugin(config),
			new HtmlWebpackPlugin({
				title: config.title,
				template: `!!${htmlLoader}!${config.template}`,
				inject: true,
			}),
			new webpack.DefinePlugin({
				'process.env': {
					NODE_ENV: JSON.stringify(env),
				},
			}),
		],
		performance: {
			hints: false,
		},
	};

	if (isProd) {
		webpackConfig = merge(webpackConfig, {
			output: {
				filename: 'build/bundle.[chunkhash:8].js',
				chunkFilename: 'build/[name].[chunkhash:8].js',
			},
			plugins: [
				new webpack.optimize.OccurrenceOrderPlugin(),
				new webpack.optimize.UglifyJsPlugin({
					compress: {
						keep_fnames: true,
						screw_ie8: true,
						warnings: false,
					},
					output: {
						comments: false,
					},
					mangle: {
						keep_fnames: true,
					},
				}),
				new CleanWebpackPlugin(['build'], {
					root: config.styleguideDir,
					verbose: config.verbose,
				}),
				new CopyWebpackPlugin(
					config.assetsDir
						? [
								{
									from: config.assetsDir,
								},
							]
						: []
				),
			],
		});
		if (isWebpack1) {
			webpackConfig.plugins.push(new webpack.optimize.DedupePlugin());
		}
	} else {
		webpackConfig = merge(webpackConfig, {
			entry: [require.resolve('react-dev-utils/webpackHotDevClient')],
			stats: {
				colors: true,
				reasons: true,
			},
			plugins: [new webpack.HotModuleReplacementPlugin()],
		});
	}

	if (config.webpackConfig) {
		webpackConfig = mergeWebpackConfig(webpackConfig, config.webpackConfig, env);
	}

	// Add JSON loader if user config has no one (Webpack 2 includes it by default)
	if (isWebpack1 && !hasJsonLoader(webpackConfig)) {
		webpackConfig = merge(webpackConfig, {
			module: {
				loaders: [
					{
						test: /\.json$/,
						loader: 'json-loader',
					},
				],
			},
		});
	}

	// Custom style guide components
	if (config.styleguideComponents) {
		forEach(config.styleguideComponents, (filepath, name) => {
			const fullName = name.match(RENDERER_REGEXP)
				? `${name.replace(RENDERER_REGEXP, '')}/${name}`
				: name;
			webpackConfig.resolve.alias[`rsg-components/${fullName}`] = filepath;
		});
	}

	// Add components folder alias at the end so users can override our components to customize the style guide
	// (their aliases should be before this one)
	webpackConfig.resolve.alias['rsg-components'] = path.resolve(sourceDir, 'rsg-components');

	if (config.dangerouslyUpdateWebpackConfig) {
		webpackConfig = config.dangerouslyUpdateWebpackConfig(webpackConfig, env);
	}

	return webpackConfig;
};
<|endoftext|>


<commit_before>
exports.Reader = Reader
exports.Writer = Writer

var fs = require("graceful-fs")
  , Stream = require("stream").Stream
  , inherits = require("inherits")
  , rimraf = require("rimraf")
  , mkdir = require("mkdirp")
  , path = require("path")
  , umask = process.umask()
  , dirmode = 0777 & (~umask)
  , filemode = 0644 & (~umask)

function Reader (opts) {
  if (typeof opts === "string") opts = { path: opts }

  var me = this
  if (!(me instanceof Reader)) return new Reader(opts)
  Stream.call(me)
  me.readable = true
  me.writable = false

  if (!opts.path) {
    return me.emit("error", new Error("path option is required"))
  }

  var stat = opts.follow ? "stat" : "lstat"
  me.filter = typeof opts.filter === "function" ? opts.filter : null
  me.depth = opts.depth || 0
  me.parent = opts.parent || null
  me.root = opts.root || (opts.parent && opts.parent.root) || me
  me.path = opts.path
  me.basename = path.basename(opts.path)
  me.dirname = path.dirname(opts.path)

  fs[stat](me.path, function (er, props) {
    if (er) return me.emit("error", er)
    me.props = props
    me.type = getType(props)

    // if the filter doesn't pass, then just skip over this one.
    // still have to emit end so that dir-walking can move on.
    if (me.filter) {
      var ret = me.filter()
      if (!ret) return me.emit("end")
    }

    me.emit("stat", props)

    // if it's a directory, then we'll be emitting "file" events.
    if (props.isDirectory()) {
      dirWalk(me)
      return
    } else if (props.isSymbolicLink()) {
      readlink(me)
      return
    }

    // TODO: special handling for character devices, block devices,
    // FIFO's, sockets.  They stat as size=0, but emit all sorts of data.

    // if it's got a zero-size, then just emit "end" right now
    if (props.size === 0) {
      me.emit("end")
      return
    }

    // otherwise, set up a readable stream for it.
    // TODO: Check that the bytesEmitted at the end matches
    // the expected size.
    var s = me._stream = fs.createReadStream(me.path, opts)
    proxyEvents(["open", "error", "data", "end", "close"], s, me)
  })
}

inherits(Reader, Stream)

function readlink (me) {
  fs.readlink(me.path, function (er, lp) {
    if (er) return me.emit("error", er)
    me.emit("linkpath", lp)
    me.emit("end")
  })
}

function dirWalk (me) {
  fs.readdir(me.path, function (er, entries) {
    if (er) return me.emit("error", er)
    me.emit("entries", entries)

    // now, go through all the entries and create Readers for them
    // Use the same filter, if one was provided, so that we don't
    // dive into directories that are excluded.
    var len = entries.length
      , f = 0

    ;(function walk () {
      if (f === len) return me.emit("end")
      var fst = Reader({ path: path.resolve(me.path, entries[f])
                       , filter: me.filter
                       , depth: me.depth + 1
                       , root: me.root
                       , parent: me })

      fst.on("error", function (e) {
        me.emit("error", e)
      })

      fst.on("stat", function (p) {
        me.emit("entry", fst)
      })

      // bubble up
      fst.on("entry", function (entry) {
        me.emit("entry", entry)
      })

      fst.on("end", function () {
        f ++
        walk()
      })
    })()
  })
}

function proxyEvents (evs, from, to) {
  evs.forEach(function (ev) {
    from.on(ev, function () {
      var l = arguments.length
        , args = new Array(l + 1)
      args[0] = ev
      for (var i = 0, l = arguments.length; i < l; i ++) {
        args[i + 1] = arguments[i]
      }
      to.emit.apply(to, args)
    })
  })
}

Reader.prototype.pipe = function (dest, opts) {
  var me = this
  if (typeof dest.add === "function") {
    // piping to a multi-compatible, and we've got directory entries.
    me.on("entry", function (entry) {
      dest.add(entry)
    })
  }

  Stream.prototype.pipe.apply(this, arguments)
}

Reader.prototype.pause = function () {
  if (this._stream) this._stream.pause()
}

Reader.prototype.resume = function () {
  if (this._stream) this._stream.resume()
}

function Writer (props) {
  var me = this
  if (!(me instanceof Writer)) return new Writer(props)
  Stream.call(me)

  if (typeof props === "string") {
    props = { path: props }
  }

  if (!props.path) {
    me.emit("error", new Error("Must provide a path"))
    return
  }

  me.props = props
  me.depth = props.depth || 0
  me.clobber = false === props.clobber ? props.clobber : true
  me.parent = props.parent || null
  me.root = props.root || (props.parent && props.parent.root) || me
  me.path = props.path
  me.basename = path.basename(props.path)
  me.dirname = path.dirname(props.path)
  me.linkpath = props.linkpath || null

  me.readable = false
  me.writable = true

  // buffer until stat
  me._buffer = []
  me._ready = false

  var stat = props.follow ? "stat" : "lstat"

  fs[stat](props.path, function (er, current) {
    // if it's not there, great.  We'll just create it.
    // if it is there, then we'll need to change whatever differs
    // if we can't modify what needs modifying, then error on it.

    // try to figure out what kind of type it is.
    // We can actually only create directories, files, and symlinks,
    // so if it's a block/character device or fifo, then abort.
    // However, if it's a fifo or device or socket, and we're not
    // *changing* it, then that's fine, since we might just be writing
    // data into it.
    //
    // If it wants to be a directory or file or symlink, and is currently
    // anything else, then clobber it.
    var changeType = true
      , currentType = current ? getType(current) : null
      , wantedType = me.type = getType(props) || currentType || "File"
      , creatable = wantedType === "Directory" ||
                    wantedType === "File" ||
                    wantedType === "SymbolicLink"
      , recreate = wantedType !== currentType

    Object.keys(current || {}).forEach(function (k) {
      if (!props.hasOwnProperty(k)) props[k] = current[k]
    })

    me._old = current

    if (!recreate) {
      if (wantedType == "File") create(me)
      else setProps(me, current)
      return
    }

    if (wantedType === "SymbolicLink" && !me.linkpath) {
      return me.emit("error", new Error(
        "Cannot create symlink without linkpath"))
    }

    if (!creatable) {
      return me.emit("error", new Error(
        "Cannot create filetype: " + wantedType))
    }

    clobber(me)
  })
}

inherits(Writer, Stream)

function clobber (me) {
  rimraf(me.path, function (er) {
    if (er) return me.emit("error", er)
    create(me)
  })
}

function create (me) {
  if (typeof me.props.mode !== "number") {
    me.props.mode = (me.type === "Directory" ? 0777 : 0666) & (~umask)
  }

  mkdir(me.dirname, dirmode, function (er) {
    if (er) return me.emit("error", me)

    switch (me.type) {
      case "Directory":
        mkdir(me.path, me.props.mode & 0777, next)
        break

      case "SymbolicLink":
        fs.symlink(me.path, me.linkpath, next)
        break

      case "File":
        var s = me._stream = fs.createWriteStream(me.path, me.props)
        proxyEvents(["open", "error", "drain", "close"], s, me)
        me._stream.on("open", function (fd) {
          next()
        })
        break

      default:
        return me.emit("error", new Error("Cannot create type: "+me.type))
    }
  })

  function next (er) {
    if (er) return me.emit("error", er)
    fs[me.follow ? "stat" : "lstat"](me.path, function (er, stat) {
      if (er) return me.emit("error", er)
      me._old = stat
      setProps(me, stat)
    })
  }
}

function setProps (me, current) {
  // set up all the things.
  var todo = 0
  var errState = null

  // mode
  var wantMode = me.props.mode
  if (typeof wantMode === "number") {
    wantMode = wantMode & 0777
    var curMode = current.mode & 0777
    if (wantMode !== curMode) {
      todo ++
      if (me._stream && me._stream.fd && fs.fchmod) {
        fs.fchmod(me._stream.fd, wantMode, next)
      } else {
        fs.chmod(me.path, wantMode, next)
      }
    }
  }

  // uid, gid
  if (typeof me.props.uid === "number" || typeof me.props.gid === "number") {
    if (typeof me.props.uid !== "number") me.props.uid = current.uid
    if (typeof me.props.gid !== "number") me.props.gid = current.gid
    if (me.props.uid !== current.uid || me.props.gid !== current.gid) {
      todo ++
      if (me._stream && me._stream.fd && fs.fchown) {
        fs.fchown(me._stream.fd, me.props.uid, me.props.gid, next)
      } else {
        fs.chown(me.path, me.props.uid, me.props.gid, next)
      }
    }
  }

  // atime, mtime.
  if (fs.utimes) {
    var curA = current.atime
      , curM = current.mtime
      , meA = me.props.atime
      , meM = me.props.mtime

    if (meA === undefined) meA = curA
    if (meM === undefined) meM = curM

    if (!isDate(meA)) meA = new Date(meA)
    if (!isDate(meM)) meA = new Date(meM)

    if (meA.getTime() !== curA.getTime() ||
        meM.getTime() !== curM.getTime()) {
      todo ++
      if (me._stream && me._stream.fd && fs.futimes) {
        fs.futimes(me._stream.fd, meA, meM, next)
      } else {
        fs.utimes(me.path, meA, meM, next)
      }
    }
  }

  // finally, handle the case if there was nothing to do.
  if (todo === 0) next()

  function next (er) {
    if (errState) return
    if (er) return me.emit("error", errState = er)
    if (--todo > 0) return

    // all the props have been set, now see if we got any pending writes
    // in the meantime.
    me._ready = true
    var buffer = me._buffer
    if (buffer.length) {
      me._buffer = []
      buffer.forEach(function (c) {
        me[c[0]](c[1])
      })
    }
  }
}

function objectToString (d) {
  return Object.prototype.toString.call(d)
}

function isDate(d) {
  return typeof d === 'object' && objectToString(d) === '[object Date]';
}

Writer.prototype.pipe = function () {
  this.emit("error", new Error("Can't pipe from writable stream"))
}

Writer.prototype.write = function (c) {
  var me = this

  if (me._ended) {
    me.emit("error", new Error("write after end"))
    return false
  }

  if (!me._ready || me._buffer.length) {
    me._buffer.push(["write", c])
    me._needsDrain = true
    return false
  }

  if (me.type !== "File") {
    // just ignore writes to non-File types.
    // some tar entries contain metadata for directories
    return true
  }

  return me._stream.write(c)
}

// create a subfolder underneath this one
Writer.prototype.add = function (entry) {
  var me = this

  if (me._ended) {
    me.emit("error", new Error("add after end"))
    return false
  }

  if (!me._ready || me._buffer.length) {
    me._buffer.push(["add", entry])
    me._needsDrain = true
    return false
  }

  if (me._ended) {
    me.emit("error", new Error("write after end"))
    return false
  }

  if (me.type !== "Directory") {
    // can't add sub-entries to a non-dir type
    me.emit("error", new Error("can't add to non-Directory type"))
    return
  }

  // don't allow recursive copying!
  var p = entry
  do {
    if (p.path === me.path) return
  } while (p = p.parent)

  // chop the entry's parent's dir
  var opts = { parent: me
             , root: me.root || me
             , type: entry.type
             , depth: me.depth + 1 }

  var p = entry.path
    , root = entry.root || entry.parent
  if (root) {
    p = p.substr(root.path.length + 1)
  }
  opts.path = path.join(me.path, p)

  var child = new Writer(opts)
  // directories are already handled.
  if (entry.type !== "Directory") {
    entry.pipe(child)
  }

  child.on("entry", function (entry) {
    me.emit("entry", entry)
  })

  child.on("stat", function () {
    me.emit("entry", child)
  })
}

Writer.prototype.end = function (c) {
  var me = this
  if (c) me.write(c)
  if (me._stream) me._stream.end()
  me._ended = true
}

function getType (st) {
  var types =
      [ "Directory"
      , "File"
      , "SymbolicLink"
      , "BlockDevice"
      , "CharacterDevice"
      , "FIFO"
      , "Socket" ]
    , type

  if (st.type && -1 !== types.indexOf(st.type)) {
    return st.type
  }

  for (var i = 0, l = types.length; i < l; i ++) {
    type = types[i]
    var is = st[type] || st["is" + type]
    if (typeof is === "function") is = is.call(st)
    if (is) {
      st[type] = true
      st.type = type
      return type
    }
  }

  return null
}
<commit_msg>Set the utimes properly<commit_after>
exports.Reader = Reader
exports.Writer = Writer

var fs = require("graceful-fs")
  , Stream = require("stream").Stream
  , inherits = require("inherits")
  , rimraf = require("rimraf")
  , mkdir = require("mkdirp")
  , path = require("path")
  , umask = process.umask()
  , dirmode = 0777 & (~umask)
  , filemode = 0644 & (~umask)

function Reader (opts) {
  if (typeof opts === "string") opts = { path: opts }

  var me = this
  if (!(me instanceof Reader)) return new Reader(opts)
  Stream.call(me)
  me.readable = true
  me.writable = false

  if (!opts.path) {
    return me.emit("error", new Error("path option is required"))
  }

  var stat = opts.follow ? "stat" : "lstat"
  me.filter = typeof opts.filter === "function" ? opts.filter : null
  me.depth = opts.depth || 0
  me.parent = opts.parent || null
  me.root = opts.root || (opts.parent && opts.parent.root) || me
  me.path = opts.path
  me.basename = path.basename(opts.path)
  me.dirname = path.dirname(opts.path)

  fs[stat](me.path, function (er, props) {
    if (er) return me.emit("error", er)
    me.props = props
    me.type = getType(props)

    // if the filter doesn't pass, then just skip over this one.
    // still have to emit end so that dir-walking can move on.
    if (me.filter) {
      var ret = me.filter()
      if (!ret) return me.emit("end")
    }

    me.emit("stat", props)

    // if it's a directory, then we'll be emitting "file" events.
    if (props.isDirectory()) {
      dirWalk(me)
      return
    } else if (props.isSymbolicLink()) {
      readlink(me)
      return
    }

    // TODO: special handling for character devices, block devices,
    // FIFO's, sockets.  They stat as size=0, but emit all sorts of data.

    // if it's got a zero-size, then just emit "end" right now
    if (props.size === 0) {
      me.emit("end")
      return
    }

    // otherwise, set up a readable stream for it.
    // TODO: Check that the bytesEmitted at the end matches
    // the expected size.
    var s = me._stream = fs.createReadStream(me.path, opts)
    proxyEvents(["open", "error", "data", "end", "close"], s, me)
  })
}

inherits(Reader, Stream)

function readlink (me) {
  fs.readlink(me.path, function (er, lp) {
    if (er) return me.emit("error", er)
    me.emit("linkpath", lp)
    me.emit("end")
  })
}

function dirWalk (me) {
  fs.readdir(me.path, function (er, entries) {
    if (er) return me.emit("error", er)
    me.emit("entries", entries)

    // now, go through all the entries and create Readers for them
    // Use the same filter, if one was provided, so that we don't
    // dive into directories that are excluded.
    var len = entries.length
      , f = 0

    ;(function walk () {
      if (f === len) return me.emit("end")
      var fst = Reader({ path: path.resolve(me.path, entries[f])
                       , filter: me.filter
                       , depth: me.depth + 1
                       , root: me.root
                       , parent: me })

      fst.on("error", function (e) {
        me.emit("error", e)
      })

      fst.on("stat", function (p) {
        me.emit("entry", fst)
      })

      // bubble up
      fst.on("entry", function (entry) {
        me.emit("entry", entry)
      })

      fst.on("end", function () {
        f ++
        walk()
      })
    })()
  })
}

function proxyEvents (evs, from, to) {
  evs.forEach(function (ev) {
    from.on(ev, function () {
      var l = arguments.length
        , args = new Array(l + 1)
      args[0] = ev
      for (var i = 0, l = arguments.length; i < l; i ++) {
        args[i + 1] = arguments[i]
      }
      to.emit.apply(to, args)
    })
  })
}

Reader.prototype.pipe = function (dest, opts) {
  var me = this
  if (typeof dest.add === "function") {
    // piping to a multi-compatible, and we've got directory entries.
    me.on("entry", function (entry) {
      dest.add(entry)
    })
  }

  Stream.prototype.pipe.apply(this, arguments)
}

Reader.prototype.pause = function () {
  if (this._stream) this._stream.pause()
}

Reader.prototype.resume = function () {
  if (this._stream) this._stream.resume()
}

function Writer (props) {
  var me = this
  if (!(me instanceof Writer)) return new Writer(props)
  Stream.call(me)

  if (typeof props === "string") {
    props = { path: props }
  }

  if (!props.path) {
    me.emit("error", new Error("Must provide a path"))
    return
  }

  me.props = props
  me.depth = props.depth || 0
  me.clobber = false === props.clobber ? props.clobber : true
  me.parent = props.parent || null
  me.root = props.root || (props.parent && props.parent.root) || me
  me.path = props.path
  me.basename = path.basename(props.path)
  me.dirname = path.dirname(props.path)
  me.linkpath = props.linkpath || null

  me.readable = false
  me.writable = true

  // buffer until stat
  me._buffer = []
  me._ready = false

  var stat = props.follow ? "stat" : "lstat"

  fs[stat](props.path, function (er, current) {
    // if it's not there, great.  We'll just create it.
    // if it is there, then we'll need to change whatever differs
    // if we can't modify what needs modifying, then error on it.

    // try to figure out what kind of type it is.
    // We can actually only create directories, files, and symlinks,
    // so if it's a block/character device or fifo, then abort.
    // However, if it's a fifo or device or socket, and we're not
    // *changing* it, then that's fine, since we might just be writing
    // data into it.
    //
    // If it wants to be a directory or file or symlink, and is currently
    // anything else, then clobber it.
    var changeType = true
      , currentType = current ? getType(current) : null
      , wantedType = me.type = getType(props) || currentType || "File"
      , creatable = wantedType === "Directory" ||
                    wantedType === "File" ||
                    wantedType === "SymbolicLink"
      , recreate = wantedType !== currentType

    Object.keys(current || {}).forEach(function (k) {
      if (!props.hasOwnProperty(k)) props[k] = current[k]
    })

    me._old = current

    if (!recreate) {
      if (wantedType == "File") create(me)
      else setProps(me, current)
      return
    }

    if (wantedType === "SymbolicLink" && !me.linkpath) {
      return me.emit("error", new Error(
        "Cannot create symlink without linkpath"))
    }

    if (!creatable) {
      return me.emit("error", new Error(
        "Cannot create filetype: " + wantedType))
    }

    clobber(me)
  })
}

inherits(Writer, Stream)

function clobber (me) {
  rimraf(me.path, function (er) {
    if (er) return me.emit("error", er)
    create(me)
  })
}

function create (me) {
  if (typeof me.props.mode !== "number") {
    me.props.mode = (me.type === "Directory" ? 0777 : 0666) & (~umask)
  }

  mkdir(me.dirname, dirmode, function (er) {
    if (er) return me.emit("error", me)

    switch (me.type) {
      case "Directory":
        mkdir(me.path, me.props.mode & 0777, next)
        break

      case "SymbolicLink":
        fs.symlink(me.path, me.linkpath, next)
        break

      case "File":
        var s = me._stream = fs.createWriteStream(me.path, me.props)
        proxyEvents(["open", "error", "drain", "close"], s, me)
        me._stream.on("open", function (fd) {
          next()
        })
        break

      default:
        return me.emit("error", new Error("Cannot create type: "+me.type))
    }
  })

  function next (er) {
    if (er) return me.emit("error", er)
    fs[me.follow ? "stat" : "lstat"](me.path, function (er, stat) {
      if (er) return me.emit("error", er)
      me._old = stat
      setProps(me, stat)
    })
  }
}

function setProps (me, current) {
  // set up all the things.
  var todo = 0
  var errState = null
  var done = false

  // mode
  var wantMode = me.props.mode
  if (typeof wantMode === "number") {
    wantMode = wantMode & 0777
    var curMode = current.mode & 0777
    if (wantMode !== curMode) {
      todo ++
      if (me._stream && me._stream.fd && fs.fchmod) {
        fs.fchmod(me._stream.fd, wantMode, next)
      } else {
        fs.chmod(me.path, wantMode, next)
      }
    }
  }

  // uid, gid
  if (typeof me.props.uid === "number" || typeof me.props.gid === "number") {
    if (typeof me.props.uid !== "number") me.props.uid = current.uid
    if (typeof me.props.gid !== "number") me.props.gid = current.gid
    if (me.props.uid !== current.uid || me.props.gid !== current.gid) {
      todo ++
      if (me._stream && me._stream.fd && fs.fchown) {
        fs.fchown(me._stream.fd, me.props.uid, me.props.gid, next)
      } else {
        fs.chown(me.path, me.props.uid, me.props.gid, next)
      }
    }
  }

  // atime, mtime.
  if (fs.utimes) {
    var curA = current.atime
      , curM = current.mtime
      , meA = me.props.atime
      , meM = me.props.mtime

    if (meA === undefined) meA = curA
    if (meM === undefined) meM = curM

    if (!isDate(meA)) meA = new Date(meA)
    if (!isDate(meM)) meA = new Date(meM)

    if (meA.getTime() !== curA.getTime() ||
        meM.getTime() !== curM.getTime()) {
      if (me._stream) {
        // can't set them now, since we'll be touching the file.
        me._stream.on("end", setTimes)
        me._stream.on("close", setTimes)
      } else {
        todo ++
        setTimes()
      }
    }

    function setTimes () {
      fs.utimes(me.path, meA, meM, next)
    }
  }

  // finally, handle the case if there was nothing to do.
  if (todo === 0) next()

  function next (er) {
    if (errState) return
    if (er) return me.emit("error", errState = er)
    if (--todo > 0) return
    if (done) return

    done = true

    // all the props have been set, now see if we got any pending writes
    // in the meantime.
    me._ready = true
    var buffer = me._buffer
    if (buffer.length) {
      me._buffer = []
      buffer.forEach(function (c) {
        me[c[0]](c[1])
      })
    }
  }
}

function objectToString (d) {
  return Object.prototype.toString.call(d)
}

function isDate(d) {
  return typeof d === 'object' && objectToString(d) === '[object Date]';
}

Writer.prototype.pipe = function () {
  this.emit("error", new Error("Can't pipe from writable stream"))
}

Writer.prototype.write = function (c) {
  var me = this

  if (me._ended) {
    me.emit("error", new Error("write after end"))
    return false
  }

  if (!me._ready || me._buffer.length) {
    me._buffer.push(["write", c])
    me._needsDrain = true
    return false
  }

  if (me.type !== "File") {
    // just ignore writes to non-File types.
    // some tar entries contain metadata for directories
    return true
  }

  return me._stream.write(c)
}

// create a subfolder underneath this one
Writer.prototype.add = function (entry) {
  var me = this

  if (me._ended) {
    me.emit("error", new Error("add after end"))
    return false
  }

  if (!me._ready || me._buffer.length) {
    me._buffer.push(["add", entry])
    me._needsDrain = true
    return false
  }

  if (me._ended) {
    me.emit("error", new Error("write after end"))
    return false
  }

  if (me.type !== "Directory") {
    // can't add sub-entries to a non-dir type
    me.emit("error", new Error("can't add to non-Directory type"))
    return
  }

  // don't allow recursive copying!
  var p = entry
  do {
    if (p.path === me.path) return
  } while (p = p.parent)

  // chop the entry's parent's dir
  var opts = { parent: me
             , root: me.root || me
             , type: entry.type
             , depth: me.depth + 1 }

  var p = entry.path
    , root = entry.root || entry.parent
  if (root) {
    p = p.substr(root.path.length + 1)
  }
  opts.path = path.join(me.path, p)

  // all the rest of the stuff, copy over from the source.
  Object.keys(entry.props).forEach(function (k) {
    if (!opts.hasOwnProperty(k)) {
      opts[k] = entry.props[k]
    }
  })

  var child = new Writer(opts)
  // directories are already handled.
  if (entry.type !== "Directory") {
    entry.pipe(child)
  }

  child.on("entry", function (entry) {
    me.emit("entry", entry)
  })

  child.on("stat", function () {
    me.emit("entry", child)
  })
}

Writer.prototype.end = function (c) {
  var me = this
  if (c) me.write(c)
  if (me._stream) me._stream.end()
  me._ended = true
}

function getType (st) {
  var types =
      [ "Directory"
      , "File"
      , "SymbolicLink"
      , "BlockDevice"
      , "CharacterDevice"
      , "FIFO"
      , "Socket" ]
    , type

  if (st.type && -1 !== types.indexOf(st.type)) {
    return st.type
  }

  for (var i = 0, l = types.length; i < l; i ++) {
    type = types[i]
    var is = st[type] || st["is" + type]
    if (typeof is === "function") is = is.call(st)
    if (is) {
      st[type] = true
      st.type = type
      return type
    }
  }

  return null
}
<|endoftext|>


<commit_before>'use strict';

const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = (env = {}) =>
  merge(common, {
    devtool: 'cheap-module-source-map',
    mode: 'development',

    entry: {
      app: './public/app/index.ts',
      dark: './public/sass/grafana.dark.scss',
      light: './public/sass/grafana.light.scss',
    },

    // If we enabled watch option via CLI
    watchOptions: {
      ignored: /node_modules/,
    },

    module: {
      // Note: order is bottom-to-top and/or right-to-left
      rules: [
        {
          test: /\.tsx?$/,
          exclude: /node_modules/,
          use: [
            {
              loader: 'babel-loader',
              options: {
                cacheDirectory: true,
                babelrc: false,
                // Note: order is top-to-bottom and/or left-to-right
                plugins: [
                  [
                    require('@rtsao/plugin-proposal-class-properties'),
                    {
                      loose: true,
                    },
                  ],
                  '@babel/plugin-proposal-nullish-coalescing-operator',
                  '@babel/plugin-proposal-optional-chaining',
                  'angularjs-annotate',
                ],
                // Note: order is bottom-to-top and/or right-to-left
                presets: [
                  [
                    '@babel/preset-env',
                    {
                      targets: {
                        browsers: 'last 3 versions',
                      },
                      useBuiltIns: 'entry',
                      corejs: 3,
                      modules: false,
                    },
                  ],
                  [
                    '@babel/preset-typescript',
                    {
                      allowNamespaces: true,
                    },
                  ],
                  '@babel/preset-react',
                ],
              },
            },
            {
              loader: 'eslint-loader',
              options: {
                emitError: true,
                emitWarning: true,
              },
            },
          ],
        },
        require('./sass.rule.js')({
          sourceMap: false,
          preserveUrl: false,
        }),
        {
          test: /\.(png|jpg|gif|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
          loader: 'file-loader',
        },
      ],
    },

    plugins: [
      new CleanWebpackPlugin(),
      env.noTsCheck
        ? new webpack.DefinePlugin({}) // bogus plugin to satisfy webpack API
        : new ForkTsCheckerWebpackPlugin({
            checkSyntacticErrors: true,
          }),
      new MiniCssExtractPlugin({
        filename: 'grafana.[name].[hash].css',
      }),
      new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, '../../public/views/error.html'),
        template: path.resolve(__dirname, '../../public/views/error-template.html'),
        inject: false,
        chunksSortMode: 'none',
        excludeChunks: ['dark', 'light'],
      }),
      new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, '../../public/views/index.html'),
        template: path.resolve(__dirname, '../../public/views/index-template.html'),
        inject: false,
        chunksSortMode: 'none',
        excludeChunks: ['dark', 'light'],
      }),
      new webpack.NamedModulesPlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('development'),
        },
      }),
      // new BundleAnalyzerPlugin({
      //   analyzerPort: 8889
      // })
    ],
  });
<commit_msg>Webpack: Do not clean webpack output on every rebuild (#23157)<commit_after>'use strict';

const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = (env = {}) =>
  merge(common, {
    devtool: 'cheap-module-source-map',
    mode: 'development',

    entry: {
      app: './public/app/index.ts',
      dark: './public/sass/grafana.dark.scss',
      light: './public/sass/grafana.light.scss',
    },

    // If we enabled watch option via CLI
    watchOptions: {
      ignored: /node_modules/,
    },

    module: {
      // Note: order is bottom-to-top and/or right-to-left
      rules: [
        {
          test: /\.tsx?$/,
          exclude: /node_modules/,
          use: [
            {
              loader: 'babel-loader',
              options: {
                cacheDirectory: true,
                babelrc: false,
                // Note: order is top-to-bottom and/or left-to-right
                plugins: [
                  [
                    require('@rtsao/plugin-proposal-class-properties'),
                    {
                      loose: true,
                    },
                  ],
                  '@babel/plugin-proposal-nullish-coalescing-operator',
                  '@babel/plugin-proposal-optional-chaining',
                  'angularjs-annotate',
                ],
                // Note: order is bottom-to-top and/or right-to-left
                presets: [
                  [
                    '@babel/preset-env',
                    {
                      targets: {
                        browsers: 'last 3 versions',
                      },
                      useBuiltIns: 'entry',
                      corejs: 3,
                      modules: false,
                    },
                  ],
                  [
                    '@babel/preset-typescript',
                    {
                      allowNamespaces: true,
                    },
                  ],
                  '@babel/preset-react',
                ],
              },
            },
            {
              loader: 'eslint-loader',
              options: {
                emitError: true,
                emitWarning: true,
              },
            },
          ],
        },
        require('./sass.rule.js')({
          sourceMap: false,
          preserveUrl: false,
        }),
        {
          test: /\.(png|jpg|gif|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
          loader: 'file-loader',
        },
      ],
    },

    plugins: [
      new CleanWebpackPlugin({
        cleanStaleWebpackAssets: false,
      }),
      env.noTsCheck
        ? new webpack.DefinePlugin({}) // bogus plugin to satisfy webpack API
        : new ForkTsCheckerWebpackPlugin({
            checkSyntacticErrors: true,
          }),
      new MiniCssExtractPlugin({
        filename: 'grafana.[name].[hash].css',
      }),
      new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, '../../public/views/error.html'),
        template: path.resolve(__dirname, '../../public/views/error-template.html'),
        inject: false,
        chunksSortMode: 'none',
        excludeChunks: ['dark', 'light'],
      }),
      new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, '../../public/views/index.html'),
        template: path.resolve(__dirname, '../../public/views/index-template.html'),
        inject: false,
        chunksSortMode: 'none',
        excludeChunks: ['dark', 'light'],
      }),
      new webpack.NamedModulesPlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('development'),
        },
      }),
      // new BundleAnalyzerPlugin({
      //   analyzerPort: 8889
      // })
    ],
  });
<|endoftext|>


<commit_before>var BaseIllustrator = require("./base.js");
var Point           = require("./components/point.js");
var Illustration    = require('./components/illustration.js');
var ShapeHouse      = require("./shapes/house.js");
var ShapePlatform   = require("./shapes/platform.js");
var ShapeContainer  = require("./container/specific/districtcontainer.js");

/**
 * Create an District Layout City
 */
class District extends BaseIllustrator {
    constructor(model, options = {}) {
        super(model, options);

        this._rules = [];
        this._model = model;
        this.setOptions(options);
        this.setDefaults({
            'layout.towers': true,

            'house.length': 12,
            'house.width': 12,
            'house.height': 12,
            'house.margin': 3,
            'house.color': 0x1A212E,

            'platform.height': 10,
            'platform.color': 0x000000,

            'district.container': ShapeContainer,
            'district.options': {}
        });
    }

    draw(version) {
        var spatialModel = this._createSpatialModel(this._model.tree, version);

        var origin = new Point(0, 0, 0);
        var rotation = 0;
        spatialModel.draw(origin, rotation);

        var illustration = new Illustration(version);
        for (var shape of spatialModel.getSpatialInformation()) {
            illustration.addShape(shape);
        }

        return illustration;
    }

    _createSpatialModel(tree, version) {
        if (!tree.children.length) {
            return this._createHouse(tree, version);
        }

        if (!this.getOption('layout.towers') &&
            tree.children.length === 1 &&
            tree.children[0].children.length) {
            return this._createSpatialModel(tree.children[0], version)
        }

        const cClass = this.getOption('district.container');
        const container = new cClass(tree, this.getOption('district.options'));
        container.add(this._createPlatform(tree, version));

        for (const child of tree.children) {
            container.add(this._createSpatialModel(child, version));
        }

        return container;
    }

    _createHouse(node, version) {
        var defaultLayout = {
            'dimensions.length': this.getOption('house.length'),
            'dimensions.width': this.getOption('house.width'),
            'dimensions.height': this.getOption('house.height'),
            'margin': this.getOption('house.margin'),
            'color': this.getOption('house.color')
        };

        var house = new ShapeHouse(node);
        house.updateAttributes(Object.assign(defaultLayout, this.applyRules(node, this._model, version)));

        return house;
    }

    _createPlatform(node, version) {
        var defaultLayout = {
            'color': this.getOption('platform.color'),
            'dimensions.height': this.getOption('platform.height')
        };

        var platform = new ShapePlatform(node.key + '_p');
        platform.updateAttributes(Object.assign(defaultLayout, this.applyRules(node, this._model, version)));

        return platform;
    }
}

module.exports = District;
<commit_msg>consistent naming/key pattern<commit_after>var BaseIllustrator = require("./base.js");
var Point           = require("./components/point.js");
var Illustration    = require('./components/illustration.js');
var ShapeHouse      = require("./shapes/house.js");
var ShapePlatform   = require("./shapes/platform.js");
var ShapeContainer  = require("./container/specific/districtcontainer.js");

/**
 * Create an District Layout City
 */
class District extends BaseIllustrator {
    constructor(model, options = {}) {
        super(model, options);

        this._rules = [];
        this._model = model;
        this.setOptions(options);
        this.setDefaults({
            'layout.towers': true,

            'house.length': 12,
            'house.width': 12,
            'house.height': 12,
            'house.margin': 3,
            'house.color': 0x1A212E,

            'platform.height': 10,
            'platform.color': 0x000000,

            'district.container': ShapeContainer,
            'district.options': {}
        });
    }

    draw(version) {
        var spatialModel = this._createSpatialModel(this._model.tree, version);

        var origin = new Point(0, 0, 0);
        var rotation = 0;
        spatialModel.draw(origin, rotation);

        var illustration = new Illustration(version);
        for (var shape of spatialModel.getSpatialInformation()) {
            illustration.addShape(shape);
        }

        return illustration;
    }

    _createSpatialModel(tree, version) {
        if (!tree.children.length) {
            return this._createHouse(tree, version);
        }

        if (!this.getOption('layout.towers') &&
            tree.children.length === 1 &&
            tree.children[0].children.length) {
            return this._createSpatialModel(tree.children[0], version)
        }

        const cClass = this.getOption('district.container');
        const container = new cClass(tree + '_c', this.getOption('district.options'));
        container.add(this._createPlatform(tree, version));

        for (const child of tree.children) {
            container.add(this._createSpatialModel(child, version));
        }

        return container;
    }

    _createHouse(node, version) {
        var defaultLayout = {
            'dimensions.length': this.getOption('house.length'),
            'dimensions.width': this.getOption('house.width'),
            'dimensions.height': this.getOption('house.height'),
            'margin': this.getOption('house.margin'),
            'color': this.getOption('house.color')
        };

        var house = new ShapeHouse(node);
        house.updateAttributes(Object.assign(defaultLayout, this.applyRules(node, this._model, version)));

        return house;
    }

    _createPlatform(node, version) {
        var defaultLayout = {
            'color': this.getOption('platform.color'),
            'dimensions.height': this.getOption('platform.height')
        };

        var platform = new ShapePlatform(node);
        platform.updateAttributes(Object.assign(defaultLayout, this.applyRules(node, this._model, version)));

        return platform;
    }
}

module.exports = District;
<|endoftext|>


<commit_before>import {Image, load} from 'test/common';
import Canvas from 'canvas';
import 'should';

describe('Image core', function () {
    it('constructor defaults', function () {
        let img = new Image();
        img.width.should.equal(1);
        img.height.should.equal(1);
        img.data.length.should.equal(4);
    });

    it('invalid constructor use', function () {
        (function () {
            new Image(0, 0);
        }).should.throw(/width must be greater than 0/);
        (function () {
            new Image(5, 0);
        }).should.throw(/height must be greater than 0/);
        (function () {
            new Image(10, 10, {kind: 'BLABLA'});
        }).should.throw(/invalid image kind: BLABLA/);
    });

    it('create from Canvas', function () {
        let canvas = new Canvas(2, 2);
        let ctx = canvas.getContext('2d');
        ctx.fillStyle = 'red';
        ctx.fillRect(0, 0, 2, 1);
        let img = Image.fromCanvas(canvas);
        Array.from(img.data).should.eql([
            255,   0,   0, 255, 255,   0,   0, 255,
            0,   0,   0,   0,   0,   0,   0,   0
        ]);
    });

    it('should load from URL', function () {
        return load('format/rgba32.png').then(function (img) {
            img.width.should.be.greaterThan(0);
            img.height.should.be.greaterThan(0);
            img.maxValue.should.equal(255);
        });
    });

    it('should load from dataURL', function () {
        // a red dot
        const dataURL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
        return Image.load(dataURL).then(img => {
            img.width.should.equal(5);
            img.height.should.equal(5);
        });
    });

    it('should clone', function () {
        return load('format/rgba32.png').then(function (img) {
            let clone = img.clone();
            clone.should.be.an.instanceOf(Image);
            clone.should.not.be.equal(img);
            clone.toDataURL().should.equal(img.toDataURL());
        });
    });

    it('isImage', function () {
        const image = new Image(5, 5);
        Image.isImage(image).should.be.true();
        Image.isImage().should.be.false();
        Image.isImage({}).should.be.false();
    });
});
<commit_msg>test: add some image creation and clone tests<commit_after>import {Image, load} from 'test/common';
import Canvas from 'canvas';
import 'should';

describe('Image core', () => {
    it('constructor defaults', () => {
        let img = new Image();
        img.width.should.equal(1);
        img.height.should.equal(1);
        img.data.length.should.equal(4);
    });

    it('invalid constructor use', () => {
        (function () {
            new Image(0, 0);
        }).should.throw(/width must be greater than 0/);
        (function () {
            new Image(5, 0);
        }).should.throw(/height must be greater than 0/);
        (function () {
            new Image(10, 10, {kind: 'BLABLA'});
        }).should.throw(/invalid image kind: BLABLA/);
    });

    it('construct with a kind', () => {
        const img = new Image(1, 1, {kind: 'RGB'});
        expect(img.data.length).toBe(3);
    });

    it('construct a 32bit image', () => {
        const img = new Image(1, 1, {bitDepth: 32});
        expect(img.bitDepth).toBe(32);
        expect(img.data).toBeInstanceOf(Float32Array);
        expect(img.maxValue).toBe(Number.MAX_VALUE);
    });

    it('wrong array passed to setData', () => {
        const img = new Image(1, 1);
        expect(() => {
            img.setData([1])
        }).toThrow('incorrect data size. Should be 4 and found 1');
    });

    it('create from Canvas', () => {
        let canvas = new Canvas(2, 2);
        let ctx = canvas.getContext('2d');
        ctx.fillStyle = 'red';
        ctx.fillRect(0, 0, 2, 1);
        let img = Image.fromCanvas(canvas);
        Array.from(img.data).should.eql([
            255,   0,   0, 255, 255,   0,   0, 255,
            0,   0,   0,   0,   0,   0,   0,   0
        ]);
    });

    it('should load from URL', function () {
        return load('format/rgba32.png').then(function (img) {
            img.width.should.be.greaterThan(0);
            img.height.should.be.greaterThan(0);
            img.maxValue.should.equal(255);
        });
    });

    it('should load from dataURL', function () {
        // a red dot
        const dataURL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
        return Image.load(dataURL).then(img => {
            img.width.should.equal(5);
            img.height.should.equal(5);
        });
    });

    it('should clone', async () => {
        const img = await load('format/rgba32.png');
        const clone = img.clone();
        clone.should.be.an.instanceOf(Image);
        clone.should.not.be.equal(img);
        clone.data.should.not.equal(img.data);
        clone.toDataURL().should.equal(img.toDataURL());
    });

    it('should clone and keep same data', async () => {
        const img = await load('format/rgba32.png');
        const clone = img.clone({copyData: false});
        clone.should.be.an.instanceOf(Image);
        clone.should.not.be.equal(img);
        clone.data.should.equal(img.data);
        clone.toDataURL().should.equal(img.toDataURL());
    });

    it('isImage', function () {
        const image = new Image(5, 5);
        Image.isImage(image).should.be.true();
        Image.isImage().should.be.false();
        Image.isImage({}).should.be.false();
    });
});
<|endoftext|>


<commit_before>const immutableReactForm = {
  greet() {
    return 'hello';
  }
};

export default immutableReactForm;
<commit_msg>Add LocalStateForm from existing code<commit_after>import React from 'react';
import curry from 'lodash/curry';
import { fromJS, is, List, Map } from 'immutable';

const setupForm = curry((updateModel,data,original,validate)=>{
  const validationData = validate(data) || new Map();
  return {
    // Core API
    update:updateModel,
    model:data,
    meta:{
      dirty:!is(data,original)
    },
    validation:{
      get:(key)=>validationData.get(key,{
        valid:true,
        message:''
      }),
      isValid:validationData.size === 0,
      toJSON:()=>validationData.toJSON()
    },

    // For easy debugging
    toJSON:()=>data.toJSON(),

    // Helpers
    set:(key,val)=>updateModel(data.set(key,val)),
    setIn:(key,val)=>updateModel(data.setIn(key,val)),
  }
});

export const LocalStateForm = curry((getForm,validate,submitFn,InputComponent)=>{
  return class extends React.Component{
    constructor(props){
      super(props);
      this.state = {
        model:fromJS(getForm(props)),
        submitting:false,
        lastSubmissionSuccessful:null
      }
    }

    updateForm(model){
      this.setState({model})
    }

    async submit(e){
      e.preventDefault();
      this.setState({submitting:true});
      try{
        await submitFn(this.state.model, this.props);
        this.setState({
          submitting:false,
          lastSubmission:{
            success:true
          }
        });
      }catch(e){
        this.setState({
          submitting:false,
          lastSubmission:{
            success:false,
            error:e
          }
        });
      }
    }

    render(){
      const form = Object.assign(
        {},
        setupForm(
          this.updateForm.bind(this),
          this.state.model,
          fromJS(getForm(this.props)),
          validate,
          submitFn
        ),
        {
          submission:{
            submit:this.submit.bind(this),
            loading:this.state.submitting,
            lastSubmission:this.state.lastSubmission
          }
        }
      );

      return <InputComponent
        {...this.props}
        form={form}
      />
    }
  }
})
<|endoftext|>


<commit_before>var PlayerControls = {
    update: function () {
        if (Game.stage == null || Game.stage.player == null || !Game.stage.unlocked) {
            return;
        }

        var p = Game.stage.player;

        if (p.dead || p.isProjectile) {
            return;
        }

        // MOVE //////////////////////////////////////////////////////////////////////////////////////////////////////
        var keyMoveUp       = Keyboard.wasKeyPressed(KeyCode.W) || Keyboard.wasKeyPressed(KeyCode.UP);
        var keyMoveLeft     = Keyboard.isKeyDown(KeyCode.A) || Keyboard.isKeyDown(KeyCode.LEFT);
        var keyMoveRight    = Keyboard.isKeyDown(KeyCode.D) || Keyboard.isKeyDown(KeyCode.RIGHT);

        if (keyMoveUp && p.canMoveUp() && (p.landed || (p.jumped && !p.doubleJumped))) {
            p.velocityY -= p.jumpPower;

            if (p.velocityY <= -p.jumpPower) {
                p.velocityY = -p.jumpPower;
            }

            p.landed = false;

            if (p.jumped) {
                p.doubleJumped = true;
            }

            AudioOut.playSfx('jump.wav', 0.75);
            p.jumped = true;
        }

        if (keyMoveLeft && p.canMoveLeft()) {
            p.velocityX -= p.movementSpeed;

            if (p.velocityX <= -p.movementSpeed) {
                p.velocityX = -p.movementSpeed;
            }
        }
        else if (keyMoveRight && p.canMoveRight()) {
            p.velocityX += p.movementSpeed;

            if (p.velocityX >= p.movementSpeed) {
                p.velocityX = p.movementSpeed;
            }
        }
        else {
            p.velocityX = 0;
        }

        // ATTACK //////////////////////////////////////////////////////////////////////////////////////////////////////
        var keyAttack = Keyboard.wasKeyPressed(KeyCode.ENTER) || Keyboard.wasKeyPressed(KeyCode.RETURN) || Keyboard.wasKeyPressed(KeyCode.SPACE);

        if (keyAttack && !p.isAttacking && p.landed) {
            // Determine attack radius (what can we pick up)
            var attackRadius = p.attackRect();

            // Find intersecting blocks
            var blocks = p.map.checkCollisions(p, attackRadius);

            if (blocks.length > 0) {
                var block = blocks[0];

                if (!block.isProjectile) {
                    p.pickUp(block);
                }
            }
        }
        else if (keyAttack && p.isAttacking) {
            // Throw!
            p.attackingWith.isProjectile = true;
            p.attackingWith.causesCollision = false;
            p.attackingWith.receivesCollision = true;
            p.attackingWith.affectedByGravity = true;
            p.attackingWith.velocityX = p.direction == Direction.LEFT ? -32 : 32;
            p.attackingWith = null;
            p.isAttacking = null;
            p.landed = true;
            p.jumped = false;
        }

        // NET SYNC ////////////////////////////////////////////////////////////////////////////////////////////////////
        var syncMessage = p.prepareSyncMessage();

        if (Net.isHost) {
            Router.processData(syncMessage);
        } else {
            Net.getConnection().sendMessage(syncMessage);
        }
    }
};<commit_msg>[Net] Only send player update packet when something has changed, let the clients compute the rest on their own<commit_after>var PlayerControls = {
    update: function () {
        if (Game.stage == null || Game.stage.player == null || !Game.stage.unlocked) {
            return;
        }

        var p = Game.stage.player;

        if (p.dead || p.isProjectile) {
            return;
        }

        var didChange = false;

        // MOVE //////////////////////////////////////////////////////////////////////////////////////////////////////
        var keyMoveUp       = Keyboard.wasKeyPressed(KeyCode.W) || Keyboard.wasKeyPressed(KeyCode.UP);
        var keyMoveLeft     = Keyboard.isKeyDown(KeyCode.A) || Keyboard.isKeyDown(KeyCode.LEFT);
        var keyMoveRight    = Keyboard.isKeyDown(KeyCode.D) || Keyboard.isKeyDown(KeyCode.RIGHT);

        if (keyMoveUp && p.canMoveUp() && (p.landed || (p.jumped && !p.doubleJumped))) {
            p.velocityY -= p.jumpPower;

            if (p.velocityY <= -p.jumpPower) {
                p.velocityY = -p.jumpPower;
            }

            p.landed = false;

            if (p.jumped) {
                p.doubleJumped = true;
            }

            AudioOut.playSfx('jump.wav', 0.75);
            p.jumped = true;
        }

        if (keyMoveLeft && p.canMoveLeft()) {
            p.velocityX -= p.movementSpeed;

            if (p.velocityX <= -p.movementSpeed) {
                p.velocityX = -p.movementSpeed;
            }

            didChange = true;
        }
        else if (keyMoveRight && p.canMoveRight()) {
            p.velocityX += p.movementSpeed;

            if (p.velocityX >= p.movementSpeed) {
                p.velocityX = p.movementSpeed;
            }

            didChange = true;
        }
        else {
            if (p.velocityX != null) {
                p.velocityX = 0;
                didChange = true;
            }
        }

        // ATTACK //////////////////////////////////////////////////////////////////////////////////////////////////////
        var keyAttack = Keyboard.wasKeyPressed(KeyCode.ENTER) || Keyboard.wasKeyPressed(KeyCode.RETURN) || Keyboard.wasKeyPressed(KeyCode.SPACE);

        if (keyAttack && !p.isAttacking && p.landed) {
            // Determine attack radius (what can we pick up)
            var attackRadius = p.attackRect();

            // Find intersecting blocks
            var blocks = p.map.checkCollisions(p, attackRadius);

            if (blocks.length > 0) {
                var block = blocks[0];

                if (!block.isProjectile) {
                    p.pickUp(block);
                    didChange = true;
                }
            }
        }
        else if (keyAttack && p.isAttacking) {
            // Throw!
            p.attackingWith.isProjectile = true;
            p.attackingWith.causesCollision = false;
            p.attackingWith.receivesCollision = true;
            p.attackingWith.affectedByGravity = true;
            p.attackingWith.velocityX = p.direction == Direction.LEFT ? -32 : 32;
            p.attackingWith = null;
            p.isAttacking = null;
            p.landed = true;
            p.jumped = false;
            didChange = true;
        }

        // NET SYNC ////////////////////////////////////////////////////////////////////////////////////////////////////
        if (didChange) {
            var syncMessage = p.prepareSyncMessage();

            if (Net.isHost) {
                Router.processData(syncMessage);
            } else {
                Net.getConnection().sendMessage(syncMessage);
            }
        }
    }
};<|endoftext|>


<commit_before>function isReturningJSXElement(path) {
  /**
   * Early exit for ArrowFunctionExpressions, there is no ReturnStatement node.
   */
  if (path.node.init && path.node.init.body && path.node.init.body.type === 'JSXElement') {
    return true;
  }

  let visited = false;

  path.traverse({
    ReturnStatement(path2) {
      // We have already found what we are looking for.
      if (visited) {
        return;
      }

      const argument = path2.get('argument');

      if (argument.node.type === 'JSXElement') {
        visited = true;
      } else if (argument.node.type === 'CallExpression') {

        const node = argument.get('callee').node;
        if (node.object.name === 'React' && node.property.name === 'createElement') {
          visited = true;
        }

        const name = argument.get('callee').node.name;
        const binding = path.scope.getBinding(name);

        if (!binding) {
          return;
        }

        if (isReturningJSXElement(binding.path)) {
          visited = true;
        }
      }
    }
  });

  return visited;
}

const validPossibleStatelessComponentTypes = [
  'VariableDeclarator',
  'FunctionDeclaration'
];

/**
 * Returns `true` if the path represents a function which returns a JSXElment
 */
export default function isStatelessComponent(path) {
  const node = path.node;

  if (validPossibleStatelessComponentTypes.indexOf(node.type) === -1) {
    return false;
  }

  if (isReturningJSXElement(path)) {
    return true;
  }

  return false;
}
<commit_msg>small js style refactor<commit_after>function isReturningJSXElement(path) {
  /**
   * Early exit for ArrowFunctionExpressions, there is no ReturnStatement node.
   */
  if (path.node.init && path.node.init.body && path.node.init.body.type === 'JSXElement') {
    return true;
  }

  let visited = false;

  path.traverse({
    ReturnStatement(path2) {
      // We have already found what we are looking for.
      if (visited) {
        return;
      }

      const argument = path2.get('argument');

      if (argument.node.type === 'JSXElement') {
        visited = true;
      } else if (argument.node.type === 'CallExpression') {

        const { node } = argument.get('callee');
        if (node.object.name === 'React' && node.property.name === 'createElement') {
          visited = true;
        }

        const binding = path.scope.getBinding(node.name);

        if (!binding) {
          return;
        }

        if (isReturningJSXElement(binding.path)) {
          visited = true;
        }
      }
    }
  });

  return visited;
}

const validPossibleStatelessComponentTypes = [
  'VariableDeclarator',
  'FunctionDeclaration'
];

/**
 * Returns `true` if the path represents a function which returns a JSXElment
 */
export default function isStatelessComponent(path) {
  const node = path.node;

  if (validPossibleStatelessComponentTypes.indexOf(node.type) === -1) {
    return false;
  }

  if (isReturningJSXElement(path)) {
    return true;
  }

  return false;
}
<|endoftext|>


<commit_before>AUI.add('io-stdmod', function(A) {

var L = A.Lang,
	isString = L.isString,

	BLANK = '',
	CFG = 'cfg',
	FORMATTER = 'formatter',
	HOST = 'host',
	ICON = 'icon',
	LOADING = 'loading',
	POST = 'POST',
	QUEUE = 'queue',
	SECTION = 'section',
	URI = 'uri',

	getCN = A.ClassNameManager.getClassName,

	CSS_ICON_LOADING = getCN(ICON, LOADING);

var StdMod = A.WidgetStdMod;

/* Standard Module IO Plugin Constructor */
function StdModIOPlugin(config) {
	StdModIOPlugin.superclass.constructor.apply(this, arguments);
}

A.mix(StdModIOPlugin, {
	NAME: 'stdModIOPlugin',

	NS: 'io',

	ATTRS: {
		uri: {
			value: null
		},

		cfg: {
			value: {}
		},

		/*
		* The default formatter to use when formatting response data. The default
		* implementation simply passes back the response data passed in.
		*/
		formatter: {
			valueFn: function() {
				return this._defFormatter;
			}
		},

		/*
		* The Standard Module section to which the io plugin instance is bound.
		* Response data will be used to populate this section, after passing through
		* the configured formatter.
		*/
		section: {
			value: StdMod.BODY,
			validator: function(val) {
				return (!val || val == StdMod.BODY || val == StdMod.HEADER || val == StdMod.FOOTER);
			}
		},

		loading: {
			value: '

'
		}
	}
});

A.extend(StdModIOPlugin, A.Plugin.Base, {
	initializer: function() {
		var instance = this;
		var host = instance.get(HOST);
		var bodyNode = host.bodyNode;

		StdModIOPlugin.superclass.initializer.apply(this, arguments);

		if (bodyNode) {
			bodyNode.plug(A.Plugin.ParseContent);
		}

		var queue = bodyNode.ParseContent.get(QUEUE);

		if (queue) {
			// dont close the overlay while queue is running
			host.on('close', function(event) {
				if (queue.isRunning()) {
					event.halt();
				}
			});

			// stop the queue after the dialog is closed, just in case.
			host.after('close', function(event) {
				queue.stop();
			});
		}
	},

	destructor: function() {
		if (this.isActive()) {
			A.io.abort(this._activeIO);
			this._activeIO = null;
		}
	},

	isActive: function() {
		return this._activeIO;
	},

	/*
	* IO Plugin specific method, use to initiate a new io request using the current
	* io configuration settings.
	*/
	refresh: function() {
		var instance = this;
		var section = this.get(SECTION);

		if (section && !this.isActive()) {
			var uri = this.get(URI);

			if (uri) {
				var cfg = A.mix(
					this.get(CFG),
					{
						method: POST,
						on: {}
					}
				);

				// binding correct scopes on callbacks
				cfg.on = A.merge(
					cfg.on,
					{
						start: A.bind(cfg.on.start || this._defStartHandler, this),
						complete: A.bind(cfg.on.complete || this._defCompleteHandler, this),
						success: A.bind(cfg.on.success || this._defSuccessHandler, this),
						failure: A.bind(cfg.on.failure || this._defFailureHandler, this)
					}
				);

				A.io(uri, cfg);
			}
		}
	},

	_defSuccessHandler: function(id, o) {
		var response = o.responseText || BLANK;
		var section = this.get(SECTION);
		var formatter = this.get(FORMATTER);

		this.get(HOST).setStdModContent(section, formatter(response));
	},

	_defFailureHandler: function(id, o) {
		this.get(HOST).setStdModContent(this.get(SECTION), 'Failed to retrieve content');
	},

	_defStartHandler: function(id, o) {
		this._activeIO = o;
		this.get(HOST).setStdModContent(this.get(SECTION), this.get(LOADING));
	},

	_defCompleteHandler: function(id, o) {
		this._activeIO = null;
	},

	_defFormatter: function(val) {
		return val;
	}
});

A.namespace('Plugin');
A.Plugin.StdModIOPlugin = StdModIOPlugin;

}, '@VERSION', { requires: [ 'aui-base', 'component-overlay', 'parse-content', 'io', 'plugin' ] });<commit_msg>io-stdmod avoid nullpointer when bodyNode is not ready<commit_after>AUI.add('io-stdmod', function(A) {

var L = A.Lang,
	isString = L.isString,

	BLANK = '',
	CFG = 'cfg',
	FORMATTER = 'formatter',
	HOST = 'host',
	ICON = 'icon',
	LOADING = 'loading',
	POST = 'POST',
	QUEUE = 'queue',
	SECTION = 'section',
	URI = 'uri',

	getCN = A.ClassNameManager.getClassName,

	CSS_ICON_LOADING = getCN(ICON, LOADING);

var StdMod = A.WidgetStdMod;

/* Standard Module IO Plugin Constructor */
function StdModIOPlugin(config) {
	StdModIOPlugin.superclass.constructor.apply(this, arguments);
}

A.mix(StdModIOPlugin, {
	NAME: 'stdModIOPlugin',

	NS: 'io',

	ATTRS: {
		uri: {
			value: null
		},

		cfg: {
			value: {}
		},

		/*
		* The default formatter to use when formatting response data. The default
		* implementation simply passes back the response data passed in.
		*/
		formatter: {
			valueFn: function() {
				return this._defFormatter;
			}
		},

		/*
		* The Standard Module section to which the io plugin instance is bound.
		* Response data will be used to populate this section, after passing through
		* the configured formatter.
		*/
		section: {
			value: StdMod.BODY,
			validator: function(val) {
				return (!val || val == StdMod.BODY || val == StdMod.HEADER || val == StdMod.FOOTER);
			}
		},

		loading: {
			value: '

'
		}
	}
});

A.extend(StdModIOPlugin, A.Plugin.Base, {
	initializer: function() {
		var queue = null;
		var instance = this;
		var host = instance.get(HOST);
		var bodyNode = host.bodyNode;

		StdModIOPlugin.superclass.initializer.apply(this, arguments);

		if (bodyNode) {
			bodyNode.plug(A.Plugin.ParseContent);

			queue = bodyNode.ParseContent.get(QUEUE);
		}

		if (queue) {
			// dont close the overlay while queue is running
			host.on('close', function(event) {
				if (queue.isRunning()) {
					event.halt();
				}
			});

			// stop the queue after the dialog is closed, just in case.
			host.after('close', function(event) {
				queue.stop();
			});
		}
	},

	destructor: function() {
		if (this.isActive()) {
			A.io.abort(this._activeIO);
			this._activeIO = null;
		}
	},

	isActive: function() {
		return this._activeIO;
	},

	/*
	* IO Plugin specific method, use to initiate a new io request using the current
	* io configuration settings.
	*/
	refresh: function() {
		var instance = this;
		var section = this.get(SECTION);

		if (section && !this.isActive()) {
			var uri = this.get(URI);

			if (uri) {
				var cfg = A.mix(
					this.get(CFG),
					{
						method: POST,
						on: {}
					}
				);

				// binding correct scopes on callbacks
				cfg.on = A.merge(
					cfg.on,
					{
						start: A.bind(cfg.on.start || this._defStartHandler, this),
						complete: A.bind(cfg.on.complete || this._defCompleteHandler, this),
						success: A.bind(cfg.on.success || this._defSuccessHandler, this),
						failure: A.bind(cfg.on.failure || this._defFailureHandler, this)
					}
				);

				A.io(uri, cfg);
			}
		}
	},

	_defSuccessHandler: function(id, o) {
		var response = o.responseText || BLANK;
		var section = this.get(SECTION);
		var formatter = this.get(FORMATTER);

		this.get(HOST).setStdModContent(section, formatter(response));
	},

	_defFailureHandler: function(id, o) {
		this.get(HOST).setStdModContent(this.get(SECTION), 'Failed to retrieve content');
	},

	_defStartHandler: function(id, o) {
		this._activeIO = o;
		this.get(HOST).setStdModContent(this.get(SECTION), this.get(LOADING));
	},

	_defCompleteHandler: function(id, o) {
		this._activeIO = null;
	},

	_defFormatter: function(val) {
		return val;
	}
});

A.namespace('Plugin');
A.Plugin.StdModIOPlugin = StdModIOPlugin;

}, '@VERSION', { requires: [ 'aui-base', 'component-overlay', 'parse-content', 'io', 'plugin' ] });<|endoftext|>


<commit_before>/*
* jQuery dumbCrossFade
* v2.0.0
* https://github.com/kevindb/jquery-dumbcrossfade
*
* jQuery DumbCrossFade is intended to be a light-weight slide transition that enables external manipulation.
*
* Copyright 2015 Kevin Morris
* Copyright 2009 Jason Sebring
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
*/

(function($) {
	$.fn.dumbCrossFade = function(settings) {

		var publicAccessorLabel = 'dumbCrossFade.publicAccessor';
		var configLabel = 'dumbCrossFade.config';

		if (typeof(this.data(publicAccessorLabel)) !== 'undefined' && this.data(publicAccessorLabel) !== null) {
			var pa = this.data(publicAccessorLabel);
			var cg = this.data(configLabel);
			var args = Array.prototype.slice.apply(arguments);
			if (args.length > 0) {
				if (typeof(args[0]) === 'object') {
					if (settings) $.extend(cg, settings);
					var args = Array.prototype.slice.apply(arguments);
					if (args.length > 1) {
						args = args.slice(1,args.length);
					} else {
						pa.start();
						return this;
					}
				}
				if (arguments.length === 1) {
					pa[arguments[0]]();
				} else if (arguments.length > 1) {
					var args = Array.prototype.slice.apply(arguments);
					args = args.slice(1,args.length);
					pa[arguments[0]].apply(this,args);
				}
			}
			return this;
		}

		var config = {
			'slideType':'slidehorizontal',
			'index':0,
			'showTime':5000,
			'transitionTime':1000,
			'doHoverPause':true,
			'maxZIndex':100,
			'slideChange':null,
			'direction':'forward',
			'fadeInOut':false
		},
		timeOut = null,
		itemArray = [],
		blockAnimation = false,
		lastIndexRequest = -1,
		$self = this
		$window = $(window),
		$body = $('body');

		if (settings) $.extend(config, settings);

		function cancelSlideShow() {
			if (timeOut !== null) { window.clearTimeout(timeOut); timeOut = null; }
		}

		function doSlideShowNow() {
			if (blockAnimation) {
				if (arguments.length > 0) {
					lastIndexRequest = arguments[0];
				}
				return;
			}
			var currentIndex = config.index;
			var nextIndex = (arguments.length > 0) ? arguments[0] : (config.index >= itemArray.length - 1) ? 0 : config.index + 1;
			if (config.direction === 'backward') {
				if (currentIndex === 0) {
					nextIndex = itemArray.length - 1;
				} else {
					nextIndex = currentIndex - 1;
				}
			}
			if (currentIndex == nextIndex) { return; }
			var $f = itemArray[currentIndex].show(),
			$n = itemArray[nextIndex];
			blockAnimation = true;
			doneF = function () {
				$f.hide();
				if (config.fadeInOut) {
					$f.css({'opacity':'1.0'});
					$n.css({'opacity':'1.0'});
				}
				blockAnimation = false;
				if (lastIndexRequest != -1) {
					doSlideShowNow(lastIndexRequest);
					lastIndexRequest = -1;
				}
			};
			$f.css('z-index',(config.maxZIndex-1)+'');
			$n.css('z-index',config.maxZIndex+'');
			switch (config.slideType) {
				case 'slidehorizontal' :
					var pos = $f.position(),
					width = $f.width(),
					adjustX = '-='+width;
					if (config.direction === 'forward') {
						$n.css({'left':(parseInt(pos.left) + width) + 'px'});
					} else {
						$n.css({'left':(parseInt(pos.left) - width) + 'px'});
						adjustX = '+='+width;
					}
					if (config.fadeInOut) {
						$n.css({'opacity':'0','display':'block'});
						$f.animate({'left':adjustX,'opacity':'0'},config.transitionTime,'swing');
						$n.animate({'left':adjustX,'opacity':'1.0'},config.transitionTime,'swing',doneF);
					} else {
						$n.show();
						$f.animate({'left':adjustX},config.transitionTime,'swing');
						$n.animate({'left':adjustX},config.transitionTime,'swing',doneF);
					}
					break;
				case 'slidevertical' :
					var pos = $f.position(),
					height = $f.height(),
					adjustY = '-='+height;
					if (config.direction === 'forward') {
						$n.css({'top':(parseInt(pos.top) + height) + 'px','display':'block'});
					} else {
						$n.css({'top':(parseInt(pos.top) - height) + 'px','display':'block'});
						adjustY = '+='+height;
					}
					if (config.fadeInOut) {
						$n.css({'opacity':'0','display':'block'});
						$f.animate({'top':adjustY,'opacity':'0'},config.transitionTime,'swing');
						$n.animate({'top':adjustY,'opacity':'1.0'},config.transitionTime,'swing',doneF);
					}
					else {
						$n.show();
						$f.animate({'top':adjustY},config.transitionTime);
						$n.animate({'top':adjustY},config.transitionTime,doneF);
					}
					break;
				case 'fade' :
					$n.fadeIn(config.transitionTime,doneF);
					break;
			}
			if (config.slideChange !== null) {
				config.slideChange(nextIndex);
			}
			config.index = nextIndex;
		}

		function doSlideShow() {
			cancelSlideShow();
			timeOut = window.setTimeout(function() {
				doSlideShowNow();
				doSlideShow();
			},config.showTime);
		}

		$self.each(function() {
			(itemArray.length === config.index) ? $(this).show() : $(this).hide();
			if (itemArray.length === 0) {
				if (config.doHoverPause) {
					$(this).parent().hover(
						function() {
							cancelSlideShow();
						},
						function() {
							cancelSlideShow();
							doSlideShow();
						}
					);
				}
			}
			itemArray[itemArray.length] = $(this);
		});

		var publicAccessor = {
			'jump' : function (index) {
				cancelSlideShow();
				doSlideShowNow(index);
				return publicAccessor;
			},
			'start' : function () {
				$self.children().hide();
				itemArray[config.index].show();
				config.direction = 'forward';
				doSlideShow();
			},
			'stop' : function () {
				cancelSlideShow();
			},
			'next' : function () {
				config.direction = 'forward';
				cancelSlideShow();
				doSlideShowNow();
			},
			'previous' : function () {
				config.direction = 'backward';
				cancelSlideShow();
				doSlideShowNow();
			}
		};

		this.data(publicAccessorLabel,publicAccessor);
		this.data(configLabel,config);

		doSlideShow();

		return this;
	};
})(jQuery);
<commit_msg>Whitespace<commit_after>/*
* jQuery dumbCrossFade
* v2.0.0
* https://github.com/kevindb/jquery-dumbcrossfade
*
* jQuery DumbCrossFade is intended to be a light-weight slide transition that enables external manipulation.
*
* Copyright 2015 Kevin Morris
* Copyright 2009 Jason Sebring
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
*/

(function($) {
	$.fn.dumbCrossFade = function(settings) {

		var publicAccessorLabel = 'dumbCrossFade.publicAccessor';
		var configLabel = 'dumbCrossFade.config';

		if (typeof(this.data(publicAccessorLabel)) !== 'undefined' && this.data(publicAccessorLabel) !== null) {
			var pa = this.data(publicAccessorLabel);
			var cg = this.data(configLabel);
			var args = Array.prototype.slice.apply(arguments);
			if (args.length > 0) {
				if (typeof(args[0]) === 'object') {
					if (settings) $.extend(cg, settings);
					var args = Array.prototype.slice.apply(arguments);
					if (args.length > 1) {
						args = args.slice(1,args.length);
					} else {
						pa.start();
						return this;
					}
				}
				if (arguments.length === 1) {
					pa[arguments[0]]();
				} else if (arguments.length > 1) {
					var args = Array.prototype.slice.apply(arguments);
					args = args.slice(1,args.length);
					pa[arguments[0]].apply(this,args);
				}
			}
			return this;
		}

		var config = {
			'slideType':'slidehorizontal',
			'index':0,
			'showTime':5000,
			'transitionTime':1000,
			'doHoverPause':true,
			'maxZIndex':100,
			'slideChange':null,
			'direction':'forward',
			'fadeInOut':false
		},
		timeOut = null,
		itemArray = [],
		blockAnimation = false,
		lastIndexRequest = -1,
		$self = this
		$window = $(window),
		$body = $('body');

		if (settings) $.extend(config, settings);

		function cancelSlideShow() {
			if (timeOut !== null) { window.clearTimeout(timeOut); timeOut = null; }
		}

		function doSlideShowNow() {
			if (blockAnimation) {
				if (arguments.length > 0) {
					lastIndexRequest = arguments[0];
				}
				return;
			}
			var currentIndex = config.index;
			var nextIndex = (arguments.length > 0) ? arguments[0] : (config.index >= itemArray.length - 1) ? 0 : config.index + 1;
			if (config.direction === 'backward') {
				if (currentIndex === 0) {
					nextIndex = itemArray.length - 1;
				} else {
					nextIndex = currentIndex - 1;
				}
			}
			if (currentIndex == nextIndex) { return; }
			var $f = itemArray[currentIndex].show(),
			$n = itemArray[nextIndex];
			blockAnimation = true;
			doneF = function () {
				$f.hide();
				if (config.fadeInOut) {
					$f.css({'opacity':'1.0'});
					$n.css({'opacity':'1.0'});
				}
				blockAnimation = false;
				if (lastIndexRequest != -1) {
					doSlideShowNow(lastIndexRequest);
					lastIndexRequest = -1;
				}
			};
			$f.css('z-index',(config.maxZIndex-1)+'');
			$n.css('z-index',config.maxZIndex+'');
			switch (config.slideType) {
				case 'slidehorizontal' :
					var pos = $f.position(),
					width = $f.width(),
					adjustX = '-='+width;
					if (config.direction === 'forward') {
						$n.css({'left':(parseInt(pos.left) + width) + 'px'});
					} else {
						$n.css({'left':(parseInt(pos.left) - width) + 'px'});
						adjustX = '+='+width;
					}
					if (config.fadeInOut) {
						$n.css({'opacity':'0','display':'block'});
						$f.animate({'left':adjustX,'opacity':'0'},config.transitionTime,'swing');
						$n.animate({'left':adjustX,'opacity':'1.0'},config.transitionTime,'swing',doneF);
					} else {
						$n.show();
						$f.animate({'left':adjustX},config.transitionTime,'swing');
						$n.animate({'left':adjustX},config.transitionTime,'swing',doneF);
					}
					break;
				case 'slidevertical' :
					var pos = $f.position(),
					height = $f.height(),
					adjustY = '-='+height;
					if (config.direction === 'forward') {
						$n.css({'top':(parseInt(pos.top) + height) + 'px','display':'block'});
					} else {
						$n.css({'top':(parseInt(pos.top) - height) + 'px','display':'block'});
						adjustY = '+='+height;
					}
					if (config.fadeInOut) {
						$n.css({'opacity':'0','display':'block'});
						$f.animate({'top':adjustY,'opacity':'0'},config.transitionTime,'swing');
						$n.animate({'top':adjustY,'opacity':'1.0'},config.transitionTime,'swing',doneF);
					}
					else {
						$n.show();
						$f.animate({'top':adjustY},config.transitionTime);
						$n.animate({'top':adjustY},config.transitionTime,doneF);
					}
					break;
				case 'fade' :
					$n.fadeIn(config.transitionTime,doneF);
					break;
			}
			if (config.slideChange !== null) {
				config.slideChange(nextIndex);
			}
			config.index = nextIndex;
		}

		function doSlideShow() {
			cancelSlideShow();
			timeOut = window.setTimeout(function() {
				doSlideShowNow();
				doSlideShow();
			},config.showTime);
		}

		$self.each(function() {
			(itemArray.length === config.index) ? $(this).show() : $(this).hide();
			if (itemArray.length === 0) {
				if (config.doHoverPause) {
					$(this).parent().hover(
						function() {
							cancelSlideShow();
						},
						function() {
							cancelSlideShow();
							doSlideShow();
						}
					);
				}
			}
			itemArray[itemArray.length] = $(this);
		});

		var publicAccessor = {
			'jump' : function (index) {
				cancelSlideShow();
				doSlideShowNow(index);
				return publicAccessor;
			},
			'start' : function () {
				$self.children().hide();
				itemArray[config.index].show();
				config.direction = 'forward';
				doSlideShow();
			},
			'stop' : function () {
				cancelSlideShow();
			},
			'next' : function () {
				config.direction = 'forward';
				cancelSlideShow();
				doSlideShowNow();
			},
			'previous' : function () {
				config.direction = 'backward';
				cancelSlideShow();
				doSlideShowNow();
			}
		};

		this.data(publicAccessorLabel,publicAccessor);
		this.data(configLabel,config);

		doSlideShow();

		return this;
	};
})(jQuery);
<|endoftext|>