<commit_before>frappe.provide("frappe.ui.form");

frappe.ui.form.PrintPreview = Class.extend({
	init: function (opts) {
		$.extend(this, opts);
		this.make();
		this.bind_events();
	},
	make: function () {
		this.wrapper = this.frm.page.add_view("print", frappe.render_template("print_layout", {}));

		// only system manager can edit
		this.wrapper.find(".btn-print-edit").toggle(frappe.user.has_role("System Manager"));
	},
	bind_events: function () {
		var me = this;
		this.wrapper.find(".btn-print-close").click(function () {
			me.frm.hide_print();
		});

		// hide print view on pressing escape, only if there is no focus on any input
		$(document).on("keydown", function (e) {
			if (e.which === 27 && me.frm && e.target === document.body) {
				me.frm.hide_print();
			}
		});

		this.print_formats = frappe.meta.get_print_formats(this.frm.meta.name);
		this.print_letterhead = this.wrapper
			.find(".print-letterhead")
			.on("change", function () { me.print_sel.trigger("change"); })
			.prop("checked", cint(
				(frappe.model.get_doc(":Print Settings", "Print Settings")
					|| { with_letterhead: 1 }).with_letterhead) ? true : false);
		this.print_sel = this.wrapper
			.find(".print-preview-select")
			.on("change", function () {
				me.set_default_print_language();
				me.multilingual_preview();
			});

		//On selection of language get code and pass it to preview method
		this.language_sel = this.wrapper
			.find(".languages")
			.on("change", function () {
				me.lang_code = me.language_sel.val()
				me.multilingual_preview()
			});

		this.wrapper.find(".btn-print-print").click(function () {
			if (me.is_old_style()) {
				me.print_old_style();
			} else {
				me.printit();
			}
		});

		this.wrapper.find(".btn-print-preview").click(function () {
			if (me.is_old_style()) {
				me.new_page_preview_old_style();
			} else {
				me.new_page_preview();
			}
		});

		this.wrapper.find(".btn-download-pdf").click(function () {
			if (!me.is_old_style()) {
				var w = window.open(
					frappe.urllib.get_full_url("/api/method/frappe.utils.print_format.download_pdf?"
						+ "doctype=" + encodeURIComponent(me.frm.doc.doctype)
						+ "&name=" + encodeURIComponent(me.frm.doc.name)
						+ "&format=" + me.selected_format()
						+ "&no_letterhead=" + (me.with_letterhead() ? "0" : "1")
						+ (me.lang_code ? ("&_lang=" + me.lang_code) : ""))
				);
				if (!w) {
					frappe.msgprint(__("Please enable pop-ups")); return;
				}
			}
		});

		this.wrapper.find(".btn-print-edit").on("click", function () {
			let print_format = me.get_print_format();
			let is_custom_format = print_format.name
				&& print_format.print_format_builder
				&& print_format.standard === 'No';
			let is_standard_but_editable = print_format.name && print_format.custom_format;

			if (is_standard_but_editable) {
				frappe.set_route("Form", "Print Format", print_format.name);
				return;
			}
			if (is_custom_format) {
				frappe.set_route("print-format-builder", print_format.name);
				return;
			}
			// start a new print format
			frappe.prompt([
				{
					label: __("New Print Format Name"),
					fieldname: "print_format_name",
					fieldtype: "Data",
					reqd: 1,
				},
				{
					label: __('Based On'),
					fieldname: 'based_on',
					fieldtype: 'Read Only',
					default: print_format.name || 'Standard'
				}
			], function (data) {
				frappe.route_options = {
					make_new: true,
					doctype: me.frm.doctype,
					name: data.print_format_name,
					based_on: data.based_on
				};
				frappe.set_route("print-format-builder");
			}, __("New Custom Print Format"), __("Start"));
		});
	},
	set_user_lang: function () {
		this.lang_code = this.frm.doc.language;
		// Load all languages in the field
		this.language_sel.empty()
			.add_options([{value:'', label:__("Select Language...")}]
				.concat(frappe.get_languages()))
			.val(this.lang_code);
		this.preview();
	},
	set_default_print_language: function () {
 		var print_format = this.get_print_format();
		this.lang_code = print_format.default_print_format || frappe.boot.lang;
		this.language_sel.val(this.lang_code);
 	},
	multilingual_preview: function () {
		var me = this;
		if (this.is_old_style()) {
			me.wrapper.find(".btn-download-pdf").toggle(false);
			me.set_style();
			me.preview_old_style();
		} else {
			me.wrapper.find(".btn-download-pdf").toggle(true);
			me.preview();
		}
	},
	preview: function () {
		var me = this;
		this.get_print_html(function (out) {
			const $print_format = me.wrapper.find(".print-format");
			$print_format.html(out.html);
			me.show_footer();
			me.set_style(out.style);

			const print_height = $print_format.get(0).offsetHeight;
			const $message = me.wrapper.find(".page-break-message");

			const print_height_inches = frappe.dom.pixel_to_inches(print_height);
			// if contents are large enough, indicate that it will get printed on multiple pages
			// Maximum height for an A4 document is 11.69 inches
			if (print_height_inches > 11.69) {
				$message.text(__('This may get printed on multiple pages'));
			} else {
				$message.text('');
			}
		});
	},
	show_footer: function() {
		// footer is hidden by default as reqd by pdf generation
		// simple hack to show it in print preview
		this.wrapper.find('.print-format').css({
			display: 'flex',
			flexDirection: 'column'
		});
		this.wrapper.find('.page-break').css({
			'display': 'flex',
			'flex-direction': 'column',
			'flex': '1'
		});
		this.wrapper.find('#footer-html').attr('style', `
			display: block !important;
			order: 1;
			margin-top: auto;
		`);
	},
	printit: function () {
		let print_server ;
		var me = this;
		frappe.call({
			method: "frappe.printing.doctype.print_settings.print_settings.is_print_server_enabled",
			callback: function (data) {
				if (data.message) {
					frappe.call({
						"method": "frappe.utils.print_format.print_by_server",
						args: {
							doctype: me.frm.doc.doctype,
							name: me.frm.doc.name,
							print_format:  me.selected_format(),
							no_letterhead: me.with_letterhead()
						},
						callback: function (data) {
						}
					});
				} else {
					me.new_page_preview(true);
				}
			}
		});
	},
	new_page_preview: function (printit) {
		var me = this;
		var w = window.open(frappe.urllib.get_full_url("/printview?"
			+ "doctype=" + encodeURIComponent(me.frm.doc.doctype)
			+ "&name=" + encodeURIComponent(me.frm.doc.name)
			+ (printit ? "&trigger_print=1" : "")
			+ "&format=" + me.selected_format()
			+ "&no_letterhead=" + (me.with_letterhead() ? "0" : "1")
			+ (me.lang_code ? ("&_lang=" + me.lang_code) : "")));
		if (!w) {
			frappe.msgprint(__("Please enable pop-ups")); return;
		}
	},
	get_print_html: function (callback) {
		if (this._req) {
			this._req.abort();
		}
		this._req = frappe.call({
			method: "frappe.www.printview.get_html_and_style",
			args: {
				doc: this.frm.doc,
				print_format: this.selected_format(),
				no_letterhead: !this.with_letterhead() ? 1 : 0,
				_lang: this.lang_code
			},
			callback: function (r) {
				if (!r.exc) {
					callback(r.message);
				}
			}
		});
	},
	preview_old_style: function () {
		var me = this;
		this.with_old_style({
			format: me.print_sel.val(),
			callback: function (html) {
				me.wrapper.find(".print-format").html('
'
					+ __("Warning: This Print Format is in old style and cannot be generated via the API.")
					+ '
'
					+ html);
			},
			no_letterhead: !this.with_letterhead(),
			only_body: true,
			no_heading: true
		});
	},
	refresh_print_options: function () {
		this.print_formats = frappe.meta.get_print_formats(this.frm.doctype);
		return this.print_sel
			.empty().add_options(this.print_formats);

	},
	with_old_style: function (opts) {
		frappe.require("/assets/js/print_format_v3.min.js", function () {
			_p.build(opts.format, opts.callback, opts.no_letterhead, opts.only_body, opts.no_heading);
		});
	},
	print_old_style: function () {
		var me = this;
		frappe.require("/assets/js/print_format_v3.min.js", function () {
			_p.build(me.print_sel.val(), _p.go,
				!me.with_letterhead());
		});
	},
	new_page_preview_old_style: function () {
		var me = this;
		frappe.require("/assets/js/print_format_v3.min.js", function () {
			_p.build(me.print_sel.val(), _p.preview, !me.with_letterhead());
		});
	},
	selected_format: function () {
		return this.print_sel.val() || this.frm.meta.default_print_format || "Standard";
	},
	is_old_style: function (format) {
		return this.get_print_format(format).print_format_type === "Client";
	},
	get_print_format: function (format) {
		if (!format) {
			format = this.selected_format();
		}

		if (locals["Print Format"] && locals["Print Format"][format]) {
			return locals["Print Format"][format]
		} else {
			return {}
		}
	},
	with_letterhead: function () {
		return this.print_letterhead.is(":checked") ? 1 : 0;
	},
	set_style: function (style) {
		frappe.dom.set_style(style || frappe.boot.print_css, "print-style");
	}
});

