<commit_before>frappe.provide("frappe.wiz");
frappe.provide("frappe.wiz.events");

frappe.wiz = {
	slides: [],
	events: {},
	on: function(event, fn) {
		if(!frappe.wiz.events[event]) {
			frappe.wiz.events[event] = [];
		}
		frappe.wiz.events[event].push(fn);
	},
	add_slide: function(slide) {
		frappe.wiz.slides.push(slide);
	},
	run_event: function(event) {
		$.each(frappe.wiz.events[event] || [], function(i, fn) {
			fn(frappe.wiz.wizard);
		});
	}
}

frappe.pages['setup-wizard'].on_page_load = function(wrapper) {
	// setup page ui
	$(".navbar:first").toggle(false);
	$("body").css({"padding-top":"30px"});

	frappe.require("/assets/frappe/css/animate.min.css");

	$.each(frappe.boot.setup_wizard_requires || [], function(i, path) {
		frappe.require(path);
	});

	frappe.wiz.run_event("before_load");

	var wizard_settings = {
		page_name: "setup-wizard",
		parent: wrapper,
		slides: frappe.wiz.slides,
		title: __("Welcome")
	}

	frappe.wiz.wizard = new frappe.wiz.Wizard(wizard_settings)

}

frappe.pages['setup-wizard'].on_page_show = function(wrapper) {
	if(frappe.get_route()[1]) {
		frappe.wiz.wizard.show(frappe.get_route()[1]);
	}
}

frappe.wiz.Wizard = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.make();
		this.slides;
		this.slide_dict = {};
		this.welcomed = true;
		frappe.set_route("setup-wizard/0");
	},
	make: function() {
		this.parent = $('
').appendTo(this.parent);
	},
	get_message: function(html) {
		return $(repl('
\

%(html)s
\

', {html:html}))
	},
	show_working: function() {
		this.hide_current_slide();
		frappe.set_route(this.page_name);
		this.current_slide = {"$wrapper": this.get_message(this.working_html()).appendTo(this.parent)};
	},
	show_complete: function() {
		this.hide_current_slide();
		this.current_slide = {"$wrapper": this.get_message(this.complete_html()).appendTo(this.parent)};
	},
	show: function(id) {
		if(!this.welcomed) {
			frappe.set_route(this.page_name);
			return;
		}
		id = cint(id);
		if(this.current_slide && this.current_slide.id===id)
			return;
		if(!this.slide_dict[id]) {
			this.slide_dict[id] = new frappe.wiz.WizardSlide($.extend(this.slides[id], {wiz:this, id:id}));
			this.slide_dict[id].make();
		}

		this.hide_current_slide();

		this.current_slide = this.slide_dict[id];
		this.current_slide.$wrapper.removeClass("hidden");
	},
	hide_current_slide: function() {
		if(this.current_slide) {
			this.current_slide.$wrapper.addClass("hidden");
			this.current_slide = null;
		}
	},
	get_values: function() {
		var values = {};
		$.each(this.slide_dict, function(id, slide) {
			$.extend(values, slide.values)
		})
		return values;
	},
	working_html: function() {
		var msg = $(frappe.render_template("setup_wizard_message", {
			image: "/assets/frappe/images/ui/bubble-tea-smile.svg",
			title: __("Setting Up"),
			message: __('Sit tight while your system is being setup. This may take a few moments.')
		}));
		msg.find(".setup-wizard-message-image").addClass("animated infinite bounce");
		return msg.html();
	},

	complete_html: function() {
		return frappe.render_template("setup_wizard_message", {
			image: "/assets/frappe/images/ui/bubble-tea-happy.svg",
			title: __('Setup Complete'),
			message: ""
		});
	},

	on_complete: function() {
		var me = this;
		var values = me.get_values();
		me.show_working();
		return frappe.call({
			method: "frappe.desk.page.setup_wizard.setup_wizard.setup_complete",
			args: {args: values},
			callback: function(r) {
				me.show_complete();
				if(frappe.wiz.welcome_page) {
					localStorage.setItem("session_last_route", frappe.wiz.welcome_page);
				}
				setTimeout(function() {
					window.location = "/desk";
				}, 2000);
			},
			error: function(r) {
				var d = msgprint(__("There were errors."));
				d.custom_onhide = function() {
					frappe.set_route(me.page_name, me.slides.length - 1);
				};
			}
		});
	}

});

frappe.wiz.WizardSlide = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.$wrapper = $('

')
			.appendTo(this.wiz.parent)
			.attr("data-slide-id", this.id);
	},
	make: function() {
		var me = this;
		if(this.$body) this.$body.remove();

		if(this.before_load) {
			this.before_load(this);
		}

		this.$body = $(frappe.render_template("setup_wizard_page", {
				help: __(this.help),
				title:__(this.title),
				main_title:__(this.wiz.title),
				step: this.id + 1,
				name: this.name,
				css_class: this.css_class || "",
				slides_count: this.wiz.slides.length
			})).appendTo(this.$wrapper);

		this.body = this.$body.find(".form")[0];

		if(this.fields) {
			this.form = new frappe.ui.FieldGroup({
				fields: this.fields,
				body: this.body,
				no_submit_on_enter: true
			});
			this.form.make();
		} else {
			$(this.body).html(this.html);
		}

		if(this.id > 0) {
			this.$prev = this.$body.find('.prev-btn').removeClass("hide")
				.click(function() {
					frappe.set_route(me.wiz.page_name, me.id-1 + "");
				})
				.css({"margin-right": "10px"});
			}
		if(this.id+1 < this.wiz.slides.length) {
			this.$next = this.$body.find('.next-btn').removeClass("hide")
				.click(function() {
					me.values = me.form.get_values();
					if(me.values===null)
						return;
					if(me.validate && !me.validate())
						return;
					frappe.set_route(me.wiz.page_name, me.id+1 + "");
				})
		} else {
			this.$complete = this.$body.find('.complete-btn').removeClass("hide")
				.click(function() {
					me.values = me.form.get_values();
					if(me.values===null)
						return;
					if(me.validate && !me.validate())
						return;
					me.wiz.on_complete(me.wiz);
				})
		}

		if(this.onload) {
			this.onload(this);
		}

	},
	get_input: function(fn) {
		return this.form.get_input(fn);
	},
	get_field: function(fn) {
		return this.form.get_field(fn);
	}
});

function load_frappe_slides() {
	// language selection
	frappe.wiz.welcome = {
		name: "welcome",
		title: __("Welcome"),
		icon: "icon-world",
		help: __("Let's prepare the system for first use."),

		fields: [
			{ fieldname: "language", label: __("Select Your Language"), reqd:1,
				fieldtype: "Select" },
		],

		onload: function(slide) {
			if (!frappe.wiz.welcome.data) {
				frappe.wiz.welcome.load_languages(slide);
			} else {
				frappe.wiz.welcome.setup_fields(slide);
			}
		},

		css_class: "single-column",
		load_languages: function(slide) {
			frappe.call({
				method: "frappe.desk.page.setup_wizard.setup_wizard.load_languages",
				callback: function(r) {
					frappe.wiz.welcome.data = r.message;
					frappe.wiz.welcome.setup_fields(slide);

					slide.get_field("language")
						.set_input(frappe.wiz.welcome.data.default_language || "english");
					moment.locale("en");
				}
			});
		},

		setup_fields: function(slide) {
			var select = slide.get_field("language");
			select.df.options = frappe.wiz.welcome.data.languages;
			select.refresh();
			frappe.wiz.welcome.bind_events(slide);
		},

		bind_events: function(slide) {
			slide.get_input("language").unbind("change").on("change", function() {
				var lang = $(this).val() || "english";
				frappe._messages = {};
				frappe.call({
					method: "frappe.desk.page.setup_wizard.setup_wizard.load_messages",
					args: {
						language: lang
					},
					callback: function(r) {
						// TODO save values!

						// reset all slides so that labels are translated
						frappe.wiz.slides = [];
						frappe.wiz.run_event("before_load");
						frappe.wiz.wizard.slides = frappe.wiz.slides;

						// re-render all slides
						$.each(slide.wiz.slide_dict, function(id, s) {
							$.extend(s, frappe.wiz.slides[id]);
							s.make();
						});

						// select is re-made after language change
						var select = slide.get_field("language");
						select.set_input(lang);
					}
				});
			});
		}
	}

	// region selection
	frappe.wiz.region = {
		title: __("Region"),
		icon: "icon-flag",
		help: __("Select your Country, Time Zone and Currency"),
		fields: [
			{ fieldname: "country", label: __("Country"), reqd:1,
				fieldtype: "Select" },
			{ fieldname: "timezone", label: __("Time Zone"), reqd:1,
				fieldtype: "Select" },
			{ fieldname: "currency", label: __("Currency"), reqd:1,
				fieldtype: "Select" },
		],

		onload: function(slide) {
			frappe.call({
				method:"frappe.geo.country_info.get_country_timezone_info",
				callback: function(data) {
					frappe.wiz.region.data = data.message;
					frappe.wiz.region.setup_fields(slide);
					frappe.wiz.region.bind_events(slide);
				}
			});
		},
		css_class: "single-column",
		setup_fields: function(slide) {
			var data = frappe.wiz.region.data;

			slide.get_input("country").empty()
				.add_options([""].concat(keys(data.country_info).sort()));

			slide.get_input("currency").empty()
				.add_options(frappe.utils.unique([""].concat($.map(data.country_info,
					function(opts, country) { return opts.currency; }))).sort());

			slide.get_input("timezone").empty()
				.add_options([""].concat(data.all_timezones));

			if (data.default_country) {
				slide.set_input("country", data.default_country);
			}
		},

		bind_events: function(slide) {
			slide.get_input("country").on("change", function() {
				var country = slide.get_input("country").val();
				var $timezone = slide.get_input("timezone");
				var data = frappe.wiz.region.data;

				$timezone.empty();

				// add country specific timezones first
				if(country) {
					var timezone_list = data.country_info[country].timezones || [];
					$timezone.add_options(timezone_list.sort());
					slide.get_field("currency").set_input(data.country_info[country].currency);
					slide.get_field("currency").$input.trigger("change");
				}

				// add all timezones at the end, so that user has the option to change it to any timezone
				$timezone.add_options([""].concat(data.all_timezones));

				slide.get_field("timezone").set_input($timezone.val());

				// temporarily set date format
				frappe.boot.sysdefaults.date_format = (data.country_info[country].date_format
					|| "dd-mm-yyyy");
			});

			slide.get_input("currency").on("change", function() {
				var currency = slide.get_input("currency").val();
				if (!currency) return;
				frappe.model.with_doc("Currency", currency, function() {
					frappe.provide("locals.:Currency." + currency);
					var currency_doc = frappe.model.get_doc("Currency", currency);
					var number_format = currency_doc.number_format;
					if (number_format==="#.###") {
						number_format = "#.###,##";
					} else if (number_format==="#,###") {
						number_format = "#,###.##"
					}

					frappe.boot.sysdefaults.number_format = number_format;
					locals[":Currency"][currency] = $.extend({}, currency_doc);
				});
			});
		}
	};
};

