<commit_before>var assert       = require('assert');
var _            = require('lodash');
var when            = require('when');
var express      = require('express');
var when         = require('when');
var fs           = require('fs');
var randString   = require('mout/random/randString');
var globalize    = require('../lib/addMethod/globalize');
var ThreadNeedle = require('../');

describe('#addMethodSOAP', function () {

    var regonline_token = require('./dummycredentials.json').regonline;

    function promiseFailFunc (done) {
        return function (err) {
            console.log(err);
            assert.fail(err);
            done();
        }
    }

    describe('Running', function () {
        this.timeout(30000);
        var threadneedle;

        before(function () {
            threadneedle = new ThreadNeedle(true);
            threadneedle.global({

                soap: true,

                wsdl: 'https://www.regonline.com/api/default.asmx?WSDL',

                options: {
                    headers: [{
                        value: {
                            TokenHeader: {
                                APIToken: regonline_token
                            }
                        },
                        xmlns: 'http://www.regonline.com/api',
                    }]
                },

                data: {}

            });
        });

        it('should error if wsdl is not provided (or not a string)', function (done) {

            var privateThreadneedle = new ThreadNeedle(true);

            privateThreadneedle.global({

                soap: true,

                options: {
                    headers: [{
                        value: {
                            TokenHeader: {
                                APIToken: regonline_token
                            }
                        },
                        xmlns: 'http://www.regonline.com/api',
                    }]
                },

                data: {}

            });

            when(
                privateThreadneedle.addMethod(
                    'list_events',
                    {
                        method: 'GetEvents',

                        data: {
                            orderBy: 'ID DESC',
                        }
                    }
                )
            )

            .done(
                function () {

                    when(
                        privateThreadneedle['list_events']({})
                    )

                    .done(
                        promiseFailFunc(done),
                        function (err) {
                            assert.strictEqual(err, '`wsdl` field (string) must be provided to create a client instance.');
                            done();
                        }
                    );

                },
                promiseFailFunc(done)
            );

        });

        it('should be able to add a standard SOAP method', function (done) {

            when(
                threadneedle.addMethod(
                    'list_events',
                    {
                        method: 'GetEvents',

                        data: {
                            orderBy: 'ID DESC',
                        }
                    }
                )
            )

            .done(
                function () {
                    assert(_.isFunction(threadneedle['list_events']));
                    done();
                },
                promiseFailFunc(done)
            );

        });

        it('should be able to execute a standard SOAP method', function (done) {

            when(
                threadneedle['list_events']({})
            )

            .then(function (results) {
                assert.deepEqual(results.headers, {});
                assert(results.body['GetEventsResult']['Success']);
            })

            .done(done, promiseFailFunc(done));

        });

        it('should substitute to the url and data with a basic example', function (done) {

            when(
                threadneedle.addMethod(
                    'list_events2',
                    {
                        method: 'Get{{event_type}}',

                        data: {
                            orderBy: '{{order_by}}',
                        }
                    }
                )
            )

            .done(
                function (result) {

                    when(
                        threadneedle['list_events2']({
                            event_type: 'Events',
                            order_by: 'ID DESC'
                        })
                    )

                    .then(function (results) {
                        assert(results.body['GetEventsResult']['Success']);
                    })

                    .done(done, promiseFailFunc(done));

                },
                promiseFailFunc(done)
            );

        });

        it('should substitute to the options with a basic example', function (done) {

            var privateThreadneedle = new ThreadNeedle(true);

            privateThreadneedle.global({

                soap: true,

                wsdl: 'https://www.regonline.com/api/default.asmx?WSDL',

                options: {
                    headers: [{
                        value: {
                            TokenHeader: {
                                APIToken: '{{access_token}}'
                            }
                        },
                        xmlns: 'http://www.regonline.com/api',
                    }]
                },

                data: {}

            });

            when(
                privateThreadneedle.addMethod(
                    'list_events',
                    {
                        method: 'GetEvents',

                        data: {
                            orderBy: 'ID DESC',
                        }
                    }
                )
            )

            .done(
                function () {

                    when(
                        privateThreadneedle['list_events']({
                            access_token: regonline_token
                        })
                    )

                    .then(function (results) {
                        assert.deepEqual(results.headers, {});
                        assert(results.body['GetEventsResult']['Success']);
                    })

                    .done(done, promiseFailFunc(done));

                },
                promiseFailFunc(done)
            );

        });

        it('should reject if expects function returns error', function (done) {
            this.timeout(10000);

            when(
                threadneedle.addMethod(
                    'list_events3',
                    {
                        method: 'GetEvents',

                        data: {
                            orderBy: 'ID DESC',
                        },

                        expects: function (results) {
                            if (results.body['GetEventsResult']['Success'] === true) {
                                return 'Test Error';
                            }
                        }
                    }
                )
            )

            .done(
                function (result) {

                    when(
                        threadneedle['list_events3']({})
                    )

                    .done(
                        promiseFailFunc(done),
                        function (err) {
                            assert.deepEqual(err.headers, {});
                            assert(err.body.message === 'Test Error');
                            done();
                        }
                    );

                },
                promiseFailFunc(done)
            );

        });

        it('should reject if notExpects function returns error', function (done) {

            when(
                threadneedle.addMethod(
                    'list_events4',
                    {
                        method: 'GetEvents',

                        data: {
                            orderBy: 'ID DESC',
                        },

                        notExpects: function (results) {
                            if (results.body['GetEventsResult']['Success'] === true) {
                                return 'Test Error';
                            }
                        }
                    }
                )
            )

            .done(
                function (result) {

                    when(
                        threadneedle['list_events4']({})
                    )

                    .done(
                        promiseFailFunc(done),
                        function (err) {
                            assert(err.body.message === 'Test Error');
                            done();
                        }
                    );

                },
                promiseFailFunc(done)
            );

        });

    });

    describe('Ad-hoc', function () {

        it('should be fine with allowing the method config to be a function', function (done) {

            var threadneedle = new ThreadNeedle(true);

            threadneedle.addMethod(
                'myCustomMethod',
                function (params) {
                    return params.name;
                }
            );

            threadneedle.myCustomMethod({ name: 'Chris' })

            .done(
                function (val) {
                    assert.deepEqual(val.body, 'Chris');
                    done();
                },
                function (err) {
                    assert.fail(err);
                }
            );

        });

		function functionModel (params) {
			return (
				params.passFlag ?
				when.resolve({ success: true }) :
				when.reject(new Error('functionModel Error'))
			);
		};

		function afterHeadersFunction (error, params, body, res) {
			if (params.ahFlag) {
				return {
					gotError: !!error
				};
			} else {
				throw new Error('afterHeaders Error');
			}
		}

		it('Should place `afterHeaders` object in header if function model resolve', function(done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, afterHeadersFunction);

			threadneedle[name]({
				passFlag: true,
				ahFlag: true
			})
			.done(
				function(result) {
					assert.deepEqual(result.headers.gotError, false);
					assert.deepEqual(result.body.success, true);
					done();
				},
				function(error) {
					assert.fail('Wrong clause - failing');
					assert.fail(error);
					done();
				}
			);
		});

		it('Should place `afterHeaders` error in body if function model resolve', function(done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, afterHeadersFunction);

			threadneedle[name]({
				passFlag: true,
				ahFlag: false
			})
			.done(
				function(result) {
					assert.fail('Wrong clause - succeeding');
					assert.fail(result);
					done();
				},
				function(result) {
					assert.deepEqual(result.headers, {});
					assert.deepEqual(result.body.message, 'afterHeaders Error');
					done();
				}
			);
		});

		it('Should place `afterHeaders` object in header if function model reject', function(done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, afterHeadersFunction);

			threadneedle[name]({
				passFlag: false,
				ahFlag: true
			})
			.done(
				function(result) {
					assert.fail('Wrong clause - succeeding');
					assert.fail(result);
					done();
				},
				function(result) {
					assert.deepEqual(result.headers.gotError, true);
					assert.deepEqual(result.body.message, 'functionModel Error');
					done();
				}
			);
		});

		it('Should place `afterHeaders` error in body if function model reject', function(done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, afterHeadersFunction);

			threadneedle[name]({
				passFlag: false,
				ahFlag: false
			})
			.done(
				function(result) {
					assert.fail('Wrong clause - succeeding');
					assert.fail(result);
					done();
				},
				function(result) {
					assert.deepEqual(result.headers, {});
					assert.deepEqual(result.body.message, 'afterHeaders Error');
					done();
				}
			);
		});

		it('Should throw error if `afterHeaders` is not a function', function(done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, {});

			threadneedle[name]({
				passFlag: true,
				ahFlag: true
			})
			.done(
				function(result) {
					assert.fail(result);
					done();
				},
				function(ahError) {
					assert.strictEqual(ahError.message, 'afterHeaders must be a function.');
					done();
				}
			);
		});

    });

    describe('Ad-hoc from REST mode', function () {
        this.timeout(10000);

        it('should be fine with allowing a single SOAP method config from REST mode', function (done) {

            var threadneedle = new ThreadNeedle();

            threadneedle.addMethod(
                'myCustomMethod',
                function (params) {
                    return params.name;
                }
            );

            threadneedle.addMethod(
                'mySOAPMethod',
                {

                    soap: true,

                    wsdl: 'https://www.regonline.com/api/default.asmx?WSDL',

                    options: {
                        headers: [{
                            value: {
                                TokenHeader: {
                                    APIToken: regonline_token
                                }
                            },
                            xmlns: 'http://www.regonline.com/api',
                        }]
                    },

                    method: 'GetEvents',

                    data: {
                        orderBy: 'ID DESC',
                    },

                    afterHeaders: function () {
                        return {
                            success: true
                        }
                    }

                }
            );

            threadneedle['mySOAPMethod']({})

            .done(
                function (val) {
                    assert.deepEqual(val.headers.success, true);
                    assert(val.body['GetEventsResult']['Success']);
                    done();
                },
                function (err) {
                    assert.fail(err);
                }
            );

        });

    });

});
<commit_msg>listing fix for addSoap test<commit_after>var assert       = require('assert');
var _            = require('lodash');
var when            = require('when');
var express      = require('express');
var fs           = require('fs');
var randString   = require('mout/random/randString');
var globalize    = require('../lib/addMethod/globalize');
var ThreadNeedle = require('../');