frappe.ui.get_print_settings = function (pdf, callback, letter_head) {
	var print_settings = locals[":Print Settings"]["Print Settings"];

	var default_letter_head = locals[":Company"] && frappe.defaults.get_default('company')
		? locals[":Company"][frappe.defaults.get_default('company')]["default_letter_head"]
		: '';

	var columns = [{
		fieldtype: "Check",
		fieldname: "with_letter_head",
		label: __("With Letter head")
	}, {
		fieldtype: "Select",
		fieldname: "letter_head",
		label: __("Letter Head"),
		depends_on: "with_letter_head",
		options: $.map(frappe.boot.letter_heads, function (i, d) { return d }),
		default: letter_head || default_letter_head
	}, {
		fieldtype: "Select",
		fieldname: "orientation",
		label: __("Orientation"),
		options: "Landscape\nPortrait",
		default: "Landscape"
	}];

	frappe.prompt(columns, function (data) {
		var data = $.extend(print_settings, data);
		if (!data.with_letter_head) {
			data.letter_head = null;
		}
		if (data.letter_head) {
			data.letter_head = frappe.boot.letter_heads[print_settings.letter_head];
		}
		callback(data);
	}, __("Print Settings"));
}
<commit_msg>fix: default_print_language instead of default_print_format (#7461)<commit_after>frappe.provide("frappe.ui.form");

frappe.ui.form.PrintPreview = Class.extend({
	init: function (opts) {
		$.extend(this, opts);
		this.make();
		this.bind_events();
	},
	make: function () {
		this.wrapper = this.frm.page.add_view("print", frappe.render_template("print_layout", {}));

		// only system manager can edit
		this.wrapper.find(".btn-print-edit").toggle(frappe.user.has_role("System Manager"));
	},
	bind_events: function () {
		var me = this;
		this.wrapper.find(".btn-print-close").click(function () {
			me.frm.hide_print();
		});

		// hide print view on pressing escape, only if there is no focus on any input
		$(document).on("keydown", function (e) {
			if (e.which === 27 && me.frm && e.target === document.body) {
				me.frm.hide_print();
			}
		});

		this.print_formats = frappe.meta.get_print_formats(this.frm.meta.name);
		this.print_letterhead = this.wrapper
			.find(".print-letterhead")
			.on("change", function () { me.print_sel.trigger("change"); })
			.prop("checked", cint(
				(frappe.model.get_doc(":Print Settings", "Print Settings")
					|| { with_letterhead: 1 }).with_letterhead) ? true : false);
		this.print_sel = this.wrapper
			.find(".print-preview-select")
			.on("change", function () {
				me.set_default_print_language();
				me.multilingual_preview();
			});

		//On selection of language get code and pass it to preview method
		this.language_sel = this.wrapper
			.find(".languages")
			.on("change", function () {
				me.lang_code = me.language_sel.val()
				me.multilingual_preview()
			});

		this.wrapper.find(".btn-print-print").click(function () {
			if (me.is_old_style()) {
				me.print_old_style();
			} else {
				me.printit();
			}
		});

		this.wrapper.find(".btn-print-preview").click(function () {
			if (me.is_old_style()) {
				me.new_page_preview_old_style();
			} else {
				me.new_page_preview();
			}
		});

		this.wrapper.find(".btn-download-pdf").click(function () {
			if (!me.is_old_style()) {
				var w = window.open(
					frappe.urllib.get_full_url("/api/method/frappe.utils.print_format.download_pdf?"
						+ "doctype=" + encodeURIComponent(me.frm.doc.doctype)
						+ "&name=" + encodeURIComponent(me.frm.doc.name)
						+ "&format=" + me.selected_format()
						+ "&no_letterhead=" + (me.with_letterhead() ? "0" : "1")
						+ (me.lang_code ? ("&_lang=" + me.lang_code) : ""))
				);
				if (!w) {
					frappe.msgprint(__("Please enable pop-ups")); return;
				}
			}
		});

		this.wrapper.find(".btn-print-edit").on("click", function () {
			let print_format = me.get_print_format();
			let is_custom_format = print_format.name
				&& print_format.print_format_builder
				&& print_format.standard === 'No';
			let is_standard_but_editable = print_format.name && print_format.custom_format;

			if (is_standard_but_editable) {
				frappe.set_route("Form", "Print Format", print_format.name);
				return;
			}
			if (is_custom_format) {
				frappe.set_route("print-format-builder", print_format.name);
				return;
			}
			// start a new print format
			frappe.prompt([
				{
					label: __("New Print Format Name"),
					fieldname: "print_format_name",
					fieldtype: "Data",
					reqd: 1,
				},
				{
					label: __('Based On'),
					fieldname: 'based_on',
					fieldtype: 'Read Only',
					default: print_format.name || 'Standard'
				}
			], function (data) {
				frappe.route_options = {
					make_new: true,
					doctype: me.frm.doctype,
					name: data.print_format_name,
					based_on: data.based_on
				};
				frappe.set_route("print-format-builder");
			}, __("New Custom Print Format"), __("Start"));
		});
	},
	set_user_lang: function () {
		this.lang_code = this.frm.doc.language;
		// Load all languages in the field
		this.language_sel.empty()
			.add_options([{value:'', label:__("Select Language...")}]
				.concat(frappe.get_languages()))
			.val(this.lang_code);
		this.preview();
	},
	set_default_print_language: function () {
 		var print_format = this.get_print_format();
		this.lang_code = print_format.default_print_language || frappe.boot.lang;
		this.language_sel.val(this.lang_code);
 	},
	multilingual_preview: function () {
		var me = this;
		if (this.is_old_style()) {
			me.wrapper.find(".btn-download-pdf").toggle(false);
			me.set_style();
			me.preview_old_style();
		} else {
			me.wrapper.find(".btn-download-pdf").toggle(true);
			me.preview();
		}
	},
	preview: function () {
		var me = this;
		this.get_print_html(function (out) {
			const $print_format = me.wrapper.find(".print-format");
			$print_format.html(out.html);
			me.show_footer();
			me.set_style(out.style);

			const print_height = $print_format.get(0).offsetHeight;
			const $message = me.wrapper.find(".page-break-message");

			const print_height_inches = frappe.dom.pixel_to_inches(print_height);
			// if contents are large enough, indicate that it will get printed on multiple pages
			// Maximum height for an A4 document is 11.69 inches
			if (print_height_inches > 11.69) {
				$message.text(__('This may get printed on multiple pages'));
			} else {
				$message.text('');
			}
		});
	},
	show_footer: function() {
		// footer is hidden by default as reqd by pdf generation
		// simple hack to show it in print preview
		this.wrapper.find('.print-format').css({
			display: 'flex',
			flexDirection: 'column'
		});
		this.wrapper.find('.page-break').css({
			'display': 'flex',
			'flex-direction': 'column',
			'flex': '1'
		});
		this.wrapper.find('#footer-html').attr('style', `
			display: block !important;
			order: 1;
			margin-top: auto;
		`);
	},
	printit: function () {
		let print_server ;
		var me = this;
		frappe.call({
			method: "frappe.printing.doctype.print_settings.print_settings.is_print_server_enabled",
			callback: function (data) {
				if (data.message) {
					frappe.call({
						"method": "frappe.utils.print_format.print_by_server",
						args: {
							doctype: me.frm.doc.doctype,
							name: me.frm.doc.name,
							print_format:  me.selected_format(),
							no_letterhead: me.with_letterhead()
						},
						callback: function (data) {
						}
					});
				} else {
					me.new_page_preview(true);
				}
			}
		});
	},
	new_page_preview: function (printit) {
		var me = this;
		var w = window.open(frappe.urllib.get_full_url("/printview?"
			+ "doctype=" + encodeURIComponent(me.frm.doc.doctype)
			+ "&name=" + encodeURIComponent(me.frm.doc.name)
			+ (printit ? "&trigger_print=1" : "")
			+ "&format=" + me.selected_format()
			+ "&no_letterhead=" + (me.with_letterhead() ? "0" : "1")
			+ (me.lang_code ? ("&_lang=" + me.lang_code) : "")));
		if (!w) {
			frappe.msgprint(__("Please enable pop-ups")); return;
		}
	},
	get_print_html: function (callback) {
		if (this._req) {
			this._req.abort();
		}
		this._req = frappe.call({
			method: "frappe.www.printview.get_html_and_style",
			args: {
				doc: this.frm.doc,
				print_format: this.selected_format(),
				no_letterhead: !this.with_letterhead() ? 1 : 0,
				_lang: this.lang_code
			},
			callback: function (r) {
				if (!r.exc) {
					callback(r.message);
				}
			}
		});
	},
	preview_old_style: function () {
		var me = this;
		this.with_old_style({
			format: me.print_sel.val(),
			callback: function (html) {
				me.wrapper.find(".print-format").html('
'
					+ __("Warning: This Print Format is in old style and cannot be generated via the API.")
					+ '
'
					+ html);
			},
			no_letterhead: !this.with_letterhead(),
			only_body: true,
			no_heading: true
		});
	},
	refresh_print_options: function () {
		this.print_formats = frappe.meta.get_print_formats(this.frm.doctype);
		return this.print_sel
			.empty().add_options(this.print_formats);

	},
	with_old_style: function (opts) {
		frappe.require("/assets/js/print_format_v3.min.js", function () {
			_p.build(opts.format, opts.callback, opts.no_letterhead, opts.only_body, opts.no_heading);
		});
	},
	print_old_style: function () {
		var me = this;
		frappe.require("/assets/js/print_format_v3.min.js", function () {
			_p.build(me.print_sel.val(), _p.go,
				!me.with_letterhead());
		});
	},
	new_page_preview_old_style: function () {
		var me = this;
		frappe.require("/assets/js/print_format_v3.min.js", function () {
			_p.build(me.print_sel.val(), _p.preview, !me.with_letterhead());
		});
	},
	selected_format: function () {
		return this.print_sel.val() || this.frm.meta.default_print_format || "Standard";
	},
	is_old_style: function (format) {
		return this.get_print_format(format).print_format_type === "Client";
	},
	get_print_format: function (format) {
		if (!format) {
			format = this.selected_format();
		}

		if (locals["Print Format"] && locals["Print Format"][format]) {
			return locals["Print Format"][format]
		} else {
			return {}
		}
	},
	with_letterhead: function () {
		return this.print_letterhead.is(":checked") ? 1 : 0;
	},
	set_style: function (style) {
		frappe.dom.set_style(style || frappe.boot.print_css, "print-style");
	}
});

frappe.ui.get_print_settings = function (pdf, callback, letter_head) {
	var print_settings = locals[":Print Settings"]["Print Settings"];

	var default_letter_head = locals[":Company"] && frappe.defaults.get_default('company')
		? locals[":Company"][frappe.defaults.get_default('company')]["default_letter_head"]
		: '';

	var columns = [{
		fieldtype: "Check",
		fieldname: "with_letter_head",
		label: __("With Letter head")
	}, {
		fieldtype: "Select",
		fieldname: "letter_head",
		label: __("Letter Head"),
		depends_on: "with_letter_head",
		options: $.map(frappe.boot.letter_heads, function (i, d) { return d }),
		default: letter_head || default_letter_head
	}, {
		fieldtype: "Select",
		fieldname: "orientation",
		label: __("Orientation"),
		options: "Landscape\nPortrait",
		default: "Landscape"
	}];

	frappe.prompt(columns, function (data) {
		var data = $.extend(print_settings, data);
		if (!data.with_letter_head) {
			data.letter_head = null;
		}
		if (data.letter_head) {
			data.letter_head = frappe.boot.letter_heads[print_settings.letter_head];
		}
		callback(data);
	}, __("Print Settings"));
}
<|endoftext|>


<commit_before><commit_msg>force API links to use api.datausa.io<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

$.extend(frappe.model, {
	docinfo: {},
	sync: function(r) {
		/* docs:
			extract docs, docinfo (attachments, comments, assignments)
			from incoming request and set in `locals` and `frappe.model.docinfo`
		*/
		var isPlain;
		if(!r.docs && !r.docinfo) r = {docs:r};

		isPlain = $.isPlainObject(r.docs);
		if(isPlain) r.docs = [r.docs];

		if(r.docs) {
			var last_parent_name = null;

			for(var i=0, l=r.docs.length; i<l; i++) {
				var d = r.docs[i];

				if (locals[d.doctype] && locals[d.doctype][d.name]) {
					// update values
					frappe.model.update_in_locals(d);
				} else {
					frappe.model.add_to_locals(d);
				}

				d.__last_sync_on = new Date();

				if(d.doctype==="DocType") {
					frappe.meta.sync(d);
				}

				if(d.localname) {
					frappe.model.new_names[d.localname] = d.name;
					$(document).trigger('rename', [d.doctype, d.localname, d.name]);
					delete locals[d.doctype][d.localname];

					// update docinfo to new dict keys
					if(i===0) {
						frappe.model.docinfo[d.doctype][d.name] = frappe.model.docinfo[d.doctype][d.localname];
						frappe.model.docinfo[d.doctype][d.localname] = undefined;
					}
				}
			}

		}

		// set docinfo (comments, assign, attachments)
		if(r.docinfo) {
			if(r.docs) {
				var doc = r.docs[0];
			} else {
				if(cur_frm)
					var doc = cur_frm.doc;
			}
			if(doc) {
				if(!frappe.model.docinfo[doc.doctype])
					frappe.model.docinfo[doc.doctype] = {};
				frappe.model.docinfo[doc.doctype][doc.name] = r.docinfo;
			}
		}

		return r.docs;
	},
	add_to_locals: function(doc) {
		if(!locals[doc.doctype])
			locals[doc.doctype] = {};

		if(!doc.name && doc.__islocal) { // get name (local if required)
			if(!doc.parentfield) frappe.model.clear_doc(doc);

			doc.name = frappe.model.get_new_name(doc.doctype);

			if(!doc.parentfield) frappe.provide("frappe.model.docinfo." + doc.doctype + "." + doc.name);
		}

		locals[doc.doctype][doc.name] = doc;

		// add child docs to locals
		if(!doc.parentfield) {
			for(var i in doc) {
				var value = doc[i];

				if($.isArray(value)) {
					for (var x=0, y=value.length; x < y; x++) {
						var d = value[x];

						if(!d.parent)
							d.parent = doc.name;

						frappe.model.add_to_locals(d);
					}
				}
			}
		}
	},
	update_in_locals: function(doc) {
		// update values in the existing local doc instead of replacing
		let local_doc = locals[doc.doctype][doc.name];
		for (let fieldname in doc) {
			if (local_doc[fieldname] instanceof Array) {
				// table
				if (!(doc[fieldname] instanceof Array)) {
					doc[fieldname] = [];
				}
				// child table, override each row and append new rows if required
				for (let i=0; i < doc[fieldname].length; i++ ) {
					let d = doc[fieldname][i];
					if (local_doc[fieldname][i]) {
						// row exists, just copy the values
						Object.assign(local_doc[fieldname][i], d);
					} else {
						local_doc[fieldname].push(d);
						if (!d.parent) d.parent = doc.name;
						frappe.model.add_to_locals(d);
					}
				}

				// remove extra rows
				if (local_doc[fieldname].length > doc[fieldname].length) {
					local_doc[fieldname].length = doc[fieldname].length;
				}
			} else {
				// literal
				local_doc[fieldname] = doc[fieldname];
			}
		}
	}

});
<commit_msg>[fix] [sync.js] delete extra rows from locals<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

$.extend(frappe.model, {
	docinfo: {},
	sync: function(r) {
		/* docs:
			extract docs, docinfo (attachments, comments, assignments)
			from incoming request and set in `locals` and `frappe.model.docinfo`
		*/
		var isPlain;
		if(!r.docs && !r.docinfo) r = {docs:r};

		isPlain = $.isPlainObject(r.docs);
		if(isPlain) r.docs = [r.docs];

		if(r.docs) {
			var last_parent_name = null;

			for(var i=0, l=r.docs.length; i<l; i++) {
				var d = r.docs[i];

				if (locals[d.doctype] && locals[d.doctype][d.name]) {
					// update values
					frappe.model.update_in_locals(d);
				} else {
					frappe.model.add_to_locals(d);
				}

				d.__last_sync_on = new Date();

				if(d.doctype==="DocType") {
					frappe.meta.sync(d);
				}

				if(d.localname) {
					frappe.model.new_names[d.localname] = d.name;
					$(document).trigger('rename', [d.doctype, d.localname, d.name]);
					delete locals[d.doctype][d.localname];

					// update docinfo to new dict keys
					if(i===0) {
						frappe.model.docinfo[d.doctype][d.name] = frappe.model.docinfo[d.doctype][d.localname];
						frappe.model.docinfo[d.doctype][d.localname] = undefined;
					}
				}
			}

		}

		// set docinfo (comments, assign, attachments)
		if(r.docinfo) {
			if(r.docs) {
				var doc = r.docs[0];
			} else {
				if(cur_frm)
					var doc = cur_frm.doc;
			}
			if(doc) {
				if(!frappe.model.docinfo[doc.doctype])
					frappe.model.docinfo[doc.doctype] = {};
				frappe.model.docinfo[doc.doctype][doc.name] = r.docinfo;
			}
		}

		return r.docs;
	},
	add_to_locals: function(doc) {
		if(!locals[doc.doctype])
			locals[doc.doctype] = {};

		if(!doc.name && doc.__islocal) { // get name (local if required)
			if(!doc.parentfield) frappe.model.clear_doc(doc);

			doc.name = frappe.model.get_new_name(doc.doctype);

			if(!doc.parentfield) frappe.provide("frappe.model.docinfo." + doc.doctype + "." + doc.name);
		}

		locals[doc.doctype][doc.name] = doc;

		// add child docs to locals
		if(!doc.parentfield) {
			for(var i in doc) {
				var value = doc[i];

				if($.isArray(value)) {
					for (var x=0, y=value.length; x < y; x++) {
						var d = value[x];

						if(!d.parent)
							d.parent = doc.name;

						frappe.model.add_to_locals(d);
					}
				}
			}
		}
	},
	update_in_locals: function(doc) {
		// update values in the existing local doc instead of replacing
		let local_doc = locals[doc.doctype][doc.name];
		for (let fieldname in doc) {
			if (local_doc[fieldname] instanceof Array) {
				// table
				if (!(doc[fieldname] instanceof Array)) {
					doc[fieldname] = [];
				}
				// child table, override each row and append new rows if required
				for (let i=0; i < doc[fieldname].length; i++ ) {
					let d = doc[fieldname][i];
					if (local_doc[fieldname][i]) {
						// row exists, just copy the values
						Object.assign(local_doc[fieldname][i], d);
					} else {
						local_doc[fieldname].push(d);
						if (!d.parent) d.parent = doc.name;
						frappe.model.add_to_locals(d);
					}
				}

				// remove extra rows
				if (local_doc[fieldname].length > doc[fieldname].length) {
					for (let i = doc[fieldname].length; i < local_doc[fieldname].length; i++) {

						// clear from local
						let d = local_doc[fieldname][i];
						if (locals[d.doctype] && locals[d.doctype][d.name]) {
							delete locals[d.doctype][d.name];
						}
					}
					local_doc[fieldname].length = doc[fieldname].length;

				}
			} else {
				// literal
				local_doc[fieldname] = doc[fieldname];
			}
		}
	}

});
<|endoftext|>


<commit_before>/*jslint node: true */
/*jshint laxbreak: true */
'use strict';

var d3 = require('d3');
var _ = require('underscore');

var symbolSize = 10,
    gapRegion = 0,
    gapShape = 0,
    dictionary = {
        //molecular processing
        chain:'rectangle',
        transit: 'rectangle',
        init_met: "arrow",
        propep: 'rectangle',
        peptide:'rectangle',
        signal:'rectangle',
        //structural
        helix:'rectangle',
        strand:'rectangle',
        turn:'rectangle',
        //domains & sites
        region:'rectangle',
        coiled: 'rectangle',
        motif:'rectangle',
        repeat:'rectangle',
        ca_bind:'rectangle',
        dna_bind: 'rectangle',
        domain:'rectangle',
        zn_fing: 'rectangle',
        np_bind: 'rectangle',
        metal: "diamond",
        site: "chevron",
        binding: "catFace",
        act_site: "circle",
        //ptms
        mod_res: "triangle",
        lipid: "wave",
        carbohyd: "hexagon",
        disulfid:'bridge',
        crosslnk:'bridge',
        //seqInfo
        compbias:'rectangle',
        conflict:'rectangle',
        non_cons: "doubleBar",
        non_ter: "doubleBar",
        unsure: 'rectangle',
        non_std: "pentagon",
        //mutagenesis
        mutagen:'rectangle',
        //topology
        topo_dom:'rectangle',
        transmem:'rectangle',
        intramem:'rectangle',
        //variants
        var_seq:'variant',
        variant:'variant',
        missense:'variant',//CHECK
        ms_del:'variant',//CHECK
        insdel:'variant',//CHECK
        stop_lost:'variant',//CHECK
        stop_gained:'variant',//CHECK
        init_codon:'variant',//CHECK
        //proteomics
        unique:'rectangle',
        non_unique:'rectangle'
    };

var Feature = function() {
    var feature = this;
    return feature;
};

var FeatureFactory = function() {
    return {
        getFeature: function(type, aaWidth, height, length) {
            var feature,
                featureType = dictionary[type.toLowerCase()],
                width = aaWidth * length;
            //0,0 is in the middle, so we first move to the starting of the aa at gapShape,0.
            gapShape = length === 1 ? 0 : width/length/2;
            //again a gap is needed for regions
            gapRegion = aaWidth/2;
            // if the constructor doesn't exist, rectangle is used by default
            if (typeof Feature[featureType] !== 'function') {
                console.log(type + ' doesn\'t exist');
                featureType = 'rectangle';
            }

            Feature[featureType].prototype = new Feature();
            feature = Feature[featureType](width, height, length);

            return feature;
        },
        isContinuous: function(type) {
            type = type.toLowerCase();
            if ((type === 'disulfid') || (type === 'crosslnk')) {
                return false;
            }
            return true;
        }
    };
}();

Feature.rectangle = function(width, height) {
    return 'M' + -(gapRegion) + ',0'
            + 'L' + (width-gapRegion) + ',0'
            + 'L' + (width-gapRegion) + ',' + height
            + 'L' + -(gapRegion) + ',' + height
            + 'Z';
};

Feature.bridge = function(width, height, length) {
    if (length !== 1) {
        return 'M' + -(gapRegion) + ',' + height
                + 'L' + -(gapRegion) + ',0'
                + 'L' + (width-gapRegion) + ',0'
                + 'L' + (width-gapRegion) + ',' + height
                + 'L' + (width-gapRegion) + ',2'
                + 'L' + -(gapRegion) + ',2Z';
    } else {
        return 'M' + -(gapRegion) + ',' + height
                + 'L' + -(gapRegion) + ',' + (height/2)
                + 'L0,' + (height/2)
                + 'L0,0'
                + 'L0,' + (height/2)
                + 'L' + (width-gapRegion) + ',' + (height/2)
                + 'L' + (width-gapRegion) + ',' + height
                + 'Z';
    }
};

var getMiddleLine = function(centerx, width) {
    return 'M' + (centerx+gapShape) + ',' + centerx
            + 'L' + (width/2+gapShape) + ',' + centerx
            + 'M' + (-centerx+gapShape) + ',' + centerx
            + 'L' + (-width/2+gapShape) + ',' + centerx;
};

Feature.diamond = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
            + 'L' + (centerx+gapShape) + ',' + centerx
            + 'L' + gapShape + ',' + symbolSize
            + 'L' + (-centerx+gapShape) + ',' + centerx;
    return length !== 1
        ? shape + 'L' + gapShape + ',0Z' + getMiddleLine(centerx, width)
        : shape + 'Z';
};