frappe.wiz.on("before_load", function() {
	load_frappe_slides();

	// add welcome slide
	frappe.wiz.add_slide(frappe.wiz.welcome);
	frappe.wiz.add_slide(frappe.wiz.region);
});
<commit_msg>[fix] added a new event after_load in setup wizard<commit_after>frappe.provide("frappe.wiz");
frappe.provide("frappe.wiz.events");

frappe.wiz = {
	slides: [],
	events: {},
	on: function(event, fn) {
		if(!frappe.wiz.events[event]) {
			frappe.wiz.events[event] = [];
		}
		frappe.wiz.events[event].push(fn);
	},
	add_slide: function(slide) {
		frappe.wiz.slides.push(slide);
	},
	run_event: function(event) {
		$.each(frappe.wiz.events[event] || [], function(i, fn) {
			fn(frappe.wiz.wizard);
		});
	}
}

frappe.pages['setup-wizard'].on_page_load = function(wrapper) {
	// setup page ui
	$(".navbar:first").toggle(false);
	$("body").css({"padding-top":"30px"});

	frappe.require("/assets/frappe/css/animate.min.css");

	$.each(frappe.boot.setup_wizard_requires || [], function(i, path) {
		frappe.require(path);
	});

	frappe.wiz.run_event("before_load");

	var wizard_settings = {
		page_name: "setup-wizard",
		parent: wrapper,
		slides: frappe.wiz.slides,
		title: __("Welcome")
	}

	frappe.wiz.wizard = new frappe.wiz.Wizard(wizard_settings);

	frappe.wiz.run_event("after_load");
}

frappe.pages['setup-wizard'].on_page_show = function(wrapper) {
	if(frappe.get_route()[1]) {
		frappe.wiz.wizard.show(frappe.get_route()[1]);
	}
}

frappe.wiz.Wizard = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.make();
		this.slides;
		this.slide_dict = {};
		this.welcomed = true;
		frappe.set_route("setup-wizard/0");
	},
	make: function() {
		this.parent = $('
').appendTo(this.parent);
	},
	get_message: function(html) {
		return $(repl('
\

%(html)s
\

', {html:html}))
	},
	show_working: function() {
		this.hide_current_slide();
		frappe.set_route(this.page_name);
		this.current_slide = {"$wrapper": this.get_message(this.working_html()).appendTo(this.parent)};
	},
	show_complete: function() {
		this.hide_current_slide();
		this.current_slide = {"$wrapper": this.get_message(this.complete_html()).appendTo(this.parent)};
	},
	show: function(id) {
		if(!this.welcomed) {
			frappe.set_route(this.page_name);
			return;
		}
		id = cint(id);
		if(this.current_slide && this.current_slide.id===id)
			return;
		if(!this.slide_dict[id]) {
			this.slide_dict[id] = new frappe.wiz.WizardSlide($.extend(this.slides[id], {wiz:this, id:id}));
			this.slide_dict[id].make();
		}

		this.hide_current_slide();

		this.current_slide = this.slide_dict[id];
		this.current_slide.$wrapper.removeClass("hidden");
	},
	hide_current_slide: function() {
		if(this.current_slide) {
			this.current_slide.$wrapper.addClass("hidden");
			this.current_slide = null;
		}
	},
	get_values: function() {
		var values = {};
		$.each(this.slide_dict, function(id, slide) {
			$.extend(values, slide.values)
		})
		return values;
	},
	working_html: function() {
		var msg = $(frappe.render_template("setup_wizard_message", {
			image: "/assets/frappe/images/ui/bubble-tea-smile.svg",
			title: __("Setting Up"),
			message: __('Sit tight while your system is being setup. This may take a few moments.')
		}));
		msg.find(".setup-wizard-message-image").addClass("animated infinite bounce");
		return msg.html();
	},

	complete_html: function() {
		return frappe.render_template("setup_wizard_message", {
			image: "/assets/frappe/images/ui/bubble-tea-happy.svg",
			title: __('Setup Complete'),
			message: ""
		});
	},

	on_complete: function() {
		var me = this;
		var values = me.get_values();
		me.show_working();
		return frappe.call({
			method: "frappe.desk.page.setup_wizard.setup_wizard.setup_complete",
			args: {args: values},
			callback: function(r) {
				me.show_complete();
				if(frappe.wiz.welcome_page) {
					localStorage.setItem("session_last_route", frappe.wiz.welcome_page);
				}
				setTimeout(function() {
					window.location = "/desk";
				}, 2000);
			},
			error: function(r) {
				var d = msgprint(__("There were errors."));
				d.custom_onhide = function() {
					frappe.set_route(me.page_name, me.slides.length - 1);
				};
			}
		});
	}

});

frappe.wiz.WizardSlide = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.$wrapper = $('

')
			.appendTo(this.wiz.parent)
			.attr("data-slide-id", this.id);
	},
	make: function() {
		var me = this;
		if(this.$body) this.$body.remove();

		if(this.before_load) {
			this.before_load(this);
		}

		this.$body = $(frappe.render_template("setup_wizard_page", {
				help: __(this.help),
				title:__(this.title),
				main_title:__(this.wiz.title),
				step: this.id + 1,
				name: this.name,
				css_class: this.css_class || "",
				slides_count: this.wiz.slides.length
			})).appendTo(this.$wrapper);

		this.body = this.$body.find(".form")[0];

		if(this.fields) {
			this.form = new frappe.ui.FieldGroup({
				fields: this.fields,
				body: this.body,
				no_submit_on_enter: true
			});
			this.form.make();
		} else {
			$(this.body).html(this.html);
		}

		if(this.id > 0) {
			this.$prev = this.$body.find('.prev-btn').removeClass("hide")
				.click(function() {
					frappe.set_route(me.wiz.page_name, me.id-1 + "");
				})
				.css({"margin-right": "10px"});
			}
		if(this.id+1 < this.wiz.slides.length) {
			this.$next = this.$body.find('.next-btn').removeClass("hide")
				.click(function() {
					me.values = me.form.get_values();
					if(me.values===null)
						return;
					if(me.validate && !me.validate())
						return;
					frappe.set_route(me.wiz.page_name, me.id+1 + "");
				})
		} else {
			this.$complete = this.$body.find('.complete-btn').removeClass("hide")
				.click(function() {
					me.values = me.form.get_values();
					if(me.values===null)
						return;
					if(me.validate && !me.validate())
						return;
					me.wiz.on_complete(me.wiz);
				})
		}

		if(this.onload) {
			this.onload(this);
		}

	},
	get_input: function(fn) {
		return this.form.get_input(fn);
	},
	get_field: function(fn) {
		return this.form.get_field(fn);
	}
});

function load_frappe_slides() {
	// language selection
	frappe.wiz.welcome = {
		name: "welcome",
		title: __("Welcome"),
		icon: "icon-world",
		help: __("Let's prepare the system for first use."),

		fields: [
			{ fieldname: "language", label: __("Select Your Language"), reqd:1,
				fieldtype: "Select" },
		],

		onload: function(slide) {
			if (!frappe.wiz.welcome.data) {
				frappe.wiz.welcome.load_languages(slide);
			} else {
				frappe.wiz.welcome.setup_fields(slide);
			}
		},

		css_class: "single-column",
		load_languages: function(slide) {
			frappe.call({
				method: "frappe.desk.page.setup_wizard.setup_wizard.load_languages",
				callback: function(r) {
					frappe.wiz.welcome.data = r.message;
					frappe.wiz.welcome.setup_fields(slide);

					slide.get_field("language")
						.set_input(frappe.wiz.welcome.data.default_language || "english");
					moment.locale("en");
				}
			});
		},

		setup_fields: function(slide) {
			var select = slide.get_field("language");
			select.df.options = frappe.wiz.welcome.data.languages;
			select.refresh();
			frappe.wiz.welcome.bind_events(slide);
		},

		bind_events: function(slide) {
			slide.get_input("language").unbind("change").on("change", function() {
				var lang = $(this).val() || "english";
				frappe._messages = {};
				frappe.call({
					method: "frappe.desk.page.setup_wizard.setup_wizard.load_messages",
					args: {
						language: lang
					},
					callback: function(r) {
						// TODO save values!

						// reset all slides so that labels are translated
						frappe.wiz.slides = [];
						frappe.wiz.run_event("before_load");
						frappe.wiz.wizard.slides = frappe.wiz.slides;
						frappe.wiz.run_event("after_load");

						// re-render all slides
						$.each(slide.wiz.slide_dict, function(id, s) {
							$.extend(s, frappe.wiz.slides[id]);
							s.make();
						});

						// select is re-made after language change
						var select = slide.get_field("language");
						select.set_input(lang);
					}
				});
			});
		}
	}

	// region selection
	frappe.wiz.region = {
		title: __("Region"),
		icon: "icon-flag",
		help: __("Select your Country, Time Zone and Currency"),
		fields: [
			{ fieldname: "country", label: __("Country"), reqd:1,
				fieldtype: "Select" },
			{ fieldname: "timezone", label: __("Time Zone"), reqd:1,
				fieldtype: "Select" },
			{ fieldname: "currency", label: __("Currency"), reqd:1,
				fieldtype: "Select" },
		],

		onload: function(slide) {
			frappe.call({
				method:"frappe.geo.country_info.get_country_timezone_info",
				callback: function(data) {
					frappe.wiz.region.data = data.message;
					frappe.wiz.region.setup_fields(slide);
					frappe.wiz.region.bind_events(slide);
				}
			});
		},
		css_class: "single-column",
		setup_fields: function(slide) {
			var data = frappe.wiz.region.data;

			slide.get_input("country").empty()
				.add_options([""].concat(keys(data.country_info).sort()));

			slide.get_input("currency").empty()
				.add_options(frappe.utils.unique([""].concat($.map(data.country_info,
					function(opts, country) { return opts.currency; }))).sort());

			slide.get_input("timezone").empty()
				.add_options([""].concat(data.all_timezones));

			if (data.default_country) {
				slide.set_input("country", data.default_country);
			}
		},

		bind_events: function(slide) {
			slide.get_input("country").on("change", function() {
				var country = slide.get_input("country").val();
				var $timezone = slide.get_input("timezone");
				var data = frappe.wiz.region.data;

				$timezone.empty();

				// add country specific timezones first
				if(country) {
					var timezone_list = data.country_info[country].timezones || [];
					$timezone.add_options(timezone_list.sort());
					slide.get_field("currency").set_input(data.country_info[country].currency);
					slide.get_field("currency").$input.trigger("change");
				}

				// add all timezones at the end, so that user has the option to change it to any timezone
				$timezone.add_options([""].concat(data.all_timezones));

				slide.get_field("timezone").set_input($timezone.val());

				// temporarily set date format
				frappe.boot.sysdefaults.date_format = (data.country_info[country].date_format
					|| "dd-mm-yyyy");
			});

			slide.get_input("currency").on("change", function() {
				var currency = slide.get_input("currency").val();
				if (!currency) return;
				frappe.model.with_doc("Currency", currency, function() {
					frappe.provide("locals.:Currency." + currency);
					var currency_doc = frappe.model.get_doc("Currency", currency);
					var number_format = currency_doc.number_format;
					if (number_format==="#.###") {
						number_format = "#.###,##";
					} else if (number_format==="#,###") {
						number_format = "#,###.##"
					}

					frappe.boot.sysdefaults.number_format = number_format;
					locals[":Currency"][currency] = $.extend({}, currency_doc);
				});
			});
		}
	};
};