describe('#addMethodSOAP', function () {

	var regonline_token = require('./dummycredentials.json').regonline;

	function promiseFailFunc (done) {
		return function (err) {
			console.log(err);
			assert.fail(err);
			done();
		};
	}

	describe('Running', function () {
		this.timeout(30000);
		var threadneedle;

		before(function () {
			threadneedle = new ThreadNeedle(true);
			threadneedle.global({

				soap: true,

				wsdl: 'https://www.regonline.com/api/default.asmx?WSDL',

				options: {
					headers: [
						{
							value: {
								TokenHeader: {
									APIToken: regonline_token
								}
							},
							xmlns: 'http://www.regonline.com/api',
						}
					]
				},

				data: {}

			});
		});

		it('should error if wsdl is not provided (or not a string)', function (done) {

			var privateThreadneedle = new ThreadNeedle(true);

			privateThreadneedle.global({

				soap: true,

				options: {
					headers: [
						{
							value: {
								TokenHeader: {
									APIToken: regonline_token
								}
							},
							xmlns: 'http://www.regonline.com/api',
						}
					]
				},

				data: {}

			});

			when(privateThreadneedle.addMethod(
				'list_events',
				{
					method: 'GetEvents',

					data: {
						orderBy: 'ID DESC',
					}
				}
			))

			.done(
				function () {

					when(privateThreadneedle['list_events']({}))

					.done(
						promiseFailFunc(done),
						function (err) {
							assert.strictEqual(err, '`wsdl` field (string) must be provided to create a client instance.');
							done();
						}
					);

				},
				promiseFailFunc(done)
			);

		});

		it('should be able to add a standard SOAP method', function (done) {

			when(threadneedle.addMethod(
				'list_events',
				{
					method: 'GetEvents',

					data: {
						orderBy: 'ID DESC',
					}
				}
			))

			.done(
				function () {
					assert(_.isFunction(threadneedle['list_events']));
					done();
				},
				promiseFailFunc(done)
			);

		});

		it('should be able to execute a standard SOAP method', function (done) {

			when(threadneedle['list_events']({}))

			.then(function (results) {
				assert.deepEqual(results.headers, {});
				assert(results.body['GetEventsResult']['Success']);
			})

			.done(done, promiseFailFunc(done));

		});

		it('should substitute to the url and data with a basic example', function (done) {

			when(threadneedle.addMethod(
				'list_events2',
				{
					method: 'Get{{event_type}}',

					data: {
						orderBy: '{{order_by}}',
					}
				}
			))

			.done(
				function (result) {

					when(threadneedle['list_events2']({
						event_type: 'Events',
						order_by: 'ID DESC'
					}))

					.then(function (results) {
						assert(results.body['GetEventsResult']['Success']);
					})

					.done(done, promiseFailFunc(done));

				},
				promiseFailFunc(done)
			);

		});

		it('should substitute to the options with a basic example', function (done) {

			var privateThreadneedle = new ThreadNeedle(true);

			privateThreadneedle.global({

				soap: true,

				wsdl: 'https://www.regonline.com/api/default.asmx?WSDL',

				options: {
					headers: [
						{
							value: {
								TokenHeader: {
									APIToken: '{{access_token}}'
								}
							},
							xmlns: 'http://www.regonline.com/api',
						}
					]
				},

				data: {}

			});

			when(privateThreadneedle.addMethod(
				'list_events',
				{
					method: 'GetEvents',

					data: {
						orderBy: 'ID DESC',
					}
				}
			))

			.done(
				function () {

					when(privateThreadneedle['list_events']({
						access_token: regonline_token
					}))

					.then(function (results) {
						assert.deepEqual(results.headers, {});
						assert(results.body['GetEventsResult']['Success']);
					})

					.done(done, promiseFailFunc(done));

				},
				promiseFailFunc(done)
			);

		});

		it('should reject if expects function returns error', function (done) {
			this.timeout(10000);

			when(threadneedle.addMethod(
				'list_events3',
				{
					method: 'GetEvents',

					data: {
						orderBy: 'ID DESC',
					},

					expects: function (results) {
						if (results.body['GetEventsResult']['Success'] === true) {
							return 'Test Error';
						}
					}
				}
			))

			.done(
				function (result) {

					when(threadneedle['list_events3']({}))

					.done(
						promiseFailFunc(done),
						function (err) {
							assert.deepEqual(err.headers, {});
							assert(err.body.message === 'Test Error');
							done();
						}
					);

				},
				promiseFailFunc(done)
			);

		});

		it('should reject if notExpects function returns error', function (done) {

			when(threadneedle.addMethod(
				'list_events4',
				{
					method: 'GetEvents',

					data: {
						orderBy: 'ID DESC',
					},

					notExpects: function (results) {
						if (results.body['GetEventsResult']['Success'] === true) {
							return 'Test Error';
						}
					}
				}
			))

			.done(
				function (result) {

					when(threadneedle['list_events4']({}))

					.done(
						promiseFailFunc(done),
						function (err) {
							assert(err.body.message === 'Test Error');
							done();
						}
					);

				},
				promiseFailFunc(done)
			);

		});

	});

	describe('Ad-hoc', function () {

		it('should be fine with allowing the method config to be a function', function (done) {

			var threadneedle = new ThreadNeedle(true);

			threadneedle.addMethod(
				'myCustomMethod',
				function (params) {
					return params.name;
				}
			);

			threadneedle.myCustomMethod({ name: 'Chris' })

			.done(
				function (val) {
					assert.deepEqual(val.body, 'Chris');
					done();
				},
				function (err) {
					assert.fail(err);
				}
			);

		});

		function functionModel (params) {
			return (
				params.passFlag ?
				when.resolve({ success: true }) :
				when.reject(new Error('functionModel Error'))
			);
		}

		function afterHeadersFunction (error, params, body, res) {
			if (params.ahFlag) {
				return {
					gotError: !!error
				};
			} else {
				throw new Error('afterHeaders Error');
			}
		}

		it('Should place `afterHeaders` object in header if function model resolve', function (done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, afterHeadersFunction);

			threadneedle[name]({
				passFlag: true,
				ahFlag: true
			})
			.done(
				function (result) {
					assert.deepEqual(result.headers.gotError, false);
					assert.deepEqual(result.body.success, true);
					done();
				},
				function (error) {
					assert.fail('Wrong clause - failing');
					assert.fail(error);
					done();
				}
			);
		});

		it('Should place `afterHeaders` error in body if function model resolve', function (done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, afterHeadersFunction);

			threadneedle[name]({
				passFlag: true,
				ahFlag: false
			})
			.done(
				function (result) {
					assert.fail('Wrong clause - succeeding');
					assert.fail(result);
					done();
				},
				function (result) {
					assert.deepEqual(result.headers, {});
					assert.deepEqual(result.body.message, 'afterHeaders Error');
					done();
				}
			);
		});

		it('Should place `afterHeaders` object in header if function model reject', function (done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, afterHeadersFunction);

			threadneedle[name]({
				passFlag: false,
				ahFlag: true
			})
			.done(
				function (result) {
					assert.fail('Wrong clause - succeeding');
					assert.fail(result);
					done();
				},
				function (result) {
					assert.deepEqual(result.headers.gotError, true);
					assert.deepEqual(result.body.message, 'functionModel Error');
					done();
				}
			);
		});

		it('Should place `afterHeaders` error in body if function model reject', function (done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, afterHeadersFunction);

			threadneedle[name]({
				passFlag: false,
				ahFlag: false
			})
			.done(
				function (result) {
					assert.fail('Wrong clause - succeeding');
					assert.fail(result);
					done();
				},
				function (result) {
					assert.deepEqual(result.headers, {});
					assert.deepEqual(result.body.message, 'afterHeaders Error');
					done();
				}
			);
		});

		it('Should throw error if `afterHeaders` is not a function', function (done) {
			var name = randString(10);
			var threadneedle = new ThreadNeedle(true);
			threadneedle.addMethod(name, functionModel, {});

			threadneedle[name]({
				passFlag: true,
				ahFlag: true
			})
			.done(
				function (result) {
					assert.fail(result);
					done();
				},
				function (ahError) {
					assert.strictEqual(ahError.message, 'afterHeaders must be a function.');
					done();
				}
			);
		});

	});

	describe('Ad-hoc from REST mode', function () {
		this.timeout(10000);

		it('should be fine with allowing a single SOAP method config from REST mode', function (done) {

			var threadneedle = new ThreadNeedle();

			threadneedle.addMethod(
				'myCustomMethod',
				function (params) {
					return params.name;
				}
			);

			threadneedle.addMethod(
				'mySOAPMethod',
				{

					soap: true,

					wsdl: 'https://www.regonline.com/api/default.asmx?WSDL',

					options: {
						headers: [
							{
								value: {
									TokenHeader: {
										APIToken: regonline_token
									}
								},
								xmlns: 'http://www.regonline.com/api',
							}
						]
					},

					method: 'GetEvents',

					data: {
						orderBy: 'ID DESC',
					},

					afterHeaders: function () {
						return {
							success: true
						};
					}

				}
			);

			threadneedle['mySOAPMethod']({})

			.done(
				function (val) {
					assert.deepEqual(val.headers.success, true);
					assert(val.body['GetEventsResult']['Success']);
					done();
				},
				function (err) {
					assert.fail(err);
				}
			);

		});

	});

});
<|endoftext|>