Feature.chevron = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',' + centerx
            + 'L' + (centerx+gapShape) + ',0'
            + 'L' + (centerx+gapShape) +',' + centerx
            + 'L' + gapShape + ',' + symbolSize
            + 'L' + (-centerx+gapShape) + ',' + centerx
            + 'L' + (-centerx+gapShape) + ',0';
    return length !== 1
        ? shape + 'L' + gapShape + ',' + centerx + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.catFace = function(width, height, length) {
    var centerx = symbolSize/2;
    var step = symbolSize/10;
    var shape = 'M' + (-centerx+gapShape) + ',0'
        + 'L' + (-centerx+gapShape) + ',' + (6*step)
        + 'L' + (-2*step+gapShape) + ',' + symbolSize
        + 'L' + (2*step+gapShape) + ',' + symbolSize
        + 'L' + (centerx+gapShape) + ',' + (6*step)
        + 'L' + (centerx+gapShape) + ',0'
        + 'L' + (2*step+gapShape) + ',' + (4*step)
        + 'L' + (-2*step+gapShape) + ',' + (4*step);
    return length !== 1
        ? shape + 'M' + (-centerx+gapShape) + ',0' + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.triangle = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
                + 'L' + (centerx+gapShape) + ',' + symbolSize
                + 'L' + (-centerx+gapShape) + ',' + symbolSize;
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.wave = function(width, height, length) {
    var rx = symbolSize/4;
    var ry = symbolSize/2;
    var shape = 'M' + (-symbolSize/2+gapShape) + ',' + ry
            + "A" + rx + "," + ry + " 0 1,1 " + gapShape + "," + ry
            + "A" + rx + "," + ry + " 0 1,0 " + (symbolSize/2+gapShape) + ',' + ry;
    return length !== 1
        ? shape + getMiddleLine(ry, width) + 'Z'
        : shape + 'Z';
};

var getPolygon = function(N, width, length){
    var r = symbolSize/2;
    var polygon = 'M ';
    for(var i=0; i < N;i++) {
        polygon += (r * Math.cos(2*Math.PI*i/N) + gapShape) + ',' + (r * Math.sin(2*Math.PI*i/N)+r)  + ' ';
    }
    return length !== 1
        ? polygon + ' ' + (r * Math.cos(0) + gapShape) + ',' + (r * Math.sin(0)+r)  + ' ' + getMiddleLine(r, width) + 'Z'
        : polygon + 'Z';
};

Feature.hexagon = function(width, height, length) {
    return getPolygon(6, width, length);
};

Feature.pentagon = function(width, height, length) {
    return getPolygon(5, width, length);
};

Feature.circle = function(width, height, length) {
  var r = Math.sqrt(symbolSize / Math.PI);
  var shape = "M" + gapShape + ",0"
      + "A" + r + "," + r + " 0 1,1 " + gapShape + "," + symbolSize
      + "A" + r + "," + r + " 0 1,1 " + gapShape + ",0";
  return length !== 1
        ? shape + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.arrow = function(width, height, length) {
    var step = symbolSize/10;
    var shape = 'M' + gapShape + ',0'
        + 'L' + (-step+gapShape) + ',0'
        + 'L' + (-5*step+gapShape) + ',' + (4*step)
        + 'L' + (-step+gapShape) + ',' + height
        + 'L' + gapShape + ',' + height
        + 'L' + (4*step+gapShape) + ',' + (4*step);
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.doubleBar = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
        + 'L' + (-centerx+gapShape) + ',' + symbolSize
        + 'L' + gapShape + ',' + symbolSize
        + 'L' + (centerx+gapShape) + ',0';
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.variant = function() {

};

module.exports = FeatureFactory;
<commit_msg>Remove warning about non-existent ft types.<commit_after>/*jslint node: true */
/*jshint laxbreak: true */
'use strict';

var d3 = require('d3');
var _ = require('underscore');

var symbolSize = 10,
    gapRegion = 0,
    gapShape = 0,
    dictionary = {
        //molecular processing
        chain:'rectangle',
        transit: 'rectangle',
        init_met: "arrow",
        propep: 'rectangle',
        peptide:'rectangle',
        signal:'rectangle',
        //structural
        helix:'rectangle',
        strand:'rectangle',
        turn:'rectangle',
        //domains & sites
        region:'rectangle',
        coiled: 'rectangle',
        motif:'rectangle',
        repeat:'rectangle',
        ca_bind:'rectangle',
        dna_bind: 'rectangle',
        domain:'rectangle',
        zn_fing: 'rectangle',
        np_bind: 'rectangle',
        metal: "diamond",
        site: "chevron",
        binding: "catFace",
        act_site: "circle",
        //ptms
        mod_res: "triangle",
        lipid: "wave",
        carbohyd: "hexagon",
        disulfid:'bridge',
        crosslnk:'bridge',
        //seqInfo
        compbias:'rectangle',
        conflict:'rectangle',
        non_cons: "doubleBar",
        non_ter: "doubleBar",
        unsure: 'rectangle',
        non_std: "pentagon",
        //mutagenesis
        mutagen:'rectangle',
        //topology
        topo_dom:'rectangle',
        transmem:'rectangle',
        intramem:'rectangle',
        //variants
        var_seq:'variant',
        variant:'variant',
        missense:'variant',//CHECK
        ms_del:'variant',//CHECK
        insdel:'variant',//CHECK
        stop_lost:'variant',//CHECK
        stop_gained:'variant',//CHECK
        init_codon:'variant',//CHECK
        //proteomics
        unique:'rectangle',
        non_unique:'rectangle'
    };

var Feature = function() {
    var feature = this;
    return feature;
};

var FeatureFactory = function() {
    return {
        getFeature: function(type, aaWidth, height, length) {
            var feature,
                featureType = dictionary[type.toLowerCase()],
                width = aaWidth * length;
            //0,0 is in the middle, so we first move to the starting of the aa at gapShape,0.
            gapShape = length === 1 ? 0 : width/length/2;
            //again a gap is needed for regions
            gapRegion = aaWidth/2;
            // if the constructor doesn't exist, rectangle is used by default
            if (typeof Feature[featureType] !== 'function') {
                featureType = 'rectangle';
            }

            Feature[featureType].prototype = new Feature();
            feature = Feature[featureType](width, height, length);

            return feature;
        },
        isContinuous: function(type) {
            type = type.toLowerCase();
            if ((type === 'disulfid') || (type === 'crosslnk')) {
                return false;
            }
            return true;
        }
    };
}();

Feature.rectangle = function(width, height) {
    return 'M' + -(gapRegion) + ',0'
            + 'L' + (width-gapRegion) + ',0'
            + 'L' + (width-gapRegion) + ',' + height
            + 'L' + -(gapRegion) + ',' + height
            + 'Z';
};

Feature.bridge = function(width, height, length) {
    if (length !== 1) {
        return 'M' + -(gapRegion) + ',' + height
                + 'L' + -(gapRegion) + ',0'
                + 'L' + (width-gapRegion) + ',0'
                + 'L' + (width-gapRegion) + ',' + height
                + 'L' + (width-gapRegion) + ',2'
                + 'L' + -(gapRegion) + ',2Z';
    } else {
        return 'M' + -(gapRegion) + ',' + height
                + 'L' + -(gapRegion) + ',' + (height/2)
                + 'L0,' + (height/2)
                + 'L0,0'
                + 'L0,' + (height/2)
                + 'L' + (width-gapRegion) + ',' + (height/2)
                + 'L' + (width-gapRegion) + ',' + height
                + 'Z';
    }
};

var getMiddleLine = function(centerx, width) {
    return 'M' + (centerx+gapShape) + ',' + centerx
            + 'L' + (width/2+gapShape) + ',' + centerx
            + 'M' + (-centerx+gapShape) + ',' + centerx
            + 'L' + (-width/2+gapShape) + ',' + centerx;
};

Feature.diamond = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
            + 'L' + (centerx+gapShape) + ',' + centerx
            + 'L' + gapShape + ',' + symbolSize
            + 'L' + (-centerx+gapShape) + ',' + centerx;
    return length !== 1
        ? shape + 'L' + gapShape + ',0Z' + getMiddleLine(centerx, width)
        : shape + 'Z';
};

Feature.chevron = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',' + centerx
            + 'L' + (centerx+gapShape) + ',0'
            + 'L' + (centerx+gapShape) +',' + centerx
            + 'L' + gapShape + ',' + symbolSize
            + 'L' + (-centerx+gapShape) + ',' + centerx
            + 'L' + (-centerx+gapShape) + ',0';
    return length !== 1
        ? shape + 'L' + gapShape + ',' + centerx + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.catFace = function(width, height, length) {
    var centerx = symbolSize/2;
    var step = symbolSize/10;
    var shape = 'M' + (-centerx+gapShape) + ',0'
        + 'L' + (-centerx+gapShape) + ',' + (6*step)
        + 'L' + (-2*step+gapShape) + ',' + symbolSize
        + 'L' + (2*step+gapShape) + ',' + symbolSize
        + 'L' + (centerx+gapShape) + ',' + (6*step)
        + 'L' + (centerx+gapShape) + ',0'
        + 'L' + (2*step+gapShape) + ',' + (4*step)
        + 'L' + (-2*step+gapShape) + ',' + (4*step);
    return length !== 1
        ? shape + 'M' + (-centerx+gapShape) + ',0' + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.triangle = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
                + 'L' + (centerx+gapShape) + ',' + symbolSize
                + 'L' + (-centerx+gapShape) + ',' + symbolSize;
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(centerx, width) + 'Z'
        : shape + 'Z';
};

Feature.wave = function(width, height, length) {
    var rx = symbolSize/4;
    var ry = symbolSize/2;
    var shape = 'M' + (-symbolSize/2+gapShape) + ',' + ry
            + "A" + rx + "," + ry + " 0 1,1 " + gapShape + "," + ry
            + "A" + rx + "," + ry + " 0 1,0 " + (symbolSize/2+gapShape) + ',' + ry;
    return length !== 1
        ? shape + getMiddleLine(ry, width) + 'Z'
        : shape + 'Z';
};

var getPolygon = function(N, width, length){
    var r = symbolSize/2;
    var polygon = 'M ';
    for(var i=0; i < N;i++) {
        polygon += (r * Math.cos(2*Math.PI*i/N) + gapShape) + ',' + (r * Math.sin(2*Math.PI*i/N)+r)  + ' ';
    }
    return length !== 1
        ? polygon + ' ' + (r * Math.cos(0) + gapShape) + ',' + (r * Math.sin(0)+r)  + ' ' + getMiddleLine(r, width) + 'Z'
        : polygon + 'Z';
};

Feature.hexagon = function(width, height, length) {
    return getPolygon(6, width, length);
};

Feature.pentagon = function(width, height, length) {
    return getPolygon(5, width, length);
};

Feature.circle = function(width, height, length) {
  var r = Math.sqrt(symbolSize / Math.PI);
  var shape = "M" + gapShape + ",0"
      + "A" + r + "," + r + " 0 1,1 " + gapShape + "," + symbolSize
      + "A" + r + "," + r + " 0 1,1 " + gapShape + ",0";
  return length !== 1
        ? shape + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.arrow = function(width, height, length) {
    var step = symbolSize/10;
    var shape = 'M' + gapShape + ',0'
        + 'L' + (-step+gapShape) + ',0'
        + 'L' + (-5*step+gapShape) + ',' + (4*step)
        + 'L' + (-step+gapShape) + ',' + height
        + 'L' + gapShape + ',' + height
        + 'L' + (4*step+gapShape) + ',' + (4*step);
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.doubleBar = function(width, height, length) {
    var centerx = symbolSize/2;
    var shape = 'M' + gapShape + ',0'
        + 'L' + (-centerx+gapShape) + ',' + symbolSize
        + 'L' + gapShape + ',' + symbolSize
        + 'L' + (centerx+gapShape) + ',0';
    return length !== 1
        ? shape + 'L' + gapShape + ',0' + getMiddleLine(symbolSize/2, width) + 'Z'
        : shape + 'Z';
};

Feature.variant = function() {

};

module.exports = FeatureFactory;
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import './GameController.css'
import DialogueBox from './DialogueBox'
import InfoPanel from './InfoPanel.js'
import Map from './Map.js'
import * as logic from './logic.js'
import * as assets from './assets.js'

class GameController extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      map: [],
      stage: 0,
      player: {
        id: "player",
        name: null,
        x: 0,
        y: 0,
        level: 1,
        XP: 0,
        mhp: 50,
        hp: 50,
        weapon: "Body slam",
        weaponId: "",
        attack: 10
      },
      inDialogue: false,
      dialogue: {
        progress: null,
        character: null,
        text: null
      }
    };

    this.generateNewlevel = this.generateNewlevel.bind(this);
    this.handleUserInput = this.handleUserInput.bind(this);
  }

  componentWillMount() {
    document.addEventListener("keydown", this.handleUserInput);
  }

  componentWillUnmount() {
    document.removeEventListener("keydown", this.handleUserInput);
  }

  componentDidMount() {
    this.generateNewlevel(this.state.stage);
  }

  generateNewlevel(level) {
    let map = [];
    let playerPosition = {};
    let player = JSON.parse(JSON.stringify(this.state.player));

    this.tileSize = 40;
    this.levelWrapperSize = 14;
    this.mapSize = 20;
    this.minRoomSize = 7;
    this.maxRoomSize = 12;
    this.staticMargin = 0;
    this.marginVariability = 3;
    // Number between 0 (inclusive) to 1 (exclusive) that determines the probability of whether or not a room can
    // have more than two unique corridors
    this.corridorAmountBias = 0.3;

    if (level === 0) {
      // Can be tidied up here
      this.mapSize = 15;
      this.minRoomSize = 15;
      this.maxRoomSize = 16;
      this.staticMargin = 1;
      this.marginVariability = 0;
      this.corridorAmountBias = 0;

      logic.generateLevel(map, this.mapSize, this.minRoomSize, this.maxRoomSize, this.staticMargin, this.marginVariability, this.corridorAmountBias);
      // Create the player character and write the coordinates to the player object for state-setting
      playerPosition = logic.placeObject(map, player, player.id, 1, [7, 7]);
      logic.placeObject(map, "item", "101", 1, [1, 1]);
      logic.placeObject(map, "item", "999", 1, [13, 1]);
      logic.placeObject(map, "npc", "9001", 1, [5, 7]);
      logic.placeObject(map, "enemy", "1001", 1, [7, 9]);
      logic.placeObject(map, "exit", "", 1, [1, 13]);
    }
    else {
      logic.generateLevel(map, this.mapSize, this.minRoomSize, this.maxRoomSize, this.staticMargin, this.marginVariability, this.corridorAmountBias);
      // Create the player character and write the coordinates to the player object for state-setting
      playerPosition = logic.placeObject(map, player, player.id);
      // Create healing objcets
      logic.placeObject(map, "item", "101", 10);
      logic.placeObject(map, "item", "999");
      logic.placeObject(map, "exit");
    }

    this.setState({
      map: map,
      player: player
    });
  }

  handleUserInput(event) {
    let map = this.state.map.slice(0);
    let key = event.which || event.keyCode;
    let player = JSON.parse(JSON.stringify(this.state.player));
    let flags = {
      changeLevel: false,
      inDialogue: this.state.inDialogue
    };
    let dialogue = JSON.parse(JSON.stringify(this.state.dialogue));

    logic.handleUserInput(key, map, player, flags, dialogue);

    this.setState({
      inDialogue: flags.inDialogue,
      dialogue: dialogue
    });

    if (flags.changeLevel) {
      let nextStage = this.state.stage + 1;

      this.setState({
        stage: nextStage,
      });

      this.generateNewlevel(nextStage);
    }
    else {
      this.setState({
        map: map,
        player: player
      });
    }
  }

  render() {
    let player = JSON.parse(JSON.stringify(this.state.player));
    let tileSize = this.tileSize;
    let wrapperCenter = this.levelWrapperSize * tileSize / 2;
    let tileOffset = tileSize / 2;
    // These ensure that the player is always in focus and at the middle of the levelWrapper
    let mapOffsetStyles = {
      height: this.mapSize * tileSize,
      width: this.mapSize * tileSize,
      top: wrapperCenter - player.y * tileSize - tileOffset,
      left: wrapperCenter - player.x * tileSize - tileOffset
    }
    // This allows the size of the playing field to be modified by changing this.mapSize and this.tileSize
    let levelWrapperStyles = {
      height: this.levelWrapperSize * tileSize,
      width: this.levelWrapperSize * tileSize
    }

    return (

        <DialogueBox dialogue={this.state.dialogue} />
        <InfoPanel player={player} stage={this.state.stage} />

          <Map map={this.state.map} style={mapOffsetStyles} />

    );
  }
};

export default GameController
<commit_msg>Minor tidying up.<commit_after>import React, {Component} from 'react';
import './GameController.css'
import DialogueBox from './DialogueBox'
import InfoPanel from './InfoPanel.js'
import Map from './Map.js'
import * as logic from './logic.js'
import * as assets from './assets.js'

class GameController extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      map: [],
      stage: 0,
      player: {
        id: "player",
        name: null,
        x: 0,
        y: 0,
        level: 1,
        XP: 0,
        mhp: 50,
        hp: 50,
        weapon: "Body slam",
        weaponId: "",
        attack: 10
      },
      inDialogue: false,
      dialogue: {
        progress: null,
        character: null,
        text: null
      }
    };

    this.generateNewlevel = this.generateNewlevel.bind(this);
    this.handleUserInput = this.handleUserInput.bind(this);
  }

  componentWillMount() {
    document.addEventListener("keydown", this.handleUserInput);
  }

  componentWillUnmount() {
    document.removeEventListener("keydown", this.handleUserInput);
  }

  componentDidMount() {
    this.generateNewlevel(this.state.stage);
  }

  generateNewlevel(level) {
    let map = [];
    let playerPosition = {};
    let player = JSON.parse(JSON.stringify(this.state.player));

    this.tileSize = 40;
    this.levelWrapperSize = 14;
    this.mapSize = 20;
    this.minRoomSize = 7;
    this.maxRoomSize = 12;
    this.staticMargin = 0;
    this.marginVariability = 3;
    // Number between 0 (inclusive) to 1 (exclusive) that determines the probability of whether or not a room can
    // have more than two unique corridors
    this.corridorAmountBias = 0.3;

    if (level === 0) {
      // Can be tidied up here
      this.mapSize = 15;
      this.minRoomSize = 15;
      this.maxRoomSize = 16;
      this.staticMargin = 1;
      this.marginVariability = 0;
      this.corridorAmountBias = 0;

      logic.generateLevel(map, this.mapSize, this.minRoomSize, this.maxRoomSize, this.staticMargin, this.marginVariability, this.corridorAmountBias);
      // Create the player character and write the coordinates to the player object for state-setting
      playerPosition = logic.placeObject(map, player, player.id, 1, [7, 7]);
      logic.placeObject(map, "item", "101", 1, [1, 1]);
      logic.placeObject(map, "item", "999", 1, [13, 1]);
      logic.placeObject(map, "npc", "9001", 1, [5, 7], 3001);
      logic.placeObject(map, "enemy", "1001", 1, [7, 9]);
      logic.placeObject(map, "exit", "", 1, [1, 13]);
    }
    else {
      logic.generateLevel(map, this.mapSize, this.minRoomSize, this.maxRoomSize, this.staticMargin, this.marginVariability, this.corridorAmountBias);
      // Create the player character and write the coordinates to the player object for state-setting
      playerPosition = logic.placeObject(map, player, player.id);
      // Create healing objcets
      logic.placeObject(map, "item", "101", 10);
      logic.placeObject(map, "item", "999");
      logic.placeObject(map, "exit");
    }

    this.setState({
      map: map,
      player: player
    });
  }

  handleUserInput(event) {
    let map = this.state.map.slice(0);
    let key = event.which || event.keyCode;
    let player = JSON.parse(JSON.stringify(this.state.player));
    let flags = {
      changeLevel: false,
      inDialogue: this.state.inDialogue
    };
    let dialogue = JSON.parse(JSON.stringify(this.state.dialogue));

    logic.handleUserInput(key, map, player, flags, dialogue);

    this.setState({
      inDialogue: flags.inDialogue,
      dialogue: dialogue
    });

    if (flags.changeLevel) {
      let nextStage = this.state.stage + 1;

      this.setState({
        stage: nextStage,
      });

      this.generateNewlevel(nextStage);
    }
    else {
      this.setState({
        map: map,
        player: player
      });
    }
  }

  render() {
    let player = JSON.parse(JSON.stringify(this.state.player));
    let tileSize = this.tileSize;
    let wrapperCenter = this.levelWrapperSize * tileSize / 2;
    let tileOffset = tileSize / 2;
    // These ensure that the player is always in focus and at the middle of the levelWrapper
    let mapOffsetStyles = {
      height: this.mapSize * tileSize,
      width: this.mapSize * tileSize,
      top: wrapperCenter - player.y * tileSize - tileOffset,
      left: wrapperCenter - player.x * tileSize - tileOffset
    }
    // This allows the size of the playing field to be modified by changing this.mapSize and this.tileSize
    let levelWrapperStyles = {
      height: this.levelWrapperSize * tileSize,
      width: this.levelWrapperSize * tileSize
    }

    return (

        <DialogueBox dialogue={this.state.dialogue} />
        <InfoPanel player={player} stage={this.state.stage} />

          <Map map={this.state.map} style={mapOffsetStyles} />

    );
  }
};