frappe.wiz.on("before_load", function() {
	load_frappe_slides();

	// add welcome slide
	frappe.wiz.add_slide(frappe.wiz.welcome);
	frappe.wiz.add_slide(frappe.wiz.region);
});
<|endoftext|>


<commit_before>// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../common/common.js';
import * as Persistence from '../persistence/persistence.js';
import * as SDK from '../sdk/sdk.js';
import * as TextUtils from '../text_utils/text_utils.js';  // eslint-disable-line no-unused-vars
import * as Workspace from '../workspace/workspace.js';

class SnippetFileSystem extends Persistence.PlatformFileSystem.PlatformFileSystem {
  constructor() {
    super('snippet://', 'snippets');
    this._lastSnippetIdentifierSetting =
        Common.Settings.Settings.instance().createSetting('scriptSnippets_lastIdentifier', 0);
    this._snippetsSetting = Common.Settings.Settings.instance().createSetting('scriptSnippets', []);
  }

  /**
   * @override
   * @return {!Array<string>}
   */
  initialFilePaths() {
    const savedSnippets = this._snippetsSetting.get();
    return savedSnippets.map(snippet => escape(snippet.name));
  }

  /**
   * @override
   * @param {string} path
   * @param {?string} name
   * @return {!Promise<?string>}
   */
  async createFile(path, name) {
    const nextId = this._lastSnippetIdentifierSetting.get() + 1;
    this._lastSnippetIdentifierSetting.set(nextId);

    const snippetName = ls`Script snippet #${nextId}`;
    const snippets = this._snippetsSetting.get();
    snippets.push({name: snippetName, content: ''});
    this._snippetsSetting.set(snippets);

    return escape(snippetName);
  }

  /**
   * @override
   * @param {string} path
   * @return {!Promise<boolean>}
   */
  async deleteFile(path) {
    const name = unescape(path.substring(1));
    const allSnippets = this._snippetsSetting.get();
    const snippets = allSnippets.filter(snippet => snippet.name !== name);
    if (allSnippets.length !== snippets.length) {
      this._snippetsSetting.set(snippets);
      return true;
    }
    return false;
  }

  /**
   * @override
   * @param {string} path
   * @returns {!Promise<!TextUtils.ContentProvider.DeferredContent>}
   */
  async requestFileContent(path) {
    const name = unescape(path.substring(1));
    const snippet = this._snippetsSetting.get().find(snippet => snippet.name === name);
    return {content: snippet ? snippet.content : null, isEncoded: false};
  }

  /**
   * @override
   * @param {string} path
   * @param {string} content
   * @param {boolean} isBase64
   */
  async setFileContent(path, content, isBase64) {
    const name = unescape(path.substring(1));
    const snippets = this._snippetsSetting.get();
    const snippet = snippets.find(snippet => snippet.name === name);
    if (snippet) {
      snippet.content = content;
      this._snippetsSetting.set(snippets);
      return true;
    }
    return false;
  }

  /**
   * @override
   * @param {string} path
   * @param {string} newName
   * @param {function(boolean, string=)} callback
   */
  renameFile(path, newName, callback) {
    const name = unescape(path.substring(1));
    const snippets = this._snippetsSetting.get();
    const snippet = snippets.find(snippet => snippet.name === name);
    newName = newName.trim();
    if (!snippet || newName.length === 0 || snippets.find(snippet => snippet.name === newName)) {
      callback(false);
      return;
    }
    snippet.name = newName;
    this._snippetsSetting.set(snippets);
    callback(true, newName);
  }

  /**
   * @override
   * @param {string} query
   * @param {!Common.Progress.Progress} progress
   * @return {!Promise<!Array<string>>}
   */
  async searchInPath(query, progress) {
    const re = new RegExp(query.escapeForRegExp(), 'i');
    const snippets = this._snippetsSetting.get().filter(snippet => snippet.content.match(re));
    return snippets.map(snippet => escape(snippet.name));
  }

  /**
   * @override
   * @param {string} path
   * @return {string}
   */
  mimeFromPath(path) {
    return 'text/javascript';
  }

  /**
   * @override
   * @param {string} path
   * @return {!Common.ResourceType.ResourceType}
   */
  contentType(path) {
    return Common.ResourceType.resourceTypes.Script;
  }

  /**
   * @override
   * @param {string} url
   * @return {string}
   */
  tooltipForURL(url) {
    return ls`Linked to ${unescape(url.substring(this.path().length))}`;
  }

  /**
   * @override
   * @return {boolean}
   */
  supportsAutomapping() {
    return true;
  }
}

/**
 * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode
 */
export async function evaluateScriptSnippet(uiSourceCode) {
  if (!uiSourceCode.url().startsWith('snippet://')) {
    return;
  }

  const executionContext = self.UI.context.flavor(SDK.RuntimeModel.ExecutionContext);
  if (!executionContext) {
    return;
  }

  const runtimeModel = executionContext.runtimeModel;
  await uiSourceCode.requestContent();
  uiSourceCode.commitWorkingCopy();
  const expression = uiSourceCode.workingCopy();
  Common.Console.Console.instance().show();

  const url = uiSourceCode.url();

  const result = await executionContext.evaluate(
      {
        expression: `${expression}\n//# sourceURL=${url}`,
        objectGroup: 'console',
        silent: false,
        includeCommandLineAPI: true,
        returnByValue: false,
        generatePreview: true,
        replMode: true,
      },
      /* userGesture */ false,
      /* awaitPromise */ true);

  if (result.exceptionDetails) {
    SDK.ConsoleModel.ConsoleModel.instance().addMessage(SDK.ConsoleModel.ConsoleMessage.fromException(
        runtimeModel, result.exceptionDetails, /* messageType */ undefined, /* timestamp */ undefined, url));
    return;
  }
  if (!result.object) {
    return;
  }

  const scripts = executionContext.debuggerModel.scriptsForSourceURL(url);
  const scriptId = scripts[scripts.length - 1].scriptId;
  SDK.ConsoleModel.ConsoleModel.instance().addMessage(new SDK.ConsoleModel.ConsoleMessage(
      runtimeModel, SDK.ConsoleModel.MessageSource.JS, SDK.ConsoleModel.MessageLevel.Info, '',
      SDK.ConsoleModel.MessageType.Result, url, undefined, undefined, [result.object], undefined, undefined,
      executionContext.id, scriptId));
}

/**
 * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode
 * @return {boolean}
 */
export function isSnippetsUISourceCode(uiSourceCode) {
  return uiSourceCode.url().startsWith('snippet://');
}

/**
 * @param {!Workspace.Workspace.Project} project
 * @return {boolean}
 */
export function isSnippetsProject(project) {
  return project.type() === Workspace.Workspace.projectTypes.FileSystem &&
      Persistence.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemType(project) === 'snippets';
}

Persistence.IsolatedFileSystemManager.IsolatedFileSystemManager.instance().addPlatformFileSystem(
    'snippet://', new SnippetFileSystem());
<commit_msg>Reland "Fix snippet saving and search"<commit_after>// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../common/common.js';
import * as Persistence from '../persistence/persistence.js';
import * as SDK from '../sdk/sdk.js';
import * as TextUtils from '../text_utils/text_utils.js';  // eslint-disable-line no-unused-vars
import * as Workspace from '../workspace/workspace.js';

/**
 * @param {string} name
 * @return {string}
 */
function escapeSnippetName(name) {
  return encodeURIComponent(name);
}

/**
 * @param {string} name
 * @return {string}
 */
function unescapeSnippetName(name) {
  return decodeURIComponent(name);
}

class SnippetFileSystem extends Persistence.PlatformFileSystem.PlatformFileSystem {
  constructor() {
    super('snippet://', 'snippets');
    this._lastSnippetIdentifierSetting =
        Common.Settings.Settings.instance().createSetting('scriptSnippets_lastIdentifier', 0);
    this._snippetsSetting = Common.Settings.Settings.instance().createSetting('scriptSnippets', []);
  }

  /**
   * @override
   * @return {!Array<string>}
   */
  initialFilePaths() {
    const savedSnippets = this._snippetsSetting.get();
    return savedSnippets.map(snippet => escapeSnippetName(snippet.name));
  }

  /**
   * @override
   * @param {string} path
   * @param {?string} name
   * @return {!Promise<?string>}
   */
  async createFile(path, name) {
    const nextId = this._lastSnippetIdentifierSetting.get() + 1;
    this._lastSnippetIdentifierSetting.set(nextId);

    const snippetName = ls`Script snippet #${nextId}`;
    const snippets = this._snippetsSetting.get();
    snippets.push({name: snippetName, content: ''});
    this._snippetsSetting.set(snippets);

    return escapeSnippetName(snippetName);
  }

  /**
   * @override
   * @param {string} path
   * @return {!Promise<boolean>}
   */
  async deleteFile(path) {
    const name = unescapeSnippetName(path.substring(1));
    const allSnippets = this._snippetsSetting.get();
    const snippets = allSnippets.filter(snippet => snippet.name !== name);
    if (allSnippets.length !== snippets.length) {
      this._snippetsSetting.set(snippets);
      return true;
    }
    return false;
  }

  /**
   * @override
   * @param {string} path
   * @returns {!Promise<!TextUtils.ContentProvider.DeferredContent>}
   */
  async requestFileContent(path) {
    const name = unescapeSnippetName(path.substring(1));
    const snippet = this._snippetsSetting.get().find(snippet => snippet.name === name);
    return {content: snippet ? snippet.content : null, isEncoded: false};
  }