<commit_before>var StaticMap;
var ZoomableMap;
var StaticCanvasMap;

!function() {
    "use strict";
    StaticMap = function(parameters) {
        var settings = jQuery.extend({
                strokeWidth: 1.5,
                height: 200,
                width: $(parameters.element).innerWidth(),
                zoomScaleFactor: 0.9
            }, parameters)
          , features = topojson.feature(settings.topojson,
                                        settings.topojson.objects[parameters.name])

        if (parameters.projection) {
            var dataPath = d3.geo.path().projection(projection = parameters.projection)
        } else {
            var b = d3.geo.bounds(features)
              , projection = d3.geo.mercator()
                                   .scale(1)
                                   .center([(b[1][0] + b[0][0]) / 2,
                                            (b[1][1] + b[0][1]) / 2])
              , dataPath = d3.geo.path().projection(projection)
              , bounds = dataPath.bounds(features)
              , dx = bounds[1][0] - bounds[0][0]
              , dy = bounds[1][1] - bounds[0][1]
              , scale = 0.9 * (settings.width / dx)

            settings.height = dy * settings.width / dx

            projection.scale(scale)
                      .translate([settings.width / 2, settings.height / 2/* + topMargin*/])
        }

        $(this).height(settings.height) //FIXME: Introduce topMargin again

        function init() {
            var svg = d3.select(settings.element).append("svg")
                        .attr("width", settings.width)
                        .attr("height", settings.height/* + topMargin*/)

            svg.append("rect")
                    .attr("class", "map-background")
                    .attr("width", settings.width)
                    .attr("height", settings.height)

            var g = svg.append("g")
                       .attr("class", "map-polygonGroup")
                       .style("stroke-width", settings.strokeWidth + "px")
                       .selectAll("path")
                       .data(features.features)
                       .enter().append("path")
                       .attr("class", "map-polygon")
                       .attr("d", dataPath)
                       .style("fill", settings.fillCallback)

            //Prevent another call to the init method
            this.init = function() {}
        }

        this.init = init
        this.features = function() { return features }
        this.path = function()  { return dataPath }
        this.parameters = function() { return settings }
    }

    StaticCanvasMap = function(parameters) {
        var settings = jQuery.extend({
                strokeWidth: 1.5,
                height: 200,
                width: $(parameters.element).innerWidth(),
                zoomScaleFactor: 0.9
            }, parameters)
          , features = topojson.feature(settings.topojson,
                                        settings.topojson.objects[parameters.name])

        if (parameters.projection) {
            var dataPath = d3.geo.path().projection(projection = parameters.projection)
        } else {
            var b = d3.geo.bounds(features)
              , projection = d3.geo.mercator()
                                   .scale(1)
                                   .center([(b[1][0] + b[0][0]) / 2,
                                            (b[1][1] + b[0][1]) / 2])
              , dataPath = d3.geo.path().projection(projection)
              , bounds = dataPath.bounds(features)
              , dx = bounds[1][0] - bounds[0][0]
              , dy = bounds[1][1] - bounds[0][1]
              , scale = 0.9 * (settings.width / dx)

            settings.height = dy * settings.width / dx

            projection.scale(scale)
                      .translate([settings.width / 2, settings.height / 2/* + topMargin*/])
        }

        $(this).height(settings.height) //FIXME: Introduce topMargin again

        function init() {
            var canvas = d3.select(settings.element).append("canvas")
                .attr("width", settings.width)
                .attr("height", settings.height)

            var context = canvas.node().getContext("2d")

            context.lineJoin = "round"
            context.lineCap = "round"
            context.strokeStyle = "#fff"

            dataPath.context(context)

            context.clearRect(0, 0, settings.width, settings.height)

            context.save()
            //context.translate(t[0], t[1]);
            //context.scale(s, s);
            //context.lineWidth = 1 / s;

            /*context.beginPath()
            dataPath(features)
            context.fillStyle = "#000"
            context.fill()*/

            for (var i in features.features) {
                console.log("Render " + i)
                console.log(features.features[i])
                var color = settings.fillCallback(features.features[i], i)
                context.beginPath()
                dataPath(features.features[i])
                context.fillStyle = color
                context.fill()
            }

            /*context.beginPath();
            path(land);
            context.fillStyle = "#000";
            context.fill();

            context.beginPath();
            path(boundary);
            context.stroke();*/

            context.restore()

            console.log(self.frameElement)

            d3.select(self.frameElement).style("height", settings.height + "px")

            //Prevent another call to the init method
            this.init = function() {}
        }

        this.init = init
        this.features = function() { return features }
        this.path = function()  { return dataPath }
        this.parameters = function() { return settings }
    }

    ZoomableMap = function(parameters) {
        var staticMap = new StaticMap(parameters)
          , settings = $.extend({
                selectCallback: function(d) {}
            }, staticMap.parameters())
          , selected
          , group

        function init() {
            staticMap.init()

            var svg = d3.select(parameters.element + " svg")
            group = svg.select(".map-polygonGroup")

            svg.select(".map-background")
               .on("click", zoomOut)

            svg.selectAll(".map-polygon")
               .on("click", zoomIn)
               .on("mouseover", function(d, i) {
                   d3.select(this).style("stroke", "black")
                })
               .on("mouseout", function(d, i) {
                    d3.select(this).style("stroke", "unset")
               })
        }

        function zoomOut() {
            selected = undefined

            group.transition()
                 .duration(500)
                 .style("stroke-width", settings.strokeWidth + "px")
                 .attr("transform", "")

            settings.selectCallback(undefined)
        }

        function zoomIn(d) {
            if (selected == d || d == undefined) {
                zoomOut()
                return
            }
            selected = d

            var bounds = staticMap.path().bounds(d),
                dx = bounds[1][0] - bounds[0][0],
                dy = bounds[1][1] - bounds[0][1],
                x = (bounds[0][0] + bounds[1][0]) / 2,
                y = (bounds[0][1] + bounds[1][1]) / 2,
                scale = settings.zoomScaleFactor /
                        Math.max(dx / settings.width, dy / settings.height),
                translate = [settings.width / 2 - scale * x,
                             settings.height / 2 - scale * y/* + topMargin*/],
                strokeWidthScaled = Math.max(0.01, settings.strokeWidth / scale)

            group.transition()
                 .duration(500)
                 .attr("transform", "translate(" + translate + ")scale(" + scale + ")")
                 .style("stroke-width", strokeWidthScaled + "px")

            settings.selectCallback(selected)
        }

        this.init = init
        this.zoomOut = zoomOut
        this.settings = function() { return settings }
    }
}()
<commit_msg>Make the static canvas thing retina ready<commit_after>var StaticMap;
var ZoomableMap;
var StaticCanvasMap;