export default GameController
<|endoftext|>


<commit_before>openerp.web.view_editor = function(openerp) {
var QWeb = openerp.web.qweb;
openerp.web.ViewEditor =   openerp.web.Widget.extend({
    init: function(parent, element_id, dataset, view, options) {
        this._super(parent);
        this.element_id = element_id
        this.parent = parent
        this.dataset = dataset;
        this.model = dataset.model;
        this.xml_id = 0;
    },

    start: function() {
        this.View_editor();
    },

    View_editor : function(){
        var self = this;
        var action = {
            name:'ViewEditor',
            context:this.session.user_context,
            domain: [["model", "=", this.dataset.model]],
            res_model : 'ir.ui.view',
            views : [[false, 'list']],
            type: 'ir.actions.act_window',
            target: "current",
            limit : 80,
            auto_search : true,
            flags: {
                sidebar: false,
                views_switcher: false,
                action_buttons:false,
                search_view:false,
                pager:false,
                radio:true
            },
        };
        var action_manager = new openerp.web.ActionManager(this);
        this.dialog = new openerp.web.Dialog(this,{
            modal: true,
            title: 'ViewEditor',
            width: 750,
            height: 500,
            buttons: {
            "Create": function(){
                //to do
            },
            "Edit": function(){
                self.xml_id = 0 ;
                self.get_data();
            },
            "Close": function(){
                $(this).dialog('destroy');
            }
        },
        });
        this.dialog.start();
        this.dialog.open();
        action_manager.appendTo(this.dialog);
        action_manager.do_action(action);
    },

    check_attr: function(xml, tag, level) {
        var obj = new Object();
        obj.child_id = [];
        obj.id = this.xml_id++;
        obj.level = level+1;
        var render_name = "<" + tag;
        obj.att_list = [];
        obj.att_list.push(tag);
        $(xml).each(function() {
            _.each(this.attributes, function(attrs){
            if (tag != 'button') {
                if (attrs.nodeName == "string" || attrs.nodeName == "name" || attrs.nodeName == "index") {
                render_name += ' ' + attrs.nodeName + '=' + '"' + attrs.nodeValue + '"' ; }
            } else {
                if (attrs.nodeName == "name") {
                render_name += ' ' + attrs.nodeName + '=' + '"' + attrs.nodeValue + '"'; }
            }
            if (attrs.nodeName != "position") {
                obj.att_list.push( [attrs.nodeName,attrs.nodeValue] );
            }

        });

        render_name+= ">";
        });
        obj.name = render_name;
        return obj;
    },

    save_object: function(val, parent_list, child_obj_list) {
        var self = this;
        var check_id = parent_list[0];
        var p_list = parent_list.slice(1);
        if (val.child_id.length != 0) {
            _.each(val.child_id, function(val, key) {
                if (val.id==check_id) {
                    if (p_list.length!=0) {
                        self.save_object(val, p_list, child_obj_list);
                    } else {
                        val.child_id = child_obj_list;
                        return false;
                    }
                }
            });
        } else {
            val.child_id = child_obj_list;
        }
    },

    xml_node_create: function(xml, root, parent_list, parent_id, main_object){
        var self = this;
        var child_obj_list = [];
        var children_list = $(xml).filter(root).children();
        var parents = $(children_list[0]).parents().get();
        _.each(children_list, function (child_node) {
            child_obj_list.push(self.check_attr(child_node,child_node.tagName.toLowerCase(),parents.length));
        });
        if (children_list.length != 0) {
            if (parents.length <= parent_list.length) {
                parent_list.splice(parents.length - 1);
            }
            parent_list.push(parent_id);
            self.save_object(main_object[0], parent_list.slice(1), child_obj_list);
        }
        for (var i=0; i<children_list.length; i++) {
            self.xml_node_create
            (children_list[i], children_list[i].tagName.toLowerCase(),
                parent_list, child_obj_list[i].id, main_object);
        }
        return main_object;
    },

    parse_xml: function(arch, view_id) {
        var self = this;
        var root = $(arch).filter(":first")[0];
        var tag = root.tagName.toLowerCase();
        var obj ={'child_id':[],'id':this.xml_id++,'level':0,'att_list':[],'name':"<view view_id='"+view_id+"'>"};
        var root_object = self.check_attr(root,tag,0);
        obj.child_id = self.xml_node_create(arch, tag, [], this.xml_id-1, [root_object], [])
        return [obj];
    },

    get_data: function() {
        var self = this;
        var view_id =(($("input[name='radiogroup']:checked").parent()).parent()).attr('data-id');
        var ve_dataset = new openerp.web.DataSet(this, 'ir.ui.view');
        ve_dataset.read_ids([parseInt(view_id)], ['arch'], function (arch) {
            one_object = self.parse_xml(arch[0].arch,view_id);
            one_object.arch = arch[0].arch;
            dataset = new openerp.web.DataSetSearch(self, 'ir.ui.view', null, null);
            dataset.read_slice([], {domain : [['inherit_id','=', parseInt(view_id)]]}, function (result) {
                _.each(result, function(res) {
                    self.inherit_view(one_object, res);
                });
                return self.edit_view({"main_object": one_object,
                         "parent_child_id": self.parent_child_list(one_object, [])});
            });
        });
    },
    parent_child_list : function(one_object, p_list) {
        var self = this;
        _.each(one_object , function(element){
            if(element.child_id.length != 0){
                p_list.push({"key":element.id,"value":_.pluck(element.child_id, 'id')});
                self.parent_child_list(element.child_id, p_list);
            }
        });
        return p_list;
    },
    inherit_view : function(one_object, result){
        var self = this;
        var root = $(result.arch).filter('*');
        var xml_list = [];
        if (root[0].tagName.toLowerCase() == "data") {
            xml_list = $(root[0]).children();
        } else {
            xml_list.push(root[0]);
        }
        _.each(xml_list , function(xml){
            var parent_id;
            var check_list = [];
            var xpath_object = self.parse_xml(xml,result.id);
            if (xml.tagName.toLowerCase() == "xpath" ) {
                var part_expr = _.without($(xml).attr('expr').split("/"),"");
                _.each(part_expr,function(part){
                    check_list.push(_.without($.trim(part.replace(/[^a-zA-Z 0-9 _]+/g,'!')).split("!"),""));
                });
            } else {
                    check_list = [_.flatten(xpath_object[0].child_id[0].att_list)];
            }
            self.full_path_search(check_list ,one_object ,xpath_object);
        });
    },
    full_path_search: function(check_list ,val ,xpath_object) {
        var self = this;
        if(xpath_object.length!=0){
            var check = check_list[0];
            var obj;
            switch (check.length) {
                case 2:
                    if(parseInt(check[1])){
                        var list_1 = _.select(val,function(element){
                            var main_list = _.flatten(element.att_list);
                            return _.include(main_list, check[0]);
                        });
                        obj = val[_.indexOf(val,list_1[parseInt(check[1])-1])];
                    } else {
                        obj = _.detect(val, function(element){
                            var main_list = _.flatten(element.att_list);
                            return _.include(main_list, check[0]);
                        });
                    }
                    break;
                case 3:
                    obj = _.detect(val,function(element){
                        var main_list = _.flatten(element.att_list);
                        check = _.uniq(check);
                        var insert = _.intersection(main_list,check);
                        if(insert.length == check.length ){return element;}
                    });
                    break;
                case 1:
                    var list_1 = _.select(val,function(element){
                        var main_list = _.flatten(element.att_list);
                        return _.include(main_list, check[0]);
                    });
                    if(list_1 != 0){
                        (check_list.length == 1)? obj = list_1[0] : check_list.shift();
                    }
                    break;
            }
            if(obj){
                check_list.shift();
                if (check_list.length !=0){
                    self.full_path_search(check_list ,obj.child_id ,xpath_object);
                }else{
                    var level = obj.level+1;
                    self.increase_level(xpath_object[0], level)
                    obj.child_id.push(xpath_object[0]);
                    xpath_object.pop();
                    return;
                }
            }
            else {
                _.each(val,function(element){
                self.full_path_search(check_list ,element.child_id ,xpath_object);
                });
            }
        }
    },
    increase_level: function(val, level) {
        var self = this;
        val.level = level;
        _.each(val.child_id, function(val, key) {
            self.increase_level(val, level + 1);
        });
    },

    edit_view : function(one_object){
        var self = this;
        this.dialog = new openerp.web.Dialog(this,{
            modal: true,
            title: 'Edit Xml',
            width: 750,
            height: 500,
            buttons: {
                "Inherited View": function(){
                    //todo
                },
                "Preview": function(){
                    //todo
                },
                "Close": function(){
                    $(this).dialog('destroy');
                }
            }
        });
        this.dialog.start().open();
        this.dialog.$element.html(QWeb.render('view_editor', {
            'data': one_object['main_object'],
        }));

        $("tr[id^='viewedit-']").click(function() {
            $("tr[id^='viewedit-']").removeClass('ui-selected');
            $(this).addClass('ui-selected');
        });

        $("img[id^='parentimg-']").click(function() {
            if ($(this).attr('src') == '/web/static/src/img/collapse.gif') {
                $(this).attr('src', '/web/static/src/img/expand.gif');
                self.on_expand(this);
            } else {
                $(this).attr('src', '/web/static/src/img/collapse.gif');
                var id = this.id.split('-')[1];
                self.on_collapse(this,one_object['parent_child_id'], one_object['main_object']);
            }
        });
        $("img[id^='side-']").click(function() {
            var side = $(this).closest("tr[id^='viewedit-']")
            var id_tr = (side.attr('id')).split('-')[1];
            var img = side.find("img[id='parentimg-"+id_tr+"']").attr('src'); ;
            var level = side.attr('level');
            var list_shift =[];
            var last_tr;
            var cur_tr = side;
            list_shift.push(side);
            var next_tr;
            switch (this.id) {
                case "side-add":
                    break;
                case "side-remove":
                    break;
                case "side-edit":
                    break;
                case "side-up":
                    while (1) {
                        var prev_tr = cur_tr.prev();
                        if(level >= prev_tr.attr('level') || prev_tr.length == 0) {
                           last_tr = prev_tr;
                           break;
                        }
                        cur_tr = prev_tr;
                    }
                    if (img) {
                        while (1) {
                            next_tr = side.next();
                            if (next_tr.attr('level') <= level || next_tr.length == 0) {
                                break;
                            } else {
                                list_shift.push(next_tr);
                                side = next_tr;
                            }
                        }
                    }
                    if (last_tr.length != 0 && last_tr.attr('level') == level) {
                        _.each(list_shift, function(rec) {
                             $(last_tr).before(rec);
                        });
                    }
                break;
            case "side-down":
                if (img) {
                    while (1) {
                        next_tr = cur_tr.next();
                        if (next_tr.attr('level') <= level || next_tr.length == 0) {
                            last_tr = next_tr;
                            break;
                        } else {
                            list_shift.push(next_tr);
                            cur_tr = next_tr;
                        }
                   }
                }
                else {
                    last_tr = cur_tr.next();
                }
                if (last_tr.length != 0 && last_tr.attr('level') == level) {
                    var last_tr_id = (last_tr.attr('id')).split('-')[1];
                    img = last_tr.find("img[id='parentimg-" + last_tr_id + "']").attr('src');
                    if (img) {
                        $("img[id='parentimg-" + last_tr_id + "']").attr('src', '/web/static/src/img/expand.gif');
                        while (1) {
                            var next_tr = last_tr.next();
                            if (next_tr.attr('level') <= level || next_tr.length == 0) break;
                            next_tr.hide();
                            last_tr = next_tr;
                        }
                    }
                    list_shift.reverse();
                    _.each(list_shift, function(rec) {
                       $(last_tr).after(rec);
                    });
                }
                break;
            }
        });
    },
    on_expand: function(self){
        var level = parseInt($(self).closest("tr[id^='viewedit-']").attr('level'));
        var cur_tr = $(self).closest("tr[id^='viewedit-']");
        while (1) {
            var nxt_tr = cur_tr.next();
            if (parseInt(nxt_tr.attr('level')) > level){
                cur_tr = nxt_tr;
                nxt_tr.hide();
            } else return nxt_tr;
        }
    },
    on_collapse: function(self, parent_child_id, id, main_object) {
        var id = self.id.split('-')[1];
        var datas = _.detect(parent_child_id,function(res) {
            return res.key == id;
        });
        _.each(datas.value, function(rec) {
            var tr = $("tr[id='viewedit-"+rec+"']");
            tr.find("img[id='parentimg-"+rec+"']").attr('src','/web/static/src/img/expand.gif');
            tr.show();
        });
    }
});
};
<commit_msg>[IMP]implement code for save and move functionality in view editor.<commit_after>openerp.web.view_editor = function(openerp) {
var QWeb = openerp.web.qweb;
openerp.web.ViewEditor =   openerp.web.Widget.extend({
    init: function(parent, element_id, dataset, view, options) {
        this._super(parent);
        this.element_id = element_id
        this.parent = parent
        this.dataset = dataset;
        this.model = dataset.model;
        this.xml_id = 0;
    },

    start: function() {
        this.View_editor();
    },

    View_editor : function(){
        var self = this;
        var action = {
            name:'ViewEditor',
            context:this.session.user_context,
            domain: [["model", "=", this.dataset.model]],
            res_model : 'ir.ui.view',
            views : [[false, 'list']],
            type: 'ir.actions.act_window',
            target: "current",
            limit : 80,
            auto_search : true,
            flags: {
                sidebar: false,
                views_switcher: false,
                action_buttons:false,
                search_view:false,
                pager:false,
                radio:true
            },
        };
        var action_manager = new openerp.web.ActionManager(this);
        this.dialog = new openerp.web.Dialog(this,{
            modal: true,
            title: 'ViewEditor',
            width: 750,
            height: 500,
            buttons: {
            "Create": function(){
                //to do
            },
            "Edit": function(){
                self.xml_id = 0 ;
                self.get_data();
            },
            "Close": function(){
                $(this).dialog('destroy');
            }
        },
        });
        this.dialog.start();
        this.dialog.open();
        action_manager.appendTo(this.dialog);
        action_manager.do_action(action);
    },

    check_attr: function(xml, tag, level) {
        var obj = new Object();
        obj.child_id = [];
        obj.id = this.xml_id++;
        obj.level = level+1;
        var render_name = "<" + tag;
        obj.att_list = [];
        obj.att_list.push(tag);
        $(xml).each(function() {
            _.each(this.attributes, function(attrs){
            if (tag != 'button') {
                if (attrs.nodeName == "string" || attrs.nodeName == "name" || attrs.nodeName == "index") {
                render_name += ' ' + attrs.nodeName + '=' + '"' + attrs.nodeValue + '"' ; }
            } else {
                if (attrs.nodeName == "name") {
                render_name += ' ' + attrs.nodeName + '=' + '"' + attrs.nodeValue + '"'; }
            }
            if (attrs.nodeName != "position") {
                obj.att_list.push( [attrs.nodeName,attrs.nodeValue] );
            }

        });

        render_name+= ">";
        });
        obj.name = render_name;
        return obj;
    },

    save_object: function(val, parent_list, child_obj_list) {
        var self = this;
        var check_id = parent_list[0];
        var p_list = parent_list.slice(1);
        if (val.child_id.length != 0) {
            _.each(val.child_id, function(val, key) {
                if (val.id == check_id) {
                    if (p_list.length!=0) {
                        self.save_object(val, p_list, child_obj_list);
                    } else {
                        val.child_id = child_obj_list;
                        return false;
                    }
                }
            });
        } else {
            val.child_id = child_obj_list;
        }
    },

    xml_node_create: function(xml, root, parent_list, parent_id, main_object){
        var self = this;
        var child_obj_list = [];
        var children_list = $(xml).filter(root).children();
        var parents = $(children_list[0]).parents().get();
        _.each(children_list, function (child_node) {
            child_obj_list.push(self.check_attr(child_node,child_node.tagName.toLowerCase(),parents.length));
        });
        if (children_list.length != 0) {
            if (parents.length <= parent_list.length) {
                parent_list.splice(parents.length - 1);
            }
            parent_list.push(parent_id);
            self.save_object(main_object[0], parent_list.slice(1), child_obj_list);
        }
        for (var i=0; i<children_list.length; i++) {
            self.xml_node_create
            (children_list[i], children_list[i].tagName.toLowerCase(),
                parent_list, child_obj_list[i].id, main_object);
        }
        return main_object;
    },

    parse_xml: function(arch, view_id) {
        var self = this;
        var root = $(arch).filter(":first")[0];
        var tag = root.tagName.toLowerCase();
        var obj ={'child_id':[],'id':this.xml_id++,'level':0,'att_list':[],'name':"<view view_id='"+view_id+"'>"};
        var root_object = self.check_attr(root,tag,0);
        obj.child_id = self.xml_node_create(arch, tag, [], this.xml_id-1, [root_object], [])
        return [obj];
    },

    get_data: function() {
        var self = this;
        var view_arch_list = [];
        var view_id =(($("input[name='radiogroup']:checked").parent()).parent()).attr('data-id');
        var ve_dataset = new openerp.web.DataSet(this, 'ir.ui.view');
        ve_dataset.read_ids([parseInt(view_id)], ['arch'], function (arch) {
            one_object = self.parse_xml(arch[0].arch,view_id);
            view_arch_list.push({"view_id" : view_id, "arch" : arch[0].arch});
            dataset = new openerp.web.DataSetSearch(self, 'ir.ui.view', null, null);
            dataset.read_slice([], {domain : [['inherit_id','=', parseInt(view_id)]]}, function (result) {
                _.each(result, function(res) {
                    view_arch_list.push({"view_id":res.id,"arch":res.arch});
                    self.inherit_view(one_object, res);
                });
                return self.edit_view({"main_object": one_object,
                         "parent_child_id": self.parent_child_list(one_object, []),
                         "arch": view_arch_list});
            });
        });
    },
    parent_child_list : function(one_object, p_list) {
        var self = this;
        _.each(one_object , function(element){
            if(element.child_id.length != 0){
                p_list.push({"key":element.id,"value":_.pluck(element.child_id, 'id')});
                self.parent_child_list(element.child_id, p_list);
            }
        });
        return p_list;
    },
    inherit_view : function(one_object, result){
        var self = this;
        var root = $(result.arch).filter('*');
        var xml_list = [];
        if (root[0].tagName.toLowerCase() == "data") {
            xml_list = $(root[0]).children();
        } else {
            xml_list.push(root[0]);
        }
        _.each(xml_list , function(xml){
            var parent_id;
            var check_list = [];
            var xpath_object = self.parse_xml(xml,result.id);
            if (xml.tagName.toLowerCase() == "xpath" ) {
                var part_expr = _.without($(xml).attr('expr').split("/"),"");
                _.each(part_expr,function(part){
                    check_list.push(_.without($.trim(part.replace(/[^a-zA-Z 0-9 _]+/g,'!')).split("!"),""));
                });
            } else {
                    check_list = [_.flatten(xpath_object[0].child_id[0].att_list)];
            }
            self.full_path_search(check_list ,one_object ,xpath_object);
        });
    },
    full_path_search: function(check_list ,val ,xpath_object) {
        var self = this;
        if(xpath_object.length!=0){
            var check = check_list[0];
            var obj;
            switch (check.length) {
                case 2:
                    if(parseInt(check[1])){
                        var list_1 = _.select(val,function(element){
                            var main_list = _.flatten(element.att_list);
                            return _.include(main_list, check[0]);
                        });
                        obj = val[_.indexOf(val,list_1[parseInt(check[1])-1])];
                    } else {
                        obj = _.detect(val, function(element){
                            var main_list = _.flatten(element.att_list);
                            return _.include(main_list, check[0]);
                        });
                    }
                    break;
                case 3:
                    obj = _.detect(val,function(element){
                        var main_list = _.flatten(element.att_list);
                        check = _.uniq(check);
                        var insert = _.intersection(main_list,check);
                        if(insert.length == check.length ){return element;}
                    });
                    break;
                case 1:
                    var list_1 = _.select(val,function(element){
                        var main_list = _.flatten(element.att_list);
                        return _.include(main_list, check[0]);
                    });
                    if(list_1.length != 0){
                        (check_list.length == 1)? obj = list_1[0] : check_list.shift();
                    }
                    break;
            }
            if(obj){
                check_list.shift();
                if (check_list.length !=0){
                    self.full_path_search(check_list ,obj.child_id ,xpath_object);
                }else{
                    var level = obj.level+1;
                    self.increase_level(xpath_object[0], level)
                    obj.child_id.push(xpath_object[0]);
                    xpath_object.pop();
                    return;
                }
            }
            else {
                _.each(val,function(element){
                self.full_path_search(check_list ,element.child_id ,xpath_object);
                });
            }
        }
    },
    increase_level: function(val, level) {
        var self = this;
        val.level = level;
        _.each(val.child_id, function(val, key) {
            self.increase_level(val, level + 1);
        });
    },

    edit_view : function(one_object){
        var self = this;
        this.dialog = new openerp.web.Dialog(this,{
            modal: true,
            title: 'Edit Xml',
            width: 750,
            height: 500,
            buttons: {
                "Inherited View": function(){
                    //todo
                },
                "Preview": function(){
                    //todo
                },
                "Close": function(){
                    $(this).dialog('destroy');
                }
            }
        });
        this.dialog.start().open();
        this.dialog.$element.html(QWeb.render('view_editor', {
            'data': one_object['main_object'],
        }));

        $("tr[id^='viewedit-']").click(function() {
            $("tr[id^='viewedit-']").removeClass('ui-selected');
            $(this).addClass('ui-selected');
        });

        $("img[id^='parentimg-']").click(function() {
            if ($(this).attr('src') == '/web/static/src/img/collapse.gif') {
                $(this).attr('src', '/web/static/src/img/expand.gif');
                self.on_expand(this);
            } else {
                $(this).attr('src', '/web/static/src/img/collapse.gif');
                var id = this.id.split('-')[1];
                self.on_collapse(this,one_object['parent_child_id'], one_object['main_object']);
            }
        });
        $("img[id^='side-']").click(function() {
            var side = $(this).closest("tr[id^='viewedit-']")
            var id_tr = (side.attr('id')).split('-')[1];
            var img = side.find("img[id='parentimg-"+id_tr+"']").attr('src'); ;
            var level = side.attr('level');
            var list_shift =[];
            var last_tr;
            var cur_tr = side;
            list_shift.push(side);
            var next_tr;
            switch (this.id) {
                case "side-add":
                    break;
                case "side-remove":
                    break;
                case "side-edit":
                    break;
                case "side-up":
                    while (1) {
                        var prev_tr = cur_tr.prev();
                        if(level >= prev_tr.attr('level') || prev_tr.length == 0) {
                           last_tr = prev_tr;
                           break;
                        }
                        cur_tr = prev_tr;
                    }
                    if (img) {
                        while (1) {
                            next_tr = side.next();
                            if (next_tr.attr('level') <= level || next_tr.length == 0) {
                                break;
                            } else {
                                list_shift.push(next_tr);
                                side = next_tr;
                            }
                        }
                    }
                    if (last_tr.length != 0 && last_tr.attr('level') == level) {
                        _.each(list_shift, function(rec) {
                             $(last_tr).before(rec);
                        });
                    }
                break;
            case "side-down":
                if (img) {
                    while (1) {
                        next_tr = cur_tr.next();
                        if (next_tr.attr('level') <= level || next_tr.length == 0) {
                            last_tr = next_tr;
                            break;
                        } else {
                            list_shift.push(next_tr);
                            cur_tr = next_tr;
                        }
                   }
                }
                else {
                    last_tr = cur_tr.next();
                }
                if (last_tr.length != 0 && last_tr.attr('level') == level) {
                    var last_tr_id = (last_tr.attr('id')).split('-')[1];
                    img = last_tr.find("img[id='parentimg-" + last_tr_id + "']").attr('src');
                    if (img) {
                        $("img[id='parentimg-" + last_tr_id + "']").attr('src', '/web/static/src/img/expand.gif');
                        while (1) {
                            var next_tr = last_tr.next();
                            if (next_tr.attr('level') <= level || next_tr.length == 0) break;
                            next_tr.hide();
                            last_tr = next_tr;
                        }
                    }
                    list_shift.reverse();
                    _.each(list_shift, function(rec) {
                       $(last_tr).after(rec);
                    });
                }
                var arch1 = one_object["arch"][0].arch;
                root = $(arch1).filter(":first")[0];
                self.get_node(one_object["arch"][0].arch,
                                one_object['main_object'][0].child_id[0],
                                     parseInt(id_tr),
                                        one_object['main_object'][0].child_id[0].chld_id, level, one_object);
                break;
            }
        });
    },
    get_node: function(arch, obj, id, child_list, level, one_object){
        var self = this;
        var children_list =  $(arch).children();
        if(obj.level <= level){
            if(id != obj.id){
                for(var i=0;i< children_list.length; i++){
                    if(obj.child_id){var child_list = obj.child_id};

                self.get_node(children_list[i], obj.child_id[i], id, child_list, level, one_object);
                }
            }else{
                var next = $(arch).next()
                $(next).after(arch);
                var index = _.indexOf(child_list,obj)
                var re_insert_obj = child_list.splice(index,1);
                child_list.splice(index+1, 0, re_insert_obj[0]);
                var p = $(arch).parents();
                one_object["arch"][0].arch = p[p.length-1];
                utfstring = unescape(encodeURIComponent(p));
                return;
            }
        }
    },
    on_expand: function(self){
        var level = parseInt($(self).closest("tr[id^='viewedit-']").attr('level'));
        var cur_tr = $(self).closest("tr[id^='viewedit-']");
        while (1) {
            var nxt_tr = cur_tr.next();
            if (parseInt(nxt_tr.attr('level')) > level){
                cur_tr = nxt_tr;
                nxt_tr.hide();
            } else return nxt_tr;
        }
    },
    on_collapse: function(self, parent_child_id, id, main_object) {
        var id = self.id.split('-')[1];

        var datas = _.detect(parent_child_id,function(res) {
            return res.key == id;
        });
        _.each(datas.value, function(rec) {
            var tr = $("tr[id='viewedit-"+rec+"']");
            tr.find("img[id='parentimg-"+rec+"']").attr('src','/web/static/src/img/expand.gif');
            tr.show();
        });
    }
});
};
<|endoftext|>


<commit_before>/**
 * trim leading zero
 * @author sarkiroka on 2017.04.08.
 */
var leadingZeroRegex = /^0+([^.])/;
module.exports = function (number) {
	var retValue = nember.replace(leadingZeroRegex, '$1');
	return retValue;
};
<commit_msg>fix typo<commit_after>/**
 * trim leading zero
 * @author sarkiroka on 2017.04.08.
 */
var leadingZeroRegex = /^0+([^.])/;
module.exports = function (number) {
	var retValue = number.replace(leadingZeroRegex, '$1');
	return retValue;
};
<|endoftext|>