  /**
   * @override
   * @param {string} path
   * @param {string} content
   * @param {boolean} isBase64
   */
  async setFileContent(path, content, isBase64) {
    const name = unescapeSnippetName(path.substring(1));
    const snippets = this._snippetsSetting.get();
    const snippet = snippets.find(snippet => snippet.name === name);
    if (snippet) {
      snippet.content = content;
      this._snippetsSetting.set(snippets);
      return true;
    }
    return false;
  }

  /**
   * @override
   * @param {string} path
   * @param {string} newName
   * @param {function(boolean, string=)} callback
   */
  renameFile(path, newName, callback) {
    const name = unescapeSnippetName(path.substring(1));
    const snippets = this._snippetsSetting.get();
    const snippet = snippets.find(snippet => snippet.name === name);
    newName = newName.trim();
    if (!snippet || newName.length === 0 || snippets.find(snippet => snippet.name === newName)) {
      callback(false);
      return;
    }
    snippet.name = newName;
    this._snippetsSetting.set(snippets);
    callback(true, newName);
  }

  /**
   * @override
   * @param {string} query
   * @param {!Common.Progress.Progress} progress
   * @return {!Promise<!Array<string>>}
   */
  async searchInPath(query, progress) {
    const re = new RegExp(query.escapeForRegExp(), 'i');
    const snippets = this._snippetsSetting.get().filter(snippet => snippet.content.match(re));
    return snippets.map(snippet => `snippet:///${escapeSnippetName(snippet.name)}`);
  }

  /**
   * @override
   * @param {string} path
   * @return {string}
   */
  mimeFromPath(path) {
    return 'text/javascript';
  }

  /**
   * @override
   * @param {string} path
   * @return {!Common.ResourceType.ResourceType}
   */
  contentType(path) {
    return Common.ResourceType.resourceTypes.Script;
  }

  /**
   * @override
   * @param {string} url
   * @return {string}
   */
  tooltipForURL(url) {
    return ls`Linked to ${unescapeSnippetName(url.substring(this.path().length))}`;
  }

  /**
   * @override
   * @return {boolean}
   */
  supportsAutomapping() {
    return true;
  }
}

/**
 * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode
 */
export async function evaluateScriptSnippet(uiSourceCode) {
  if (!uiSourceCode.url().startsWith('snippet://')) {
    return;
  }

  const executionContext = self.UI.context.flavor(SDK.RuntimeModel.ExecutionContext);
  if (!executionContext) {
    return;
  }

  const runtimeModel = executionContext.runtimeModel;
  await uiSourceCode.requestContent();
  uiSourceCode.commitWorkingCopy();
  const expression = uiSourceCode.workingCopy();
  Common.Console.Console.instance().show();

  const url = uiSourceCode.url();

  const result = await executionContext.evaluate(
      {
        expression: `${expression}\n//# sourceURL=${url}`,
        objectGroup: 'console',
        silent: false,
        includeCommandLineAPI: true,
        returnByValue: false,
        generatePreview: true,
        replMode: true,
      },
      /* userGesture */ false,
      /* awaitPromise */ true);

  if (result.exceptionDetails) {
    SDK.ConsoleModel.ConsoleModel.instance().addMessage(SDK.ConsoleModel.ConsoleMessage.fromException(
        runtimeModel, result.exceptionDetails, /* messageType */ undefined, /* timestamp */ undefined, url));
    return;
  }
  if (!result.object) {
    return;
  }

  const scripts = executionContext.debuggerModel.scriptsForSourceURL(url);
  const scriptId = scripts[scripts.length - 1].scriptId;
  SDK.ConsoleModel.ConsoleModel.instance().addMessage(new SDK.ConsoleModel.ConsoleMessage(
      runtimeModel, SDK.ConsoleModel.MessageSource.JS, SDK.ConsoleModel.MessageLevel.Info, '',
      SDK.ConsoleModel.MessageType.Result, url, undefined, undefined, [result.object], undefined, undefined,
      executionContext.id, scriptId));
}

/**
 * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode
 * @return {boolean}
 */
export function isSnippetsUISourceCode(uiSourceCode) {
  return uiSourceCode.url().startsWith('snippet://');
}

/**
 * @param {!Workspace.Workspace.Project} project
 * @return {boolean}
 */
export function isSnippetsProject(project) {
  return project.type() === Workspace.Workspace.projectTypes.FileSystem &&
      Persistence.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemType(project) === 'snippets';
}

Persistence.IsolatedFileSystemManager.IsolatedFileSystemManager.instance().addPlatformFileSystem(
    'snippet://', new SnippetFileSystem());
<|endoftext|>


<commit_before>"use strict";
/*jslint browser: true*/
/*global Tangram, gui */

// initialize variables
var map, views, queue, nextView,
    newImg, newCanvas, newCtx, newData,
    oldImg, oldCanvas, oldCtx, oldData,
    diffImg, diffCanvas, diffCtx, diff,
    images = {};
var testsFile = "views.json";
var imgDir = "images/";
var imgType = ".png";
var size = 250; // physical pixels
var lsize = 250 * window.devicePixelRatio; // logical pixels
var scores = [], totalScore = 0;
var tests = document.getElementById("tests");
var alertDiv = document.getElementById("alert");
var statusDiv = document.getElementById("status");
var totalScoreDiv = document.getElementById("totalScore");

// parse URL to check for test json passed in the query
// eg: http://localhost:8080/#test.json
function getValuesFromUrl() {
    var url_query = window.location.search.slice(1, window.location.search.length);
    if (url_query != "") return url_query;
    else return testsFile;
}
testsFile = getValuesFromUrl();
console.log('testsFile', testsFile);
// load from url
function loadButton() {
    var url = window.location;
    var newlocation = "?" + document.getElementById("loadtext").value;
    console.log('newlocation:', newlocation);
    window.location = newlocation;
}

// load file
function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        console.log('readyState:', rawFile.readyState);
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            console.log('rawFile.responseText:', rawFile.responseText);
            callback(rawFile.responseText);
        }
        else if (rawFile.readyState === 4 && rawFile.status == "404") {
            console.error("404 – can't load file", file);
            // set page title
            alertDiv.innerHTML = "404 - can't load file:
"+testsFile+"";
        }

    }
    rawFile.send(null);
}

function parseView(view) {
    // console.log('view:', view);
    if (Object.prototype.toString.call(view["location"]) === '[object Array]') {
        return view; // no parsing needed
    } else if (typeof(view["location"]) === "string") {
        // parse string location as array of floats
        var location = view["location"].split(/[ ,]+/);
        location = location.map(parseFloat);
        view["location"] = location;
        return view;
    } else {
        console.log("Can't parse location:", view);
    }
}

// setup divs and canvases
var prep = new Promise( function (resolve, reject) {
    // load and parse test json
    readTextFile(testsFile, function(text){
        try {
            var data = JSON.parse(text);
        } catch(e) {
            console.log('e:', e);
            // set page title
            alertDiv.innerHTML = "Can't parse JSON:
"+testsFile+"";
            return false;
        }
        // convert tests to an array for easier traversal
        views = Object.keys(data.tests).map(function (key) {
            // add test's name as a property of the test
            data.tests[key].name = key;
            return data.tests[key];
        });

        // clone views array
        queue = views.slice(0);
        nextView = parseView(queue.shift()); // pop first and parse location

        // then initialize Tangram with the first view
        map = (function () {
            // console.log('views:', views);
            // console.log('nextView', nextView.location);
            var map_start_location = nextView.location;

            /*** Map ***/

            var map = L.map('map', {
                keyboardZoomOffset : .05,
                zoomControl: false,
                attributionControl : false
            });

            var layer = Tangram.leafletLayer({
                scene: nextView.url,
                // highDensityDisplay: false
            });

            window.layer = layer;
            var scene = layer.scene;
            window.scene = scene;

            // setView expects format ([lat, long], zoom)
            map.setView(map_start_location.slice(0, 3), map_start_location[2]);

            layer.addTo(map);

            return map;

        }());

        // subscribe to Tangram's published view_complete event to
        // load the next scene when the current scene is done drawing
        scene.subscribe({
            view_complete: function () {
                // console.log('nextView:', nextView);
                if (nextView) {
                    // when prep is done, screenshot is made, and oldImg is loaded...
                    Promise.all([prep,screenshot(true),loadOld(imgDir+nextView.name+imgType)]).then(function() {
                        // perform the diff
                        doDiff(nextView);
                        // move along
                        if (queue.length > 0) {
                            nextView = parseView(queue.shift()); // pop first and parse location
                            loadView(nextView);
                        } else return;
                    });
                } else {
                    console.log('view_complete, no nextView');
                    return viewComplete();
                }
            }
        });

        // set page title
        alertDiv.innerHTML = "Now diffing:
"+testsFile+"";

    });

    // set sizes
    document.getElementById("map").style.height = size+"px";
    document.getElementById("map").style.width = size+"px";

    // set up canvases

    // make canvas for the old image
    oldCanvas = document.createElement('canvas');
    oldCanvas.height = lsize;
    oldCanvas.width = lsize;
    oldCtx = oldCanvas.getContext('2d');

    // make a canvas for the newly-drawn map image
    newCanvas = document.createElement('canvas');
    newCanvas.height = lsize;
    newCanvas.width = lsize;
    newCtx = newCanvas.getContext('2d');

    // make a canvas for the diff
    diffCanvas = document.createElement('canvas');
    diffCanvas.height = lsize;
    diffCanvas.width = lsize;
    diffCtx = diffCanvas.getContext('2d');
    diff = diffCtx.createImageData(lsize, lsize);

    resolve();
});

// load an image asynchronously with a Promise
function loadImage (url, target) {
    return new Promise(function(resolve, reject) {
        var image = target || new Image();
        image.onload = function() {
            resolve({ url: url, image: image });
        };
        image.onerror = function(error) {
            resolve({ error: error });
        };
        image.crossOrigin = 'anonymous';
        // force-refresh any local images with a cache-buster
        if (url.slice(-4) == imgType) url += "?" + new Date().getTime();
        image.src = url;
    });
}

// load the old image
function loadOld (img) {
    oldImg = new Image();
    return loadImage(img).then(function(result){
        if (result.url) {
            // set the old image to be drawn to the canvas once the image loads
            oldImg = result.image;
            oldCtx.drawImage(oldImg, 0, 0, oldImg.width, oldImg.height, 0, 0, oldCanvas.width, oldCanvas.height);
            // make the data available to pixelmatch
            oldData = oldCtx.getImageData(0, 0, lsize, lsize);
        } else {
            oldData = null;
        }
        return result;
    });
};

// take a screenshot
function screenshot (save) {
    return scene.screenshot().then(function(data) {
        // save it to a file
        if (save) saveAs(data.blob, nextView.name);

        var urlCreator = window.URL || window.webkitURL;
        newImg = new Image();
        return loadImage(urlCreator.createObjectURL( data.blob ), newImg);
    });
};