!function() {
    "use strict";
    StaticMap = function(parameters) {
        var settings = jQuery.extend({
                strokeWidth: 1.5,
                height: 200,
                width: $(parameters.element).innerWidth(),
                zoomScaleFactor: 0.9
            }, parameters)
          , features = topojson.feature(settings.topojson,
                                        settings.topojson.objects[parameters.name])

        if (parameters.projection) {
            var dataPath = d3.geo.path().projection(projection = parameters.projection)
        } else {
            var b = d3.geo.bounds(features)
              , projection = d3.geo.mercator()
                                   .scale(1)
                                   .center([(b[1][0] + b[0][0]) / 2,
                                            (b[1][1] + b[0][1]) / 2])
              , dataPath = d3.geo.path().projection(projection)
              , bounds = dataPath.bounds(features)
              , dx = bounds[1][0] - bounds[0][0]
              , dy = bounds[1][1] - bounds[0][1]
              , scale = 0.9 * (settings.width / dx)

            settings.height = dy * settings.width / dx

            projection.scale(scale)
                      .translate([settings.width / 2, settings.height / 2/* + topMargin*/])
        }

        $(this).height(settings.height) //FIXME: Introduce topMargin again

        function init() {
            var svg = d3.select(settings.element).append("svg")
                        .attr("width", settings.width)
                        .attr("height", settings.height/* + topMargin*/)

            svg.append("rect")
                    .attr("class", "map-background")
                    .attr("width", settings.width)
                    .attr("height", settings.height)

            var g = svg.append("g")
                       .attr("class", "map-polygonGroup")
                       .style("stroke-width", settings.strokeWidth + "px")
                       .selectAll("path")
                       .data(features.features)
                       .enter().append("path")
                       .attr("class", "map-polygon")
                       .attr("d", dataPath)
                       .style("fill", settings.fillCallback)

            //Prevent another call to the init method
            this.init = function() {}
        }

        this.init = init
        this.features = function() { return features }
        this.path = function()  { return dataPath }
        this.parameters = function() { return settings }
    }

    StaticCanvasMap = function(parameters) {
        var settings = jQuery.extend({
                strokeWidth: 1.5,
                height: 200,
                width: $(parameters.element).innerWidth(),
                zoomScaleFactor: 0.9
            }, parameters)
          , features = topojson.feature(settings.topojson,
                                        settings.topojson.objects[parameters.name])
          , ratio = 1

        if (parameters.projection) {
            var dataPath = d3.geo.path().projection(projection = parameters.projection)
        } else {
            var b = d3.geo.bounds(features)
              , projection = d3.geo.mercator()
                                   .scale(1)
                                   .center([(b[1][0] + b[0][0]) / 2,
                                            (b[1][1] + b[0][1]) / 2])
              , dataPath = d3.geo.path().projection(projection)
              , bounds = dataPath.bounds(features)
              , dx = bounds[1][0] - bounds[0][0]
              , dy = bounds[1][1] - bounds[0][1]
              , scale = 0.9 * (settings.width / dx)

            settings.height = dy * settings.width / dx

            projection.scale(scale)
                      .translate([settings.width / 2, settings.height / 2/* + topMargin*/])
        }

        $(this).height(settings.height) //FIXME: Introduce topMargin again

        function init() {
            var canvas = d3.select(settings.element).append("canvas")
              , context = canvas.node().getContext("2d")
              , devicePixelRatio = window.devicePixelRatio || 1
              , backingStoreRatio = context.webkitBackingStorePixelRatio ||
                                    context.mozBackingStorePixelRatio ||
                                    context.msBackingStorePixelRatio ||
                                    context.oBackingStorePixelRatio ||
                                    context.backingStorePixelRatio || 1
              , ratio = devicePixelRatio / backingStoreRatio

            canvas.attr("width", settings.width * ratio)
            canvas.attr("height", settings.height * ratio)
            canvas.style("width", settings.width + "px")
            canvas.style("height", settings.height + "px")
            context.lineJoin = "round"
            context.lineCap = "round"

            dataPath.context(context)

            context.clearRect(0, 0, settings.width, settings.height)

            context.save()

            context.scale(ratio, ratio)

            for (var i in features.features) {
                var color = settings.fillCallback(features.features[i], i)
                context.beginPath()
                dataPath(features.features[i])
                context.fillStyle = color
                context.fill()
            }

            context.restore()

            //Prevent another call to the init method
            this.init = function() {}
        }

        this.init = init
        this.features = function() { return features }
        this.path = function()  { return dataPath }
        this.parameters = function() { return settings }
    }

    ZoomableMap = function(parameters) {
        var staticMap = new StaticMap(parameters)
          , settings = $.extend({
                selectCallback: function(d) {}
            }, staticMap.parameters())
          , selected
          , group

        function init() {
            staticMap.init()

            var svg = d3.select(parameters.element + " svg")
            group = svg.select(".map-polygonGroup")

            svg.select(".map-background")
               .on("click", zoomOut)

            svg.selectAll(".map-polygon")
               .on("click", zoomIn)
               .on("mouseover", function(d, i) {
                   d3.select(this).style("stroke", "black")
                })
               .on("mouseout", function(d, i) {
                    d3.select(this).style("stroke", "unset")
               })
        }

        function zoomOut() {
            selected = undefined

            group.transition()
                 .duration(500)
                 .style("stroke-width", settings.strokeWidth + "px")
                 .attr("transform", "")

            settings.selectCallback(undefined)
        }

        function zoomIn(d) {
            if (selected == d || d == undefined) {
                zoomOut()
                return
            }
            selected = d

            var bounds = staticMap.path().bounds(d),
                dx = bounds[1][0] - bounds[0][0],
                dy = bounds[1][1] - bounds[0][1],
                x = (bounds[0][0] + bounds[1][0]) / 2,
                y = (bounds[0][1] + bounds[1][1]) / 2,
                scale = settings.zoomScaleFactor /
                        Math.max(dx / settings.width, dy / settings.height),
                translate = [settings.width / 2 - scale * x,
                             settings.height / 2 - scale * y/* + topMargin*/],
                strokeWidthScaled = Math.max(0.01, settings.strokeWidth / scale)

            group.transition()
                 .duration(500)
                 .attr("transform", "translate(" + translate + ")scale(" + scale + ")")
                 .style("stroke-width", strokeWidthScaled + "px")

            settings.selectCallback(selected)
        }

        this.init = init
        this.zoomOut = zoomOut
        this.settings = function() { return settings }
    }
}()
<|endoftext|>