// perform the image comparison and update the html
function doDiff( test ) {
    // save the new image to the new canvas, stretching it to fit (in case it's retina)
    newCtx.drawImage(newImg, 0, 0, newImg.width, newImg.height, 0, 0, newCanvas.width, newCanvas.height);
    // make the data available
    var newData = newCtx.getImageData(0, 0, lsize, lsize);
    if (oldData) {
        // run the diff
        var difference = pixelmatch(newData.data, oldData.data, diff.data, lsize, lsize, {threshold: 0.1});
        // calculate match percentage
        var match = 100-(difference/(lsize*lsize)*100*100)/100;
        var matchScore = Math.floor(match);
        // put the diff in its canvas
        diffCtx.putImageData(diff, 0, 0);
    } else {
        // generating new image
        match = 100;
        matchScore = "";
    }

    // UPDATE READOUTS
    var count = views.length-queue.length;
    statusDiv.innerHTML = count + " of " + views.length;

    // update master percentage
    scores[test.name] = match;
    var totalSum = 0;
    for (var v in scores) {
        totalSum += scores[v];
    }
    totalScore = Math.floor(totalSum/(100*count)*100);
    var threatLevel = totalScore > 99 ? "green" : totalScore > 98 ? "orange" : "red";
    totalScoreDiv.innerHTML = "
"+totalScore+"% match

";

    // make an output row
    makeRow(test, matchScore);

    images[test.name] = {};
    images[test.name].oldImg = oldImg;
    images[test.name].newImg = newImg;
    images[test.name].diffImg = diffImg;
};

function loadView (view) {
    // load and draw scene
    scene.load(view.url).then(function() {
        if (!view) return;
        scene.animated = false;
        map.setView([view.location[0], view.location[1]], view.location[2]);
        scene.requestRedraw();
    });
}

// save a file with a POST request to the server
function saveAs( file, filename ) {
    var url = '/save';
    var data = new FormData();

    data.append("image", file, filename);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.onload = function () {
        // console.log('response:', this.responseText);
        // window.location.href = ".#"+this.responseText;
    };
    xhr.send(data);
}

function stop() {
    console.log('stop button');
    nextView = false;
    queue = false;
}

// convert event to promise
function viewComplete () {
    console.log('viewComplete');
    return new Promise(function(resolve, reject) {
        console.log('viewComplete sent');
        resolve();
    });
}

function makeRow(test, matchScore) {
    // check to see if div already exists (if re-running a test);
    var testdiv = document.getElementById(test.name);

    // if a row for this test doesn't already exist:
    if (testdiv === null) {
        // generate one
        var testdiv = document.createElement('div');
        testdiv.className = 'test';
        testdiv.id = test.name;
        tests.insertBefore(testdiv, tests.firstChild);
    } else {
        // clear it out
        testdiv.innerHTML = "";
    }
    testdiv.style.minHeight = size+"px";

    var title = document.createElement('div');
    title.className = 'testname';
    title.innerHTML = test.name;
    testdiv.appendChild(title);

    var oldcolumn = document.createElement('span');
    oldcolumn.className = 'column';
    oldcolumn.id = "old";
    oldcolumn.innerHTML = "old";
    testdiv.appendChild(oldcolumn);

    var newcolumn = document.createElement('span');
    newcolumn.className = 'column';
    newcolumn.id = "new";
    newcolumn.innerHTML = "new";
    testdiv.appendChild(newcolumn);

    var diffcolumn = document.createElement('span');
    diffcolumn.className = 'column';
    diffcolumn.id = "diff";
    diffcolumn.innerHTML = "diff";
    testdiv.appendChild(diffcolumn);

    // insert old and new images
    newImg.width = size;
    newImg.height = size;
    newcolumn.appendChild( newImg );

    oldImg.width = size;
    oldImg.height = size;
    oldcolumn.appendChild( oldImg );

    // CONTROLS //

    var controls = document.createElement('div');
    controls.className = 'controls';
    testdiv.appendChild(controls);

    var threatLevel = matchScore > 99 ? "green" : matchScore > 95 ? "orange" : "red";

    if (matchScore != "") {
        matchScore += "% match";
        diffImg = document.createElement('img');
        diffImg.src = diffCanvas.toDataURL("image/png");
        diffImg.width = size;
        diffImg.height = size;
        diffcolumn.appendChild( diffImg );
    }

    controls.innerHTML = "
"+matchScore+"

";

    var refreshButton =  document.createElement('button');
    refreshButton.innerHTML = "refresh " + test.name;
    controls.appendChild(refreshButton);
    refreshButton.onclick = function() {refresh(test);}

    var exportButton =  document.createElement('button');
    exportButton.innerHTML = "make PNG";
    // store current value of these global variables
    exportButton.onclick = function() {
        var img = makeStrip([images[test.name].oldImg, images[test.name].newImg, images[test.name].diffImg], lsize);
        popup(img, size * 3, size);
    };
    controls.appendChild(exportButton);

    var exportGifButton =  document.createElement('button');
    exportGifButton.innerHTML = "make GIF";
    exportGifButton.onclick = function() {
        var img = makeGif([images[test.name].oldImg, images[test.name].newImg]);
    };
    controls.appendChild(exportGifButton);

}

function makeStrip(images, size) {
    var c = document.createElement('canvas');
    c.width = size*images.length;
    c.height = size;
    var ctx=c.getContext("2d");
    for (var x in images) {
        ctx.drawImage(images[x], size * x, 0, size, size);
    }
    return c.toDataURL("image/png");
}

function makeGif(images) {
    var gif = new GIF({
      workers: 1,
      quality: 10,
      width: lsize,
      height: lsize,
    });

    for (var y in images) {
        gif.addFrame(images[y]);
    }

    gif.on('finished', function(blob) {
        window.open(URL.createObjectURL(blob));
    });

    gif.render();
}

function popup(img, width, height) {
    var data = '';
    var myWindow = window.open("data:text/html," + encodeURIComponent(data));
}

function makeContactSheet() {
    var c = document.createElement('canvas');
    c.width = lsize*3;
    c.height = lsize*views.length;
    var ctx=c.getContext("2d");
    var i = 0;
    for (var x in images) {
        var img = new Image();
        if (!images.hasOwnProperty(x)) continue; // sigh
        var strip = makeStrip([images[x].oldImg, images[x].newImg, images[x].diffImg], lsize);
        img.src = strip;
        ctx.drawImage(img, 0, lsize * i, lsize * 3, lsize);
        i++;
    }
    var sheet = c.toDataURL("image/png");
    popup(sheet, size * 3, size * images.length);
}

function rerunAll() {
    console.log('refresh all button');
    tests.innerHTML = "";
    totalScoreDiv.innerHTML = "";
    nextView = false;
    totalSum = 0;
    totalScore = 0;
    queue = views.slice(0);
    startRender();
}

function refresh(test) {
    queue.push(test);
    startRender();
}

function startRender() {
    // if map is rendering, wait for it to finish, then start over
    Promise.all([viewComplete]).then(function() {
        // move along
        nextView = queue.shift()
        loadView(nextView);
    });
}

<commit_msg>catch enter key<commit_after>"use strict";
/*jslint browser: true*/
/*global Tangram, gui */

// initialize variables
var map, views, queue, nextView,
    newImg, newCanvas, newCtx, newData,
    oldImg, oldCanvas, oldCtx, oldData,
    diffImg, diffCanvas, diffCtx, diff,
    images = {};
var testsFile = "views.json";
var imgDir = "images/";
var imgType = ".png";
var size = 250; // physical pixels
var lsize = 250 * window.devicePixelRatio; // logical pixels
var scores = [], totalScore = 0;
var tests = document.getElementById("tests");
var alertDiv = document.getElementById("alert");
var statusDiv = document.getElementById("status");
var totalScoreDiv = document.getElementById("totalScore");

// parse URL to check for test json passed in the query
// eg: http://localhost:8080/?test.json
function getValuesFromUrl() {
    var url_query = window.location.search.slice(1, window.location.search.length);
    if (url_query != "") return url_query;
    else return testsFile;
}

testsFile = getValuesFromUrl();
var testsDir = "";
console.log('testsFile', testsFile);
var parseURL = document.createElement('a');
parseURL.href = testsFile;
console.log('testsDir', parseURL.host, parseURL.pathname);

document.getElementById("loadtext").onkeypress = function(e){
    if (!e) e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == '13'){
      // Enter pressed
      loadButton();
      return false;
    }
  }

// load from url
function loadButton() {
    var url = window.location;
    var newlocation = "?" + document.getElementById("loadtext").value;
    console.log('newlocation:', newlocation);
    window.location = newlocation;
}

// load file
function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        // console.log('readyState:', rawFile.readyState);
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            // console.log('rawFile.responseText:', rawFile.responseText);
            callback(rawFile.responseText);
        }
        else if (rawFile.readyState === 4 && rawFile.status == "404") {
            console.error("404 – can't load file", file);
            // set page title
            alertDiv.innerHTML = "404 - can't load file:
"+testsFile+"";
        }

    }
    rawFile.send(null);
}

function parseView(view) {
    // console.log('view:', view);
    if (Object.prototype.toString.call(view["location"]) === '[object Array]') {
        return view; // no parsing needed
    } else if (typeof(view["location"]) === "string") {
        // parse string location as array of floats
        var location = view["location"].split(/[ ,]+/);
        location = location.map(parseFloat);
        view["location"] = location;
        return view;
    } else {
        console.log("Can't parse location:", view);
    }
}

// setup divs and canvases
var prep = new Promise( function (resolve, reject) {
    // load and parse test json
    readTextFile(testsFile, function(text){
        try {
            var data = JSON.parse(text);
        } catch(e) {
            console.log('e:', e);
            // set page title
            alertDiv.innerHTML = "Can't parse JSON:
"+testsFile+"";
            return false;
        }
        // convert tests to an array for easier traversal
        views = Object.keys(data.tests).map(function (key) {
            // add test's name as a property of the test
            data.tests[key].name = key;
            return data.tests[key];
        });

        // clone views array
        queue = views.slice(0);
        nextView = parseView(queue.shift()); // pop first and parse location

        // then initialize Tangram with the first view
        map = (function () {
            // console.log('views:', views);
            // console.log('nextView', nextView.location);
            var map_start_location = nextView.location;

            /*** Map ***/

            var map = L.map('map', {
                keyboardZoomOffset : .05,
                zoomControl: false,
                attributionControl : false
            });

            var layer = Tangram.leafletLayer({
                scene: nextView.url,
                // highDensityDisplay: false
            });

            window.layer = layer;
            var scene = layer.scene;
            window.scene = scene;

            // setView expects format ([lat, long], zoom)
            map.setView(map_start_location.slice(0, 3), map_start_location[2]);

            layer.addTo(map);

            return map;

        }());

        // subscribe to Tangram's published view_complete event to
        // load the next scene when the current scene is done drawing
        scene.subscribe({
            view_complete: function () {
                // console.log('nextView:', nextView);
                if (nextView) {
                    // when prep is done, screenshot is made, and oldImg is loaded...
                    Promise.all([prep,screenshot(true),loadOld(imgDir+nextView.name+imgType)]).then(function() {
                        // perform the diff
                        doDiff(nextView);
                        // move along
                        if (queue.length > 0) {
                            nextView = parseView(queue.shift()); // pop first and parse location
                            loadView(nextView);
                        } else return;
                    });
                } else {
                    console.log('view_complete, no nextView');
                    return viewComplete();
                }
            }
        });

        // set page title
        alertDiv.innerHTML = "Now diffing:
"+testsFile+"";

    });

    // set sizes
    document.getElementById("map").style.height = size+"px";
    document.getElementById("map").style.width = size+"px";

    // set up canvases

    // make canvas for the old image
    oldCanvas = document.createElement('canvas');
    oldCanvas.height = lsize;
    oldCanvas.width = lsize;
    oldCtx = oldCanvas.getContext('2d');

    // make a canvas for the newly-drawn map image
    newCanvas = document.createElement('canvas');
    newCanvas.height = lsize;
    newCanvas.width = lsize;
    newCtx = newCanvas.getContext('2d');

    // make a canvas for the diff
    diffCanvas = document.createElement('canvas');
    diffCanvas.height = lsize;
    diffCanvas.width = lsize;
    diffCtx = diffCanvas.getContext('2d');
    diff = diffCtx.createImageData(lsize, lsize);

    resolve();
});

// load an image asynchronously with a Promise
function loadImage (url, target) {
    return new Promise(function(resolve, reject) {
        var image = target || new Image();
        image.onload = function() {
            resolve({ url: url, image: image });
        };
        image.onerror = function(error) {
            resolve({ error: error });
        };
        image.crossOrigin = 'anonymous';
        // force-refresh any local images with a cache-buster
        if (url.slice(-4) == imgType) url += "?" + new Date().getTime();
        image.src = url;
    });
}

// load the old image
function loadOld (img) {
    oldImg = new Image();
    return loadImage(img).then(function(result){
        if (result.url) {
            // set the old image to be drawn to the canvas once the image loads
            oldImg = result.image;
            oldCtx.drawImage(oldImg, 0, 0, oldImg.width, oldImg.height, 0, 0, oldCanvas.width, oldCanvas.height);
            // make the data available to pixelmatch
            oldData = oldCtx.getImageData(0, 0, lsize, lsize);
        } else {
            oldData = null;
        }
        return result;
    });
};

// take a screenshot
function screenshot (save) {
    return scene.screenshot().then(function(data) {
        // save it to a file
        if (save) saveAs(data.blob, nextView.name);

        var urlCreator = window.URL || window.webkitURL;
        newImg = new Image();
        return loadImage(urlCreator.createObjectURL( data.blob ), newImg);
    });
};

// perform the image comparison and update the html
function doDiff( test ) {
    // save the new image to the new canvas, stretching it to fit (in case it's retina)
    newCtx.drawImage(newImg, 0, 0, newImg.width, newImg.height, 0, 0, newCanvas.width, newCanvas.height);
    // make the data available
    var newData = newCtx.getImageData(0, 0, lsize, lsize);
    if (oldData) {
        // run the diff
        var difference = pixelmatch(newData.data, oldData.data, diff.data, lsize, lsize, {threshold: 0.1});
        // calculate match percentage
        var match = 100-(difference/(lsize*lsize)*100*100)/100;
        var matchScore = Math.floor(match);
        // put the diff in its canvas
        diffCtx.putImageData(diff, 0, 0);
    } else {
        // generating new image
        match = 100;
        matchScore = "";
    }

    // UPDATE READOUTS
    var count = views.length-queue.length;
    statusDiv.innerHTML = count + " of " + views.length;

    // update master percentage
    scores[test.name] = match;
    var totalSum = 0;
    for (var v in scores) {
        totalSum += scores[v];
    }
    totalScore = Math.floor(totalSum/(100*count)*100);
    var threatLevel = totalScore > 99 ? "green" : totalScore > 98 ? "orange" : "red";
    totalScoreDiv.innerHTML = "
"+totalScore+"% match

";

    // make an output row
    makeRow(test, matchScore);

    images[test.name] = {};
    images[test.name].oldImg = oldImg;
    images[test.name].newImg = newImg;
    images[test.name].diffImg = diffImg;
};

function loadView (view) {
    // load and draw scene
    scene.load(view.url).then(function() {
        if (!view) return;
        scene.animated = false;
        map.setView([view.location[0], view.location[1]], view.location[2]);
        scene.requestRedraw();
    });
}

// save a file with a POST request to the server
function saveAs( file, filename ) {
    var url = '/save';
    var data = new FormData();

    data.append("image", file, filename);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.onload = function () {
        // console.log('response:', this.responseText);
        // window.location.href = ".#"+this.responseText;
    };
    xhr.send(data);
}

function stop() {
    console.log('stop button');
    nextView = false;
    queue = false;
}

// convert event to promise
function viewComplete () {
    console.log('viewComplete');
    return new Promise(function(resolve, reject) {
        console.log('viewComplete sent');
        resolve();
    });
}

function makeRow(test, matchScore) {
    // check to see if div already exists (if re-running a test);
    var testdiv = document.getElementById(test.name);

    // if a row for this test doesn't already exist:
    if (testdiv === null) {
        // generate one
        var testdiv = document.createElement('div');
        testdiv.className = 'test';
        testdiv.id = test.name;
        tests.insertBefore(testdiv, tests.firstChild);
    } else {
        // clear it out
        testdiv.innerHTML = "";
    }
    testdiv.style.minHeight = size+"px";

    var title = document.createElement('div');
    title.className = 'testname';
    title.innerHTML = test.name;
    testdiv.appendChild(title);

    var oldcolumn = document.createElement('span');
    oldcolumn.className = 'column';
    oldcolumn.id = "old";
    oldcolumn.innerHTML = "old";
    testdiv.appendChild(oldcolumn);

    var newcolumn = document.createElement('span');
    newcolumn.className = 'column';
    newcolumn.id = "new";
    newcolumn.innerHTML = "new";
    testdiv.appendChild(newcolumn);

    var diffcolumn = document.createElement('span');
    diffcolumn.className = 'column';
    diffcolumn.id = "diff";
    diffcolumn.innerHTML = "diff";
    testdiv.appendChild(diffcolumn);

    // insert old and new images
    newImg.width = size;
    newImg.height = size;
    newcolumn.appendChild( newImg );

    oldImg.width = size;
    oldImg.height = size;
    oldcolumn.appendChild( oldImg );

    // CONTROLS //

    var controls = document.createElement('div');
    controls.className = 'controls';
    testdiv.appendChild(controls);

    var threatLevel = matchScore > 99 ? "green" : matchScore > 95 ? "orange" : "red";

    if (matchScore != "") {
        matchScore += "% match";
        diffImg = document.createElement('img');
        diffImg.src = diffCanvas.toDataURL("image/png");
        diffImg.width = size;
        diffImg.height = size;
        diffcolumn.appendChild( diffImg );
    }

    controls.innerHTML = "
"+matchScore+"

";

    var refreshButton =  document.createElement('button');
    refreshButton.innerHTML = "refresh " + test.name;
    controls.appendChild(refreshButton);
    refreshButton.onclick = function() {refresh(test);}

    var exportButton =  document.createElement('button');
    exportButton.innerHTML = "make PNG";
    // store current value of these global variables
    exportButton.onclick = function() {
        var img = makeStrip([images[test.name].oldImg, images[test.name].newImg, images[test.name].diffImg], lsize);
        popup(img, size * 3, size);
    };
    controls.appendChild(exportButton);

    var exportGifButton =  document.createElement('button');
    exportGifButton.innerHTML = "make GIF";
    exportGifButton.onclick = function() {
        var img = makeGif([images[test.name].oldImg, images[test.name].newImg]);
    };
    controls.appendChild(exportGifButton);

}

function makeStrip(images, size) {
    var c = document.createElement('canvas');
    c.width = size*images.length;
    c.height = size;
    var ctx=c.getContext("2d");
    for (var x in images) {
        ctx.drawImage(images[x], size * x, 0, size, size);
    }
    return c.toDataURL("image/png");
}

function makeGif(images) {
    var gif = new GIF({
      workers: 1,
      quality: 10,
      width: lsize,
      height: lsize,
    });

    for (var y in images) {
        gif.addFrame(images[y]);
    }

    gif.on('finished', function(blob) {
        window.open(URL.createObjectURL(blob));
    });

    gif.render();
}

function popup(img, width, height) {
    var data = '';
    var myWindow = window.open("data:text/html," + encodeURIComponent(data));
}

function makeContactSheet() {
    var c = document.createElement('canvas');
    c.width = lsize*3;
    c.height = lsize*views.length;
    var ctx=c.getContext("2d");
    var i = 0;
    for (var x in images) {
        var img = new Image();
        if (!images.hasOwnProperty(x)) continue; // sigh
        var strip = makeStrip([images[x].oldImg, images[x].newImg, images[x].diffImg], lsize);
        img.src = strip;
        ctx.drawImage(img, 0, lsize * i, lsize * 3, lsize);
        i++;
    }
    var sheet = c.toDataURL("image/png");
    popup(sheet, size * 3, size * images.length);
}

function rerunAll() {
    console.log('refresh all button');
    tests.innerHTML = "";
    totalScoreDiv.innerHTML = "";
    nextView = false;
    totalSum = 0;
    totalScore = 0;
    queue = views.slice(0);
    startRender();
}

function refresh(test) {
    queue.push(test);
    startRender();
}

function startRender() {
    // if map is rendering, wait for it to finish, then start over
    Promise.all([viewComplete]).then(function() {
        // move along
        nextView = queue.shift()
        loadView(nextView);
    });
}

<|endoftext|>


<commit_before>const config = require('./config.addresses.json');
const ENVs = {
    "test":"kovan",
    "main":"live",
    "private":"default"
}