<commit_before>$(function() {
	var $globalBar = $( ".global-bar");
  var $smartBar = $(".notification");

	if($globalBar.length > 0) {
	    window.globalBar = $globalBar.clone();
	    $globalBar.remove();
    	newbar();
      $smartBar.addClass('white');
  }

  else if(($smartBar).hasClass('white')) {
      $smartBar.addClass('tan');
    }

  else if(($smartBar).hasClass('tan')) {
      $smartBar.addClass('sky');
    }

  else {
    $('.notification').remove();
    $('body').prepend(window.globalBar);
  }

function newbar() {
    $("body").prepend(
     "
Read the ePaper edition. The complete print edition, in its exact layout. Browse the print edition page by page, including stories and ads.<button class='notification__toggle'><svg class='icon-close'><use xlink:href='#icon-close' /></svg></button>
");
     $("body").append(
     "<svg display='none' xmlns='http://www.w3.org/2000/svg'><defs><symbol id='icon-close' viewBox='0 0 100 100'><path d='M76.83,32.561L59.392,50L76.83,67.439c2.594,2.594,2.594,6.798,0,9.392 c-1.296,1.296-2.995,1.945-4.694,1.945c-1.7,0-3.399-0.648-4.695-1.945L50,59.391l-17.44,17.44 c-1.296,1.296-2.995,1.945-4.695,1.945c-1.699,0-3.397-0.648-4.694-1.945c-2.594-2.593-2.594-6.797,0-9.392L40.608,50L23.17,32.561 c-2.594-2.594-2.594-6.798,0-9.392c2.593-2.592,6.795-2.592,9.389,0L50,40.609l17.44-17.44c2.594-2.592,6.796-2.592,9.389,0C79.424,25.763,79.424,29.967,76.83,32.561z'></path></symbol></defs></svg>")

    $('.notification__toggle').click(function() {

      $('.notification').slideToggle('300');

      return false;

  });
  }

});<commit_msg>changes<commit_after>$(function() {
	var $globalBar = $( ".global-bar");
  var $smartBar = $(".notification");

	if($globalBar.length > 0) {
	    window.globalBar = $globalBar.clone();
	    $globalBar.remove();
    	newbar();
      $smartBar.addClass('white');
  }

  else if(($smartBar).hasClass('white')) {
      $smartBar.addClass('tan');
    }

  else if(($smartBar).hasClass('tan')) {
      $smartBar.addClass('sky');
    }

  else {
    $('.notification').remove();
    $('body').prepend(window.globalBar);
  }

function newbar() {
    $("body").prepend(
     "
Read the ePaper edition. The complete print edition, in its exact layout. Browse the print edition page by page, including stories and ads.<button class='notification__toggle'><svg class='icon-close'><use xlink:href='#icon-close' /></svg></button>
");
     $("body").append(
     "<svg display='none' xmlns='http://www.w3.org/2000/svg'><defs><symbol id='icon-close' viewBox='0 0 100 100'><path d='M76.83,32.561L59.392,50L76.83,67.439c2.594,2.594,2.594,6.798,0,9.392 c-1.296,1.296-2.995,1.945-4.694,1.945c-1.7,0-3.399-0.648-4.695-1.945L50,59.391l-17.44,17.44 c-1.296,1.296-2.995,1.945-4.695,1.945c-1.699,0-3.397-0.648-4.694-1.945c-2.594-2.593-2.594-6.797,0-9.392L40.608,50L23.17,32.561 c-2.594-2.594-2.594-6.798,0-9.392c2.593-2.592,6.795-2.592,9.389,0L50,40.609l17.44-17.44c2.594-2.592,6.796-2.592,9.389,0C79.424,25.763,79.424,29.967,76.83,32.561z'></path></symbol></defs></svg>")

    $('.notification__toggle').click(function() {

      $('.notification').slideToggle('300');

      return false;

  });
  }

});<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const AWS = require('aws-sdk');
const response = require('cfn-response');
const lambda = new AWS.Lambda();

// Helpers

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

/**
 * Get function configuration by its name
 *
 * @return {Promise} which resolves into the function configuration
 */
function getFunction(name) {
    return new Promise((resolve, reject) => {
        lambda.getFunctionConfiguration({
            FunctionName: name
        }, function(err, data) {
            if (err) return reject(err);
            resolve(data);
        });
    });
}

/**
 * Get all function versions
 *
 * @return {Promise} which resolves into an array of version configurations
 */
function getFunctionVersions(name, marker) {
    // Grab functions
    return new Promise((resolve, reject) => {
        lambda.listVersionsByFunction({
            FunctionName: name,
            Marker: marker
        }, function(err, data) {
            if (err) return reject(err);

            // Check if we can grab even more
            if (data.NextMarker) {
                return getFunctionVersions(name, data.NextMarker).then((versions) => {
                    resolve(data.Versions.concat(versions));
                });
            }

            resolve(data.Versions);
        });
    });
}

/**
 * Publish a new Lambda function version
 *
 * @return {Promise} which resolves into the newly published version
 */
function functionPublishVersion(name, description, hash) {
    return new Promise((resolve, reject) => {
        lambda.publishVersion({
            FunctionName: name,
            Description: description,
            CodeSha256: hash
        }, function(err, data) {
            if (err) return reject(err);
            resolve(data);
        });
    });
}

exports.handler = function(event, context) {
    // Determine the nature of this request
    const command = event.RequestType;

    // Log the event (this will help debugging)
    console.log('Handle ' + command + ' request');  // eslint-disable-line no-console
    console.log('Event', JSON.stringify(event, null, 4));  // eslint-disable-line no-console

    // Validate context
    if (!event) {
        console.error(new Error('Context MUST have an event'));
        return response.send(event, context, response.FAILED, {});
    }

    const properties = event.ResourceProperties;

    if (!properties) {
        console.error(new Error('Context event must have a \'ResourceProperties\' key'));
        return response.send(event, context, response.FAILED, {});
    }

    // Ignore delete event
    if (command === 'Delete') {
        console.log('Ignore delete event');
        return response.send(event, context, response.SUCCESS, {});
    }

    // Grab the function first
    getFunction(properties.FunctionName).then(function(fn) {
        // Then grab all versions
        return getFunctionVersions(fn.FunctionName).then((versions) => {
            // Try to find one that matches the function configuration
            versions = versions.filter((version) => {
                // Ignore the latest pseudo-version
                return version.Version !== '$LATEST';
            });

            const trimmedFn = _.pick(fn, 'LastModified');
            return {
                fn: fn,
                version: _.find(versions, trimmedFn)
            };
        });
    }).then((results) => {
        return delay(getRandomInt(5000)).then(function() {
            return results;
        });
    }).then((results) => {
        const fn = results.fn;
        const version = results.version;

        if (!version) {
            console.log('Publish a new version');
            return functionPublishVersion(fn.FunctionName, properties.Description, properties.CodeSha256);
        }

        return version;
    }).then((version) => {
        // Make sure the Arn property is populated
        version.Arn = version.FunctionArn;
        response.send(event, context, response.SUCCESS, version, version.FunctionArn);
    }).catch((err) => {
        console.error('Error', err);
        response.send(event, context, response.FAILED, {});
    });
};
<commit_msg>delay api calls by rnd 1-15s<commit_after>'use strict';

const _ = require('lodash');
const AWS = require('aws-sdk');
const response = require('cfn-response');
const lambda = new AWS.Lambda();

// Helpers

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

/**
 * Get function configuration by its name
 *
 * @return {Promise} which resolves into the function configuration
 */
function getFunction(name) {
    console.log('[getFunction]', name);
    return new Promise((resolve, reject) => {
        lambda.getFunctionConfiguration({
            FunctionName: name
        }, function(err, data) {
            if (err) return reject(err);
            resolve(data);
        });
    });
}

/**
 * Get all function versions
 *
 * @return {Promise} which resolves into an array of version configurations
 */
function getFunctionVersions(name, marker) {
    // Grab functions
    console.log('[getFunctionVersions]', name);
    return new Promise((resolve, reject) => {
        lambda.listVersionsByFunction({
            FunctionName: name,
            Marker: marker
        }, function(err, data) {
            if (err) return reject(err);

            // Check if we can grab even more
            if (data.NextMarker) {
                return getFunctionVersions(name, data.NextMarker).then((versions) => {
                    resolve(data.Versions.concat(versions));
                });
            }

            resolve(data.Versions);
        });
    });
}

/**
 * Publish a new Lambda function version
 *
 * @return {Promise} which resolves into the newly published version
 */
function functionPublishVersion(name, description, hash) {
    console.log('[functionPublishVersion]', name);
    return new Promise((resolve, reject) => {
        lambda.publishVersion({
            FunctionName: name,
            Description: description,
            CodeSha256: hash
        }, function(err, data) {
            if (err) return reject(err);
            resolve(data);
        });
    });
}

exports.handler = function(event, context) {
    // Determine the nature of this request
    const command = event.RequestType;

    // Log the event (this will help debugging)
    console.log('Handle ' + command + ' request');  // eslint-disable-line no-console
    console.log('Event', JSON.stringify(event, null, 4));  // eslint-disable-line no-console

    // Validate context
    if (!event) {
        console.error(new Error('Context MUST have an event'));
        return response.send(event, context, response.FAILED, {});
    }

    const properties = event.ResourceProperties;

    if (!properties) {
        console.error(new Error('Context event must have a \'ResourceProperties\' key'));
        return response.send(event, context, response.FAILED, {});
    }

    // Ignore delete event
    if (command === 'Delete') {
        console.log('Ignore delete event');
        return response.send(event, context, response.SUCCESS, {});
    }

    delay(getRandomInt(15000)).then(() => {
        // Grab the function first
        return getFunction(properties.FunctionName).then(function(fn) {
            // Then grab all versions
            return getFunctionVersions(fn.FunctionName).then((versions) => {
                // Try to find one that matches the function configuration
                versions = versions.filter((version) => {
                    // Ignore the latest pseudo-version
                    return version.Version !== '$LATEST';
                });

                const trimmedFn = _.pick(fn, 'LastModified');
                return {
                    fn: fn,
                    version: _.find(versions, trimmedFn)
                };
            });
        });
    }).then((results) => {
        return delay(getRandomInt(5000)).then(function() {
            return results;
        });
    }).then((results) => {
        const fn = results.fn;
        const version = results.version;

        if (!version) {
            console.log('Publish a new version');
            return functionPublishVersion(fn.FunctionName, properties.Description, properties.CodeSha256);
        }

        return version;
    }).then((version) => {
        // Make sure the Arn property is populated
        version.Arn = version.FunctionArn;
        response.send(event, context, response.SUCCESS, version, version.FunctionArn);
    }).catch((err) => {
        console.error('Error', err);
        response.send(event, context, response.FAILED, {});
    });
};
<|endoftext|>


<commit_before>/*
 * L.Map is the central class of the API - it is used to create a map.
 */

L.Map = L.Class.extend({
	includes: L.Mixin.Events,

	options: {
		// projection
		crs: L.CRS.EPSG3857 || L.CRS.EPSG4326,
		scale: function(zoom) { return 256 * (1 << zoom); },

		// state
		center: null,
		zoom: null,
		layers: [],

		// interaction
		dragging: true,
		touchZoom: L.Browser.touch && !L.Browser.android,
		scrollWheelZoom: !L.Browser.touch,
		doubleClickZoom: true,
		shiftDragZoom: true,

		// controls
		zoomControl: true,
		attributionControl: true,

		// animation
		fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android,
		zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android && !L.Browser.mobileOpera,

		// misc
		trackResize: true,
		closePopupOnClick: true
	},

	// constructor

	initialize: function(/*HTMLElement or String*/ id, /*Object*/ options) {
		L.Util.setOptions(this, options);

		this._container = L.DomUtil.get(id);

		this._initLayout();

		if (L.DomEvent) {
			this._initEvents();
			if (L.Handler) { this._initInteraction(); }
			if (L.Control) { this._initControls(); }
		}

		var center = this.options.center,
			zoom = this.options.zoom;

		if (center !== null && zoom !== null) {
			this.setView(center, zoom, true);
		}

		var layers = this.options.layers;
		layers = (layers instanceof Array ? layers : [layers]);
		this._tileLayersNum = 0;
		this._initLayers(layers);
	},

	// public methods that modify map state

	// replaced by animation-powered implementation in Map.PanAnimation.js
	setView: function(center, zoom, forceReset) {
		// reset the map view
		this._resetView(center, this._limitZoom(zoom));
		return this;
	},

	setZoom: function(/*Number*/ zoom) {
		return this.setView(this.getCenter(), zoom);
	},

	zoomIn: function() {
		return this.setZoom(this._zoom + 1);
	},

	zoomOut: function() {
		return this.setZoom(this._zoom - 1);
	},

	fitBounds: function(/*LatLngBounds*/ bounds) {
		var zoom = this.getBoundsZoom(bounds);
		return this.setView(bounds.getCenter(), zoom);
	},

	fitWorld: function() {
		var sw = new L.LatLng(-60, -170),
			ne = new L.LatLng(85, 179);
		return this.fitBounds(new L.LatLngBounds(sw, ne));
	},

	panTo: function(/*LatLng*/ center) {
		return this.setView(center, this._zoom);
	},

	panBy: function(/*Point*/ offset) {
		// replaced with animated panBy in Map.Animation.js
		this.fire('movestart');

		this._rawPanBy(offset);

		this.fire('move');
		this.fire('moveend');

		return this;
	},

	addLayer: function(layer, insertAtTheTop) {
		var id = L.Util.stamp(layer);

		if (this._layers[id]) return this;

		this._layers[id] = layer;

		if (layer.options && !isNaN(layer.options.maxZoom)) {
			this._layersMaxZoom = Math.max(this._layersMaxZoom || 0, layer.options.maxZoom);
		}
		if (layer.options && !isNaN(layer.options.minZoom)) {
			this._layersMinZoom = Math.min(this._layersMinZoom || Infinity, layer.options.minZoom);
		}
		//TODO getMaxZoom, getMinZoom in ILayer (instead of options)

		if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
			this._tileLayersNum++;
			layer.on('load', this._onTileLayerLoad, this);
		}
		if (this.attributionControl && layer.getAttribution) {
			this.attributionControl.addAttribution(layer.getAttribution());
		}

		var onMapLoad = function() {
			layer.onAdd(this, insertAtTheTop);
			this.fire('layeradd', {layer: layer});
		};

		if (this._loaded) {
			onMapLoad.call(this);
		} else {
			this.on('load', onMapLoad, this);
		}

		return this;
	},

	removeLayer: function(layer) {
		var id = L.Util.stamp(layer);

		if (this._layers[id]) {
			layer.onRemove(this);
			delete this._layers[id];

			if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
				this._tileLayersNum--;
				layer.off('load', this._onTileLayerLoad, this);
			}
			if (this.attributionControl && layer.getAttribution) {
				this.attributionControl.removeAttribution(layer.getAttribution());
			}

			this.fire('layerremove', {layer: layer});
		}
		return this;
	},

	hasLayer: function(layer) {
		var id = L.Util.stamp(layer);

		return (id in this._layers);
	},

	invalidateSize: function() {
		var oldSize = this.getSize();
		this._sizeChanged = true;
		this._rawPanBy(oldSize.subtract(this.getSize()).divideBy(2));

		this.fire('move');

		clearTimeout(this._sizeTimer);
		this._sizeTimer = setTimeout(L.Util.bind(function() {
			this.fire('moveend');
		}, this), 200);

		return this;
	},

	// public methods for getting map state

	getCenter: function(/*Boolean*/ unbounded) {
		var viewHalf = this.getSize().divideBy(2),
			centerPoint = this._getTopLeftPoint().add(viewHalf);
		return this.unproject(centerPoint, this._zoom, unbounded);
	},

	getZoom: function() {
		return this._zoom;
	},

	getBounds: function() {
		var bounds = this.getPixelBounds(),
			sw = this.unproject(new L.Point(bounds.min.x, bounds.max.y)),
			ne = this.unproject(new L.Point(bounds.max.x, bounds.min.y));
		return new L.LatLngBounds(sw, ne);
	},

	getMinZoom: function() {
		return isNaN(this.options.minZoom) ?  this._layersMinZoom || 0 : this.options.minZoom;
	},

	getMaxZoom: function() {
		return isNaN(this.options.maxZoom) ?  this._layersMaxZoom || Infinity : this.options.maxZoom;
	},

	getBoundsZoom: function(/*LatLngBounds*/ bounds) {
		var size = this.getSize(),
			zoom = this.getMinZoom(),
			maxZoom = this.getMaxZoom(),
			ne = bounds.getNorthEast(),
			sw = bounds.getSouthWest(),
			boundsSize,
			nePoint, swPoint;
		do {
			zoom++;
			nePoint = this.project(ne, zoom);
			swPoint = this.project(sw, zoom);
			boundsSize = new L.Point(nePoint.x - swPoint.x, swPoint.y - nePoint.y);
		} while ((boundsSize.x <= size.x) &&
				 (boundsSize.y <= size.y) && (zoom <= maxZoom));

		return zoom - 1;
	},

	getSize: function() {
		if (!this._size || this._sizeChanged) {
			this._size = new L.Point(this._container.clientWidth, this._container.clientHeight);
			this._sizeChanged = false;
		}
		return this._size;
	},

	getPixelBounds: function() {
		var topLeftPoint = this._getTopLeftPoint(),
			size = this.getSize();
		return new L.Bounds(topLeftPoint, topLeftPoint.add(size));
	},

	getPixelOrigin: function() {
		return this._initialTopLeftPoint;
	},

	getPanes: function() {
		return this._panes;
	},

	// conversion methods

	mouseEventToContainerPoint: function(/*MouseEvent*/ e) {
		return L.DomEvent.getMousePosition(e, this._container);
	},

	mouseEventToLayerPoint: function(/*MouseEvent*/ e) {
		return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
	},

	mouseEventToLatLng: function(/*MouseEvent*/ e) {
		return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
	},

	containerPointToLayerPoint: function(/*Point*/ point) {
		return point.subtract(L.DomUtil.getPosition(this._mapPane));
	},

	layerPointToContainerPoint: function(/*Point*/ point) {
		return point.add(L.DomUtil.getPosition(this._mapPane));
	},

	layerPointToLatLng: function(/*Point*/ point) {
		return this.unproject(point.add(this._initialTopLeftPoint));
	},

	latLngToLayerPoint: function(/*LatLng*/ latlng) {
		return this.project(latlng)._round()._subtract(this._initialTopLeftPoint);
	},

	project: function(/*LatLng*/ latlng, /*(optional) Number*/ zoom)/*-> Point*/ {
		zoom = (typeof zoom == 'undefined' ? this._zoom : zoom);
		return this.options.crs.latLngToPoint(latlng, this.options.scale(zoom));
	},

	unproject: function(/*Point*/ point, /*(optional) Number*/ zoom, /*(optional) Boolean*/ unbounded)/*-> Object*/ {
		zoom = (typeof zoom == 'undefined' ? this._zoom : zoom);
		return this.options.crs.pointToLatLng(point, this.options.scale(zoom), unbounded);
	},

	// private methods that modify map state

	_initLayout: function() {
		var container = this._container;

		container.innerHTML = '';

		container.className += ' leaflet-container';

		if (this.options.fadeAnimation) {
			container.className += ' leaflet-fade-anim';
		}

		var position = L.DomUtil.getStyle(container, 'position');
		if (position != 'absolute' && position != 'relative') {
			container.style.position = 'relative';
		}

		this._initPanes();

		if (this._initControlPos) this._initControlPos();
	},

	_initPanes: function() {
		var panes = this._panes = {};

		this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);

		this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
		this._objectsPane = panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);

		panes.shadowPane = this._createPane('leaflet-shadow-pane');
		panes.overlayPane = this._createPane('leaflet-overlay-pane');
		panes.markerPane = this._createPane('leaflet-marker-pane');
		panes.popupPane = this._createPane('leaflet-popup-pane');
	},

	_createPane: function(className, container) {
		return L.DomUtil.create('div', className, container || this._objectsPane);
	},

	_resetView: function(center, zoom, preserveMapOffset) {
		var zoomChanged = (this._zoom != zoom);

		this.fire('movestart');

		this._zoom = zoom;

		this._initialTopLeftPoint = this._getNewTopLeftPoint(center);

		if (!preserveMapOffset) {
			L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
		} else {
			var offset = L.DomUtil.getPosition(this._mapPane);
			this._initialTopLeftPoint._add(offset);
		}

		this._tileLayersToLoad = this._tileLayersNum;
		this.fire('viewreset', {hard: !preserveMapOffset});

		this.fire('move');
		if (zoomChanged) { this.fire('zoomend'); }
		this.fire('moveend');

		if (!this._loaded) {
			this._loaded = true;
			this.fire('load');
		}
	},

	_initLayers: function(layers) {
		this._layers = {};
		for (var i = 0, len = layers.length; i < len; i++) {
			this.addLayer(layers[i]);
		}
	},

	_initControls: function() {
		if (this.options.zoomControl) {
			this.addControl(new L.Control.Zoom());
		}
		if (this.options.attributionControl) {
			this.attributionControl = new L.Control.Attribution();
			this.addControl(this.attributionControl);
		}
	},

	_rawPanBy: function(offset) {
		var mapPaneOffset = L.DomUtil.getPosition(this._mapPane);
		L.DomUtil.setPosition(this._mapPane, mapPaneOffset.subtract(offset));
	},

	// map events

	_initEvents: function() {
		L.DomEvent.addListener(this._container, 'click', this._onMouseClick, this);

		var events = ['dblclick', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove'];
		for (var i = 0; i < events.length; i++) {
			L.DomEvent.addListener(this._container, events[i], this._fireMouseEvent, this);
		}

		if (this.options.trackResize) {
			L.DomEvent.addListener(window, 'resize', this._onResize, this);
		}
	},

	_onResize: function() {
		L.Util.requestAnimFrame(this.invalidateSize, this, false, this._container);
	},

	_onMouseClick: function(e) {
		if (this.dragging && this.dragging.moved()) { return; }

		this.fire('pre' + e.type);
		this._fireMouseEvent(e);
	},

	_fireMouseEvent: function(e) {
		var type = e.type;
		type = (type == 'mouseenter' ? 'mouseover' : (type == 'mouseleave' ? 'mouseout' : type));
		if (!this.hasEventListeners(type)) { return; }
		this.fire(type, {
			latlng: this.mouseEventToLatLng(e),
			layerPoint: this.mouseEventToLayerPoint(e)
		});
	},

	_initInteraction: function() {
		var handlers = {
			dragging: L.Handler.MapDrag,
			touchZoom: L.Handler.TouchZoom,
			doubleClickZoom: L.Handler.DoubleClickZoom,
			scrollWheelZoom: L.Handler.ScrollWheelZoom,
			shiftDragZoom: L.Handler.ShiftDragZoom
		};
		for (var i in handlers) {
			if (handlers.hasOwnProperty(i) && handlers[i]) {
				this[i] = new handlers[i](this);
				if (this.options[i]) this[i].enable();
			}
		}
	},

	_onTileLayerLoad: function() {
		// clear scaled tiles after all new tiles are loaded (for performance)
		this._tileLayersToLoad--;
		if (this._tileLayersNum && !this._tileLayersToLoad && this._tileBg) {
			clearTimeout(this._clearTileBgTimer);
			this._clearTileBgTimer = setTimeout(L.Util.bind(this._clearTileBg, this), 500);
		}
	},

	// private methods for getting map state

	_getTopLeftPoint: function() {
		if (!this._loaded) throw new Error('Set map center and zoom first.');
		var offset = L.DomUtil.getPosition(this._mapPane);
		return this._initialTopLeftPoint.subtract(offset);
	},

	_getNewTopLeftPoint: function(center) {
		var viewHalf = this.getSize().divideBy(2);
		return this.project(center).subtract(viewHalf).round();
	},

	_limitZoom: function(zoom) {
		var min = this.getMinZoom();
		var max = this.getMaxZoom();
		return Math.max(min, Math.min(max, zoom));
	}
});
<commit_msg>if map is not loaded don't fire mouse events<commit_after>/*
 * L.Map is the central class of the API - it is used to create a map.
 */