Dapple.init = function init(env) {
  var predefinedEnv = ENVs[env];

  if (!predefinedEnv) {
      predefinedEnv = env;
  }

  Dapple.env = predefinedEnv;

  Dapple['maker-otc']['environments'][Dapple.env]['otc']['value'] = config.market[Dapple.env]
  Dapple['maker-otc'].class(web3, Dapple['maker-otc'].environments[Dapple.env]);
  Dapple['ds-eth-token'].class(web3, Dapple['ds-eth-token'].environments[Dapple.env]);
  Dapple['token-wrapper'].class(web3, Dapple['token-wrapper'].environments[Dapple.env]);

  if (env) {
    // Check if contract exists on new environment
    const contractAddress = Dapple['maker-otc'].environments[Dapple.env].otc.value;
    web3.eth.getCode(contractAddress, (error, code) => {
      Session.set('contractExists', !error && typeof code === 'string' && code !== '' && code !== '0x');
    });
  }
};

const tokens = config.tokens;

// http://numeraljs.com/ for formats
const tokenSpecs = {
  'W-ETH': { precision: 18, format: '0,0.00[0000000000000000]' },
  DAI: { precision: 18, format: '0,0.00[0000000000000000]' },
  MKR: { precision: 18, format: '0,0.00[0000000000000000]' },
  DGD: { precision: 9, format: '0,0.00[0000000]' },
  GNT: { precision: 18, format: '0,0.00[0000000000000000]' },
  'W-GNT': { precision: 18, format: '0,0.00[0000000000000000]' },
  REP: { precision: 18, format: '0,0.00[0000000000000000]' },
  ICN: { precision: 18, format: '0,0.00[0000000000000000]' },
  '1ST': { precision: 18, format: '0,0.00[0000000000000000]' },
  SNGLS: { precision: 0, format: '0,0' },
  VSL: { precision: 18, format: '0,0.00[0000000000000000]' },
  PLU: { precision: 18, format: '0,0.00[0000000000000000]' },
  MLN: { precision: 18, format: '0,0.00[0000000000000000]' },
  RHOC: { precision: 9, format: '0,0.00[0000000]'  }
};

Dapple.getQuoteTokens = () => ['W-ETH'];

Dapple.getBaseTokens = () => ['MKR', 'DGD', 'W-GNT', 'REP', 'ICN', '1ST', 'SNGLS', 'VSL', 'PLU', 'MLN', 'RHOC'];

Dapple.getTokens = () => ['W-ETH', 'MKR', 'DGD', 'GNT', 'W-GNT', 'REP', 'ICN', '1ST', 'SNGLS', 'VSL', 'PLU', 'MLN', 'RHOC'];

Dapple.getTokenSpecs = (symbol) => {
  if (typeof (tokenSpecs[symbol]) !== 'undefined') {
    return tokenSpecs[symbol];
  }
  return tokenSpecs['W-ETH'];
};

Dapple.getTokenAddress = (symbol) => tokens[Dapple.env][symbol];

Dapple.getTokenByAddress = (address) => _.invert(tokens[Dapple.env])[address];

Dapple.getToken = (symbol, callback) => {
  if (!(Dapple.env in tokens)) {
    callback('Unknown environment', null);
    return;
  }
  if (!(symbol in tokens[Dapple.env])) {
    callback(`Unknown token "${symbol}"`, null);
    return;
  }

  const address = Dapple.getTokenAddress(symbol);
  let tokenClass = 'DSTokenBase';
  let that = Dapple['ds-eth-token'];

  if (symbol === 'W-ETH') {
    tokenClass = 'DSEthToken';
  } else if (symbol === 'W-GNT') {
    tokenClass = 'TokenWrapper';
    that = Dapple['token-wrapper'];
  }

  try {
    that.classes[tokenClass].at(address, (error, token) => {
      if (!error) {
        token.abi = that.classes[tokenClass].abi;
        callback(false, token);
      } else {
        callback(error, token);
      }
    });
  } catch (e) {
    callback(e, null);
  }
};
<commit_msg>Fixing the precision of RHOC<commit_after>const config = require('./config.addresses.json');
const ENVs = {
    "test":"kovan",
    "main":"live",
    "private":"default"
}

Dapple.init = function init(env) {
  var predefinedEnv = ENVs[env];

  if (!predefinedEnv) {
      predefinedEnv = env;
  }

  Dapple.env = predefinedEnv;

  Dapple['maker-otc']['environments'][Dapple.env]['otc']['value'] = config.market[Dapple.env]
  Dapple['maker-otc'].class(web3, Dapple['maker-otc'].environments[Dapple.env]);
  Dapple['ds-eth-token'].class(web3, Dapple['ds-eth-token'].environments[Dapple.env]);
  Dapple['token-wrapper'].class(web3, Dapple['token-wrapper'].environments[Dapple.env]);

  if (env) {
    // Check if contract exists on new environment
    const contractAddress = Dapple['maker-otc'].environments[Dapple.env].otc.value;
    web3.eth.getCode(contractAddress, (error, code) => {
      Session.set('contractExists', !error && typeof code === 'string' && code !== '' && code !== '0x');
    });
  }
};

const tokens = config.tokens;

// http://numeraljs.com/ for formats
const tokenSpecs = {
  'W-ETH': { precision: 18, format: '0,0.00[0000000000000000]' },
  DAI: { precision: 18, format: '0,0.00[0000000000000000]' },
  MKR: { precision: 18, format: '0,0.00[0000000000000000]' },
  DGD: { precision: 9, format: '0,0.00[0000000]' },
  GNT: { precision: 18, format: '0,0.00[0000000000000000]' },
  'W-GNT': { precision: 18, format: '0,0.00[0000000000000000]' },
  REP: { precision: 18, format: '0,0.00[0000000000000000]' },
  ICN: { precision: 18, format: '0,0.00[0000000000000000]' },
  '1ST': { precision: 18, format: '0,0.00[0000000000000000]' },
  SNGLS: { precision: 0, format: '0,0' },
  VSL: { precision: 18, format: '0,0.00[0000000000000000]' },
  PLU: { precision: 18, format: '0,0.00[0000000000000000]' },
  MLN: { precision: 18, format: '0,0.00[0000000000000000]' },
  RHOC: { precision: 8, format: '0,0.00[000000]'  }
};

Dapple.getQuoteTokens = () => ['W-ETH'];

Dapple.getBaseTokens = () => ['MKR', 'DGD', 'W-GNT', 'REP', 'ICN', '1ST', 'SNGLS', 'VSL', 'PLU', 'MLN', 'RHOC'];

Dapple.getTokens = () => ['W-ETH', 'MKR', 'DGD', 'GNT', 'W-GNT', 'REP', 'ICN', '1ST', 'SNGLS', 'VSL', 'PLU', 'MLN', 'RHOC'];

Dapple.getTokenSpecs = (symbol) => {
  if (typeof (tokenSpecs[symbol]) !== 'undefined') {
    return tokenSpecs[symbol];
  }
  return tokenSpecs['W-ETH'];
};

Dapple.getTokenAddress = (symbol) => tokens[Dapple.env][symbol];

Dapple.getTokenByAddress = (address) => _.invert(tokens[Dapple.env])[address];

Dapple.getToken = (symbol, callback) => {
  if (!(Dapple.env in tokens)) {
    callback('Unknown environment', null);
    return;
  }
  if (!(symbol in tokens[Dapple.env])) {
    callback(`Unknown token "${symbol}"`, null);
    return;
  }

  const address = Dapple.getTokenAddress(symbol);
  let tokenClass = 'DSTokenBase';
  let that = Dapple['ds-eth-token'];

  if (symbol === 'W-ETH') {
    tokenClass = 'DSEthToken';
  } else if (symbol === 'W-GNT') {
    tokenClass = 'TokenWrapper';
    that = Dapple['token-wrapper'];
  }

  try {
    that.classes[tokenClass].at(address, (error, token) => {
      if (!error) {
        token.abi = that.classes[tokenClass].abi;
        callback(false, token);
      } else {
        callback(error, token);
      }
    });
  } catch (e) {
    callback(e, null);
  }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import './Detail.css'
import Bed from './Bed';
import './PersonInfo.css';

var DetailPage = React.createClass({
    getInitialState: function() {
        //var listArray = [];
        return {
            nameTextField:"",
            ageTextField:"",
            cardIdNoField:"",
            birthdayField:"",
            isEdit:false,
            isNeedBack:false,
            users:[],
            devices:[],
            totoalPeople:0,
            personInfo:{},
            sex:"",
            token:""
        }
    },
    getData: function(recive) {
        // console.info("reciveData",recive)
        if(recive) {
            this.setState({
                isEdit: true,
                personInfo:recive
            });
        }
    },
    componentDidMount: function() {
        console.info("Did Mount");
        var name = "Bob", time = "today";
        var string =`Hello ${name}, how are you ${time}?`
        console.info("string",string)
        var guardID=this.props.passgurdian
        var urlstr = `http://api.51aijia.ren:10000/gateway/guardians/${guardID}/users`;
        //urlstr = urlstr.concat(this.props.passgurdian);
        //urlstr = urlstr.concat("/users");
        var urldevice = "http://api.51aijia.ren:10000/gateway/guardians/";
        urldevice = urldevice.concat(this.props.passgurdian);
        urldevice = urldevice.concat("/devices");
        console.info("拼接后的字符串",urlstr);
        var tokenStr="Bear ";
        tokenStr = tokenStr.concat(this.props.passtoken);
        this.setState({
            token:tokenStr
        })
        //获取所有的用户
        fetch(urlstr, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "Authorization":tokenStr
            },
        })
        .then((response) => response.json())
        .then((responseData) => {
            console.info("userdata",responseData.users);
            this.setState({
                users:responseData.users});

        }) .catch((error) => {
            console.info("error",error);
        });
        //获取所有的设备
        fetch(urldevice, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "Authorization":tokenStr
            },
        })
        .then((response) => response.json())
        .then((responseData) => {
            console.info("devicedata",responseData.devices);
            this.setState({
                devices:responseData.devices});

        }) .catch((error) => {
            console.info("error",error);
        });

    },
    onChangeNameValue: function(e) {
        this.setState({
            nameTextField:e.target.value
        });
    },
    onChangeAgeValue: function(e) {
        this.setState({
            ageTextField:e.target.value
        });
    },
    onChangeCardIdValue: function(e) {
        this.setState({
            cardIdNoField:e.target.value
        });
    },
    onChangeBirthdayValue: function(e) {
        this.setState({
            birthdayField:e.target.value
        });
    },
    handleCancle: function () {
        console.info("quxiao")
        this.setState({
            isEdit:false
        })
    },
    editUser: function () {
        var guardID = this.state.personInfo.guardianId
        var userID = this.state.personInfo.id
        var urlstr = `http://api.51aijia.ren:10000/gateway/guardians/${guardID}/users/${userID}`
        var body = {
            "name":this.state.nameTextField?this.state.nameTextField:this.state.personInfo.name,
            "birthday":this.state.birthdayField?this.state.birthdayField:this.state.personInfo.birthday,
            "sex":this.state.ageTextField?this.state.ageTextField:this.state.personInfo.sex,
            // "carId":this.state.cardIdNoField?this.state.cardIdNoField:this.state.personInfo.cardId
        }
        console.info("body==",body)
        fetch(urlstr, {
            method: "PUT",
            headers: {
                "Content-Type": "application/json",
                "Authorization":this.state.token
            },
            body: JSON.stringify(body),
        })
        .then((response) => response.json())
       .then((responseData) => {
           console.info("修改用户资料=================",responseData);
           this.setState({
               //response:responseData
               isEdit:false,
               nameTextField:"",
               ageTextField:"",
               cardIdNoField:"",
               birthdayField:"",
           });
            var guardID = this.state.personInfo.guardianId
           var urlstr = `http://api.51aijia.ren:10000/gateway/guardians/${guardID}/users`
           fetch(urlstr, {
               method: "GET",
               headers: {
                   "Content-Type": "application/json",
                   "Authorization":this.state.token
               },
           })
           .then((response) => response.json())
           .then((responseData) => {
               console.info("刷新事件=========",responseData.users);
               this.setState({
                   users:responseData.users});

           }) .catch((error) => {
               console.info("error",error);
           });

        })
        .catch((error) => {
            console.info("error",error);
        });

    },
    handleSubmit: function () {
        console.info("queren")
        this.editUser()
    },
    render: function() {
        //console.info("tokennnnnnnn",this.props.passtoken);
        //console.info("guardianId",this.props.passgurdian);
        let a = [1,2,3,4,5,6]
        //let c = ["gwc","gwc2","gwc3","gwc4","gwc5","gwc6"]
        let c = this.state.users
        let b = c.map(value => {
            console.info("valuevalue",value);
            return <Bed callBack={this.getData} data={value} key={value.id} name={value.name} heartbeatLowerAlarm={value.heartbeatLowerAlarm} sex={value.sex} breathLowerAlarm={value.breathLowerAlarm}/>
        })

        console.info("用户列表",this.state.users);
        console.info("设备列表",this.state.devices);
        var describle = "总床位数";
        describle = describle.concat(this.state.devices.length);
        describle = describle.concat("掉线入住人数告警");
        if(this.state.isEdit){
            console.info(this.state.personInfo.id)
            return(

                            名字

                    <input type="text"
                        onChange={this.onChangeNameValue}
                        value={this.state.nameTextField ? this.state.nameTextField : this.state.personInfo.name}
                        className="PerNameInput">
                    </input>

                            性别

                    <input type="text"
                        onChange={this.onChangeAgeValue}
                        value={this.state.ageTextField ? this.state.ageTextField : this.state.personInfo.sex}
                        className="PerNameInput">
                    </input>

                            号码

                    <input type="text"
                        onChange={this.onChangeCardIdValue}
                        value={this.state.cardIdNoField ? this.state.cardIdNoField:this.state.personInfo.cardId}
                        className="PerNameInput">
                    </input>

                            生日

                    <input type="text"
                        onChange={this.onChangeBirthdayValue}
                        value={this.state.birthdayField ? this.state.birthdayField:this.state.personInfo.birthday}
                        className="PerNameInput">
                    </input>

                        <button className="PButton"
                        onClick={this.handleCancle}
                        name="button">
                        取消
                    </button>
                    <button className="PButton"
                        onClick={this.handleSubmit}
                        name="button">
                        确认
                    </button>

            );
        }else{
            return(

                        <button className="button button1"> 用户名
                        </button>
                        <button className="button button1">
                            设备
                        </button>   <button className="button button1">
                            退出
                        </button>

                            {describle}

                        {b}

            );
        }
    }
});
export default DetailPage;
<commit_msg>cardType cardId<commit_after>import React, { Component } from 'react';
import './Detail.css'
import Bed from './Bed';
import './PersonInfo.css';