L.Map = L.Class.extend({
	includes: L.Mixin.Events,

	options: {
		// projection
		crs: L.CRS.EPSG3857 || L.CRS.EPSG4326,
		scale: function(zoom) { return 256 * (1 << zoom); },

		// state
		center: null,
		zoom: null,
		layers: [],

		// interaction
		dragging: true,
		touchZoom: L.Browser.touch && !L.Browser.android,
		scrollWheelZoom: !L.Browser.touch,
		doubleClickZoom: true,
		shiftDragZoom: true,

		// controls
		zoomControl: true,
		attributionControl: true,

		// animation
		fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android,
		zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android && !L.Browser.mobileOpera,

		// misc
		trackResize: true,
		closePopupOnClick: true
	},

	// constructor

	initialize: function(/*HTMLElement or String*/ id, /*Object*/ options) {
		L.Util.setOptions(this, options);

		this._container = L.DomUtil.get(id);

		this._initLayout();

		if (L.DomEvent) {
			this._initEvents();
			if (L.Handler) { this._initInteraction(); }
			if (L.Control) { this._initControls(); }
		}

		var center = this.options.center,
			zoom = this.options.zoom;

		if (center !== null && zoom !== null) {
			this.setView(center, zoom, true);
		}

		var layers = this.options.layers;
		layers = (layers instanceof Array ? layers : [layers]);
		this._tileLayersNum = 0;
		this._initLayers(layers);
	},

	// public methods that modify map state

	// replaced by animation-powered implementation in Map.PanAnimation.js
	setView: function(center, zoom, forceReset) {
		// reset the map view
		this._resetView(center, this._limitZoom(zoom));
		return this;
	},

	setZoom: function(/*Number*/ zoom) {
		return this.setView(this.getCenter(), zoom);
	},

	zoomIn: function() {
		return this.setZoom(this._zoom + 1);
	},

	zoomOut: function() {
		return this.setZoom(this._zoom - 1);
	},

	fitBounds: function(/*LatLngBounds*/ bounds) {
		var zoom = this.getBoundsZoom(bounds);
		return this.setView(bounds.getCenter(), zoom);
	},

	fitWorld: function() {
		var sw = new L.LatLng(-60, -170),
			ne = new L.LatLng(85, 179);
		return this.fitBounds(new L.LatLngBounds(sw, ne));
	},

	panTo: function(/*LatLng*/ center) {
		return this.setView(center, this._zoom);
	},

	panBy: function(/*Point*/ offset) {
		// replaced with animated panBy in Map.Animation.js
		this.fire('movestart');

		this._rawPanBy(offset);

		this.fire('move');
		this.fire('moveend');

		return this;
	},

	addLayer: function(layer, insertAtTheTop) {
		var id = L.Util.stamp(layer);

		if (this._layers[id]) return this;

		this._layers[id] = layer;

		if (layer.options && !isNaN(layer.options.maxZoom)) {
			this._layersMaxZoom = Math.max(this._layersMaxZoom || 0, layer.options.maxZoom);
		}
		if (layer.options && !isNaN(layer.options.minZoom)) {
			this._layersMinZoom = Math.min(this._layersMinZoom || Infinity, layer.options.minZoom);
		}
		//TODO getMaxZoom, getMinZoom in ILayer (instead of options)

		if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
			this._tileLayersNum++;
			layer.on('load', this._onTileLayerLoad, this);
		}
		if (this.attributionControl && layer.getAttribution) {
			this.attributionControl.addAttribution(layer.getAttribution());
		}

		var onMapLoad = function() {
			layer.onAdd(this, insertAtTheTop);
			this.fire('layeradd', {layer: layer});
		};

		if (this._loaded) {
			onMapLoad.call(this);
		} else {
			this.on('load', onMapLoad, this);
		}

		return this;
	},

	removeLayer: function(layer) {
		var id = L.Util.stamp(layer);

		if (this._layers[id]) {
			layer.onRemove(this);
			delete this._layers[id];

			if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
				this._tileLayersNum--;
				layer.off('load', this._onTileLayerLoad, this);
			}
			if (this.attributionControl && layer.getAttribution) {
				this.attributionControl.removeAttribution(layer.getAttribution());
			}

			this.fire('layerremove', {layer: layer});
		}
		return this;
	},

	hasLayer: function(layer) {
		var id = L.Util.stamp(layer);

		return (id in this._layers);
	},

	invalidateSize: function() {
		var oldSize = this.getSize();
		this._sizeChanged = true;
		this._rawPanBy(oldSize.subtract(this.getSize()).divideBy(2));

		this.fire('move');

		clearTimeout(this._sizeTimer);
		this._sizeTimer = setTimeout(L.Util.bind(function() {
			this.fire('moveend');
		}, this), 200);

		return this;
	},

	// public methods for getting map state

	getCenter: function(/*Boolean*/ unbounded) {
		var viewHalf = this.getSize().divideBy(2),
			centerPoint = this._getTopLeftPoint().add(viewHalf);
		return this.unproject(centerPoint, this._zoom, unbounded);
	},

	getZoom: function() {
		return this._zoom;
	},

	getBounds: function() {
		var bounds = this.getPixelBounds(),
			sw = this.unproject(new L.Point(bounds.min.x, bounds.max.y)),
			ne = this.unproject(new L.Point(bounds.max.x, bounds.min.y));
		return new L.LatLngBounds(sw, ne);
	},

	getMinZoom: function() {
		return isNaN(this.options.minZoom) ?  this._layersMinZoom || 0 : this.options.minZoom;
	},

	getMaxZoom: function() {
		return isNaN(this.options.maxZoom) ?  this._layersMaxZoom || Infinity : this.options.maxZoom;
	},

	getBoundsZoom: function(/*LatLngBounds*/ bounds) {
		var size = this.getSize(),
			zoom = this.getMinZoom(),
			maxZoom = this.getMaxZoom(),
			ne = bounds.getNorthEast(),
			sw = bounds.getSouthWest(),
			boundsSize,
			nePoint, swPoint;
		do {
			zoom++;
			nePoint = this.project(ne, zoom);
			swPoint = this.project(sw, zoom);
			boundsSize = new L.Point(nePoint.x - swPoint.x, swPoint.y - nePoint.y);
		} while ((boundsSize.x <= size.x) &&
				 (boundsSize.y <= size.y) && (zoom <= maxZoom));

		return zoom - 1;
	},

	getSize: function() {
		if (!this._size || this._sizeChanged) {
			this._size = new L.Point(this._container.clientWidth, this._container.clientHeight);
			this._sizeChanged = false;
		}
		return this._size;
	},

	getPixelBounds: function() {
		var topLeftPoint = this._getTopLeftPoint(),
			size = this.getSize();
		return new L.Bounds(topLeftPoint, topLeftPoint.add(size));
	},

	getPixelOrigin: function() {
		return this._initialTopLeftPoint;
	},

	getPanes: function() {
		return this._panes;
	},

	// conversion methods

	mouseEventToContainerPoint: function(/*MouseEvent*/ e) {
		return L.DomEvent.getMousePosition(e, this._container);
	},

	mouseEventToLayerPoint: function(/*MouseEvent*/ e) {
		return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
	},

	mouseEventToLatLng: function(/*MouseEvent*/ e) {
		return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
	},

	containerPointToLayerPoint: function(/*Point*/ point) {
		return point.subtract(L.DomUtil.getPosition(this._mapPane));
	},

	layerPointToContainerPoint: function(/*Point*/ point) {
		return point.add(L.DomUtil.getPosition(this._mapPane));
	},

	layerPointToLatLng: function(/*Point*/ point) {
		return this.unproject(point.add(this._initialTopLeftPoint));
	},

	latLngToLayerPoint: function(/*LatLng*/ latlng) {
		return this.project(latlng)._round()._subtract(this._initialTopLeftPoint);
	},

	project: function(/*LatLng*/ latlng, /*(optional) Number*/ zoom)/*-> Point*/ {
		zoom = (typeof zoom == 'undefined' ? this._zoom : zoom);
		return this.options.crs.latLngToPoint(latlng, this.options.scale(zoom));
	},

	unproject: function(/*Point*/ point, /*(optional) Number*/ zoom, /*(optional) Boolean*/ unbounded)/*-> Object*/ {
		zoom = (typeof zoom == 'undefined' ? this._zoom : zoom);
		return this.options.crs.pointToLatLng(point, this.options.scale(zoom), unbounded);
	},

	// private methods that modify map state

	_initLayout: function() {
		var container = this._container;

		container.innerHTML = '';

		container.className += ' leaflet-container';

		if (this.options.fadeAnimation) {
			container.className += ' leaflet-fade-anim';
		}

		var position = L.DomUtil.getStyle(container, 'position');
		if (position != 'absolute' && position != 'relative') {
			container.style.position = 'relative';
		}

		this._initPanes();

		if (this._initControlPos) this._initControlPos();
	},

	_initPanes: function() {
		var panes = this._panes = {};

		this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);

		this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
		this._objectsPane = panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);

		panes.shadowPane = this._createPane('leaflet-shadow-pane');
		panes.overlayPane = this._createPane('leaflet-overlay-pane');
		panes.markerPane = this._createPane('leaflet-marker-pane');
		panes.popupPane = this._createPane('leaflet-popup-pane');
	},

	_createPane: function(className, container) {
		return L.DomUtil.create('div', className, container || this._objectsPane);
	},

	_resetView: function(center, zoom, preserveMapOffset) {
		var zoomChanged = (this._zoom != zoom);

		this.fire('movestart');

		this._zoom = zoom;

		this._initialTopLeftPoint = this._getNewTopLeftPoint(center);

		if (!preserveMapOffset) {
			L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
		} else {
			var offset = L.DomUtil.getPosition(this._mapPane);
			this._initialTopLeftPoint._add(offset);
		}

		this._tileLayersToLoad = this._tileLayersNum;
		this.fire('viewreset', {hard: !preserveMapOffset});

		this.fire('move');
		if (zoomChanged) { this.fire('zoomend'); }
		this.fire('moveend');

		if (!this._loaded) {
			this._loaded = true;
			this.fire('load');
		}
	},

	_initLayers: function(layers) {
		this._layers = {};
		for (var i = 0, len = layers.length; i < len; i++) {
			this.addLayer(layers[i]);
		}
	},

	_initControls: function() {
		if (this.options.zoomControl) {
			this.addControl(new L.Control.Zoom());
		}
		if (this.options.attributionControl) {
			this.attributionControl = new L.Control.Attribution();
			this.addControl(this.attributionControl);
		}
	},

	_rawPanBy: function(offset) {
		var mapPaneOffset = L.DomUtil.getPosition(this._mapPane);
		L.DomUtil.setPosition(this._mapPane, mapPaneOffset.subtract(offset));
	},

	// map events

	_initEvents: function() {
		L.DomEvent.addListener(this._container, 'click', this._onMouseClick, this);

		var events = ['dblclick', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove'];
		for (var i = 0; i < events.length; i++) {
			L.DomEvent.addListener(this._container, events[i], this._fireMouseEvent, this);
		}

		if (this.options.trackResize) {
			L.DomEvent.addListener(window, 'resize', this._onResize, this);
		}
	},

	_onResize: function() {
		L.Util.requestAnimFrame(this.invalidateSize, this, false, this._container);
	},

	_onMouseClick: function(e) {
		if (!this._loaded || (this.dragging && this.dragging.moved())) { return; }

		this.fire('pre' + e.type);
		this._fireMouseEvent(e);
	},

	_fireMouseEvent: function(e) {
		if (!this._loaded) return;

		var type = e.type;
		type = (type == 'mouseenter' ? 'mouseover' : (type == 'mouseleave' ? 'mouseout' : type));
		if (!this.hasEventListeners(type)) { return; }
		this.fire(type, {
			latlng: this.mouseEventToLatLng(e),
			layerPoint: this.mouseEventToLayerPoint(e)
		});
	},

	_initInteraction: function() {
		var handlers = {
			dragging: L.Handler.MapDrag,
			touchZoom: L.Handler.TouchZoom,
			doubleClickZoom: L.Handler.DoubleClickZoom,
			scrollWheelZoom: L.Handler.ScrollWheelZoom,
			shiftDragZoom: L.Handler.ShiftDragZoom
		};
		for (var i in handlers) {
			if (handlers.hasOwnProperty(i) && handlers[i]) {
				this[i] = new handlers[i](this);
				if (this.options[i]) this[i].enable();
			}
		}
	},

	_onTileLayerLoad: function() {
		// clear scaled tiles after all new tiles are loaded (for performance)
		this._tileLayersToLoad--;
		if (this._tileLayersNum && !this._tileLayersToLoad && this._tileBg) {
			clearTimeout(this._clearTileBgTimer);
			this._clearTileBgTimer = setTimeout(L.Util.bind(this._clearTileBg, this), 500);
		}
	},

	// private methods for getting map state

	_getTopLeftPoint: function() {
		if (!this._loaded) throw new Error('Set map center and zoom first.');
		var offset = L.DomUtil.getPosition(this._mapPane);
		return this._initialTopLeftPoint.subtract(offset);
	},

	_getNewTopLeftPoint: function(center) {
		var viewHalf = this.getSize().divideBy(2);
		return this.project(center).subtract(viewHalf).round();
	},

	_limitZoom: function(zoom) {
		var min = this.getMinZoom();
		var max = this.getMaxZoom();
		return Math.max(min, Math.min(max, zoom));
	}
});
<|endoftext|>