var DetailPage = React.createClass({
    getInitialState: function() {
        //var listArray = [];
        return {
            nameTextField:"",
            ageTextField:"",
            cardIdNoField:"",
            birthdayField:"",
            isEdit:false,
            isNeedBack:false,
            users:[],
            devices:[],
            totoalPeople:0,
            personInfo:{},
            sex:"",
            token:""
        }
    },
    getData: function(recive) {
        // console.info("reciveData",recive)
        if(recive) {
            this.setState({
                isEdit: true,
                personInfo:recive
            });
        }
    },
    componentDidMount: function() {
        console.info("Did Mount");
        var name = "Bob", time = "today";
        var string =`Hello ${name}, how are you ${time}?`
        console.info("string",string)
        var guardID=this.props.passgurdian
        var urlstr = `http://api.51aijia.ren:10000/gateway/guardians/${guardID}/users`;
        //urlstr = urlstr.concat(this.props.passgurdian);
        //urlstr = urlstr.concat("/users");
        var urldevice = "http://api.51aijia.ren:10000/gateway/guardians/";
        urldevice = urldevice.concat(this.props.passgurdian);
        urldevice = urldevice.concat("/devices");
        console.info("拼接后的字符串",urlstr);
        var tokenStr="Bear ";
        tokenStr = tokenStr.concat(this.props.passtoken);
        this.setState({
            token:tokenStr
        })
        //获取所有的用户
        fetch(urlstr, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "Authorization":tokenStr
            },
        })
        .then((response) => response.json())
        .then((responseData) => {
            console.info("userdata",responseData.users);
            this.setState({
                users:responseData.users});

        }) .catch((error) => {
            console.info("error",error);
        });
        //获取所有的设备
        fetch(urldevice, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "Authorization":tokenStr
            },
        })
        .then((response) => response.json())
        .then((responseData) => {
            console.info("devicedata",responseData.devices);
            this.setState({
                devices:responseData.devices});

        }) .catch((error) => {
            console.info("error",error);
        });

    },
    onChangeNameValue: function(e) {
        this.setState({
            nameTextField:e.target.value
        });
    },
    onChangeAgeValue: function(e) {
        this.setState({
            ageTextField:e.target.value
        });
    },
    onChangeCardIdValue: function(e) {
        this.setState({
            cardIdNoField:e.target.value
        });
    },
    onChangeBirthdayValue: function(e) {
        this.setState({
            birthdayField:e.target.value
        });
    },
    handleCancle: function () {
        console.info("quxiao")
        this.setState({
            isEdit:false
        })
    },
    editUser: function () {
        var guardID = this.state.personInfo.guardianId
        var userID = this.state.personInfo.id
        var urlstr = `http://api.51aijia.ren:10000/gateway/guardians/${guardID}/users/${userID}`
        var body = {
            "name":this.state.nameTextField?this.state.nameTextField:this.state.personInfo.name,
            "birthday":this.state.birthdayField?this.state.birthdayField:this.state.personInfo.birthday,
            "sex":this.state.ageTextField?this.state.ageTextField:this.state.personInfo.sex,
            "cardType":"idCard",
            "cardId":this.state.cardIdNoField?this.state.cardIdNoField:this.state.personInfo.cardId
        }
        console.info("body==",body)
        fetch(urlstr, {
            method: "PUT",
            headers: {
                "Content-Type": "application/json",
                "Authorization":this.state.token
            },
            body: JSON.stringify(body),
        })
        .then((response) => response.json())
       .then((responseData) => {
           console.info("修改用户资料=================",responseData);
           this.setState({
               //response:responseData
               isEdit:false,
               nameTextField:"",
               ageTextField:"",
               cardIdNoField:"",
               birthdayField:"",
           });
            var guardID = this.state.personInfo.guardianId
           var urlstr = `http://api.51aijia.ren:10000/gateway/guardians/${guardID}/users`
           fetch(urlstr, {
               method: "GET",
               headers: {
                   "Content-Type": "application/json",
                   "Authorization":this.state.token
               },
           })
           .then((response) => response.json())
           .then((responseData) => {
               console.info("刷新事件=========",responseData.users);
               this.setState({
                   users:responseData.users});

           }) .catch((error) => {
               console.info("error",error);
           });

        })
        .catch((error) => {
            console.info("error",error);
        });

    },
    handleSubmit: function () {
        console.info("queren")
        this.editUser()
    },
    userNameClick: function () {
        console.info("userNameClick");
    },
    deviceClick: function () {
        console.info("deviceClick")
    },
    signOut: function () {
        console.info("signOut");
    },
    render: function() {
        //console.info("tokennnnnnnn",this.props.passtoken);
        //console.info("guardianId",this.props.passgurdian);
        let a = [1,2,3,4,5,6]
        //let c = ["gwc","gwc2","gwc3","gwc4","gwc5","gwc6"]
        let c = this.state.users
        let b = c.map(value => {
            console.info("valuevalue",value);
            return <Bed callBack={this.getData} data={value} key={value.id} name={value.name} heartbeatLowerAlarm={value.heartbeatLowerAlarm} sex={value.sex} breathLowerAlarm={value.breathLowerAlarm}/>
        })

        console.info("用户列表",this.state.users);
        console.info("设备列表",this.state.devices);
        var describle = "总床位数";
        describle = describle.concat(this.state.devices.length);
        describle = describle.concat("掉线入住人数告警");
        if(this.state.isEdit){
            console.info(this.state.personInfo.id)
            return(

                            名字

                    <input type="text"
                        onChange={this.onChangeNameValue}
                        value={this.state.nameTextField ? this.state.nameTextField : this.state.personInfo.name}
                        className="PerNameInput">
                    </input>

                            性别

                    <input type="text"
                        onChange={this.onChangeAgeValue}
                        value={this.state.ageTextField ? this.state.ageTextField : this.state.personInfo.sex}
                        className="PerNameInput">
                    </input>

                            号码

                    <input type="text"
                        onChange={this.onChangeCardIdValue}
                        value={this.state.cardIdNoField ? this.state.cardIdNoField:this.state.personInfo.cardId}
                        className="PerNameInput">
                    </input>

                            生日

                    <input type="text"
                        onChange={this.onChangeBirthdayValue}
                        value={this.state.birthdayField ? this.state.birthdayField:this.state.personInfo.birthday}
                        className="PerNameInput">
                    </input>

                        <button className="PButton"
                        onClick={this.handleCancle}
                        name="button">
                        取消
                    </button>
                    <button className="PButton"
                        onClick={this.handleSubmit}
                        name="button">
                        确认
                    </button>

            );
        }else{
            return(

                        <button className="button button1"
                            onClick={this.userNameClick}
                        > 用户名
                        </button>
                        <button className="button button1"
                            onClick={this.deviceClick}
                        >
                            设备
                            </button>   <button className="button button1"
                            onClick={this.signOut}
                        >
                            退出
                        </button>

                            {describle}

                        {b}

            );
        }
    }
});
export default DetailPage;
<|endoftext|>