<commit_before>define(
  'ephox.alloy.demo.docs.UiDocumentation',

  [
    'ephox.alloy.api.ui.Container',
    'ephox.alloy.demo.docs.SchemaView',
    'ephox.boulder.api.ValueSchema',
    'ephox.compass.Arr'
  ],

  function (Container, SchemaView, ValueSchema, Arr) {
    var make = function (uis) {
      var extractParts = function (partTypes) {
        return Arr.map(partTypes, function (pt) {
          return pt.fold(
            function (_, name, _, _, _) {
              return name;
            },
            function (_, name, _, _, _) {
              return name;
            },
            function (_, name, _, _, _) {
              return name;
            },
            function (_, name, _, _, _, _) {
              return name;
            }
          );
        });
      };

      var makeParts = function (partTypes) {
        var parts = extractParts(partTypes);

        return Container.sketch({
          dom: {
            tag: 'div',
            classes: [ 'doc-component-parts' ]
          },
          components: Arr.flatten([
            parts.length > 0 ? [
              Container.sketch({
                dom: { tag: 'h4', innerHtml: 'Parts' }
              }),
              Container.sketch({
                dom: {
                  tag: 'ul'
                },
                components: Arr.map(parts, function (p) {
                  return Container.sketch({
                    dom: {
                      tag: 'li',
                      innerHtml: p
                    }
                  });
                })
              })] : [ ]
          ])
        });
      };

      var definitions = Arr.map(uis, function (s) {
        var heading = Container.sketch({
          dom: {
            tag: 'h3',
            innerHtml: s.name()
          }
        });

        var description = Container.sketch({
          dom: {
            tag: 'p',
            innerHtml: SchemaView.getDescription(s.name())
          }
        });

        var schema = SchemaView.build([ s.name() ],  ValueSchema.objOf(s.schema()).toDsl());

        var wrapper = Container.sketch({
          dom: {
            tag: 'div'
          },
          components: [
            heading,
            description,
            schema,
            makeParts(s.parts())
          ]
        });

        return {
          value: s.name(),
          wrapper: wrapper
        };
      });

      return definitions;
    };

    return {
      make: make
    };
  }
);<commit_msg>VAN-44-parts-docs: using appropriate parameter for name<commit_after>define(
  'ephox.alloy.demo.docs.UiDocumentation',

  [
    'ephox.alloy.api.ui.Container',
    'ephox.alloy.demo.docs.SchemaView',
    'ephox.boulder.api.ValueSchema',
    'ephox.compass.Arr'
  ],

  function (Container, SchemaView, ValueSchema, Arr) {
    var make = function (uis) {
      var extractParts = function (partTypes) {
        return Arr.map(partTypes, function (pt) {
          return pt.fold(
            function (_, _, name, _, _, _) {
              return name;
            },
            function (_, _, name, _, _, _) {
              return name;
            },
            function (_, _, name, _, _, _) {
              return name;
            },
            function (_, _, name, _, _, _, _) {
              return name;
            }
          );
        });
      };

      var makeParts = function (partTypes) {
        var parts = extractParts(partTypes);

        return Container.sketch({
          dom: {
            tag: 'div',
            classes: [ 'doc-component-parts' ]
          },
          components: Arr.flatten([
            parts.length > 0 ? [
              Container.sketch({
                dom: { tag: 'h4', innerHtml: 'Parts' }
              }),
              Container.sketch({
                dom: {
                  tag: 'ul'
                },
                components: Arr.map(parts, function (p) {
                  return Container.sketch({
                    dom: {
                      tag: 'li',
                      innerHtml: p
                    }
                  });
                })
              })] : [ ]
          ])
        });
      };

      var definitions = Arr.map(uis, function (s) {
        var heading = Container.sketch({
          dom: {
            tag: 'h3',
            innerHtml: s.name()
          }
        });

        var description = Container.sketch({
          dom: {
            tag: 'p',
            innerHtml: SchemaView.getDescription(s.name())
          }
        });

        var schema = SchemaView.build([ s.name() ],  ValueSchema.objOf(s.schema()).toDsl());

        var wrapper = Container.sketch({
          dom: {
            tag: 'div'
          },
          components: [
            heading,
            description,
            schema,
            makeParts(s.parts())
          ]
        });

        return {
          value: s.name(),
          wrapper: wrapper
        };
      });

      return definitions;
    };

    return {
      make: make
    };
  }
);<|endoftext|>