<commit_before>/* eslint-disable no-case-declarations */
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

import store from '../store';
import { getCookie } from '../../utils/browser_utils';
import * as actionCreators from '../actions';

function scraps(state = [], action) {
  switch (action.type) {
    case 'RECEIVE_SCRAPS':
      return action.scraps;
    case 'RECEIVE_SINGLE_SCRAP':
      const i = state.findIndex(scrap => scrap.id === action.scrap.id);
      return [
        ...state.slice(0, i),
        action.scrap,
        ...state.slice(i+1),
      ];
    case 'REMOVE_SCRAP':
      return state.filter(s => s.id !== action.scrap.id);
    default:
      return state;
  }
}

function scrapEditor(state = [], action) {
  switch (action.type) {
    case 'OPEN_EDITOR':
      return {
        ...state,
        isOpen: true,
        scrap: action.scrap,
        index: action.index,
      };
    case 'CLOSE_EDITOR':
      return {
        ...state,
        isOpen: false,
        scrap: null,
        index: null,
      };
    case 'UPDATE_SCRAP':
      updateScrap(action.scrap);
      return state;
    case 'DELETE_SCRAP':
      deleteScrap(action.scrap);
      return state;
    default:
      return state;
  }
}

// FIXME: Refactor updateScrap and deleteScrap to remove duplication

async function updateScrap(scrap) {
  const response = await fetch(
    `/api/scraps/${scrap.id}/`,
    {
      method: 'put',
      credentials: 'include',
      body: JSON.stringify(scrap),
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken'),
      },
    },
  );
  const newScrap = await response.json();
  store.dispatch(actionCreators.receiveSingleScrap(newScrap));
}

async function deleteScrap(scrap) {
  const response = await fetch(
    `/api/scraps/${scrap.id}/`,
    {
      method: 'delete',
      credentials: 'include',
      body: JSON.stringify(scrap),
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken'),
      },
    },
  );
  if (response.ok) {
    store.dispatch(actionCreators.removeScrap(scrap));
  }
}

const rootReducer = combineReducers({
  scrapEditor,
  scraps,
  routing: routerReducer,
});

export default rootReducer;
<commit_msg>Refactor fetch API calls to remove duplication<commit_after>/* eslint-disable no-case-declarations */
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

import store from '../store';
import { getCookie } from '../../utils/browser_utils';
import * as actionCreators from '../actions';

function scraps(state = [], action) {
  switch (action.type) {
    case 'RECEIVE_SCRAPS':
      return action.scraps;
    case 'RECEIVE_SINGLE_SCRAP':
      const i = state.findIndex(scrap => scrap.id === action.scrap.id);
      return [
        ...state.slice(0, i),
        action.scrap,
        ...state.slice(i+1),
      ];
    case 'REMOVE_SCRAP':
      return state.filter(s => s.id !== action.scrap.id);
    default:
      return state;
  }
}

function scrapEditor(state = [], action) {
  switch (action.type) {
    case 'OPEN_EDITOR':
      return {
        ...state,
        isOpen: true,
        scrap: action.scrap,
        index: action.index,
      };
    case 'CLOSE_EDITOR':
      return {
        ...state,
        isOpen: false,
        scrap: null,
        index: null,
      };
    case 'UPDATE_SCRAP':
      updateScrap(action.scrap);
      return state;
    case 'DELETE_SCRAP':
      deleteScrap(action.scrap);
      return state;
    default:
      return state;
  }
}

async function fetchScrapDetail(method, scrap, ) {
  const response = await fetch(
    `/api/scraps/${scrap.id}/`,
    {
      method: method,
      credentials: 'include',
      body: JSON.stringify(scrap),
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken'),
      },
    },
  );
  return response;
}

async function updateScrap(scrap) {
  const response = await fetchScrapDetail('put', scrap)
  const newScrap = await response.json();
  store.dispatch(actionCreators.receiveSingleScrap(newScrap));
}

async function deleteScrap(scrap) {
  const response = await fetchScrapDetail('delete', scrap);
  if (response.ok) {
    store.dispatch(actionCreators.removeScrap(scrap));
  }
}

const rootReducer = combineReducers({
  scrapEditor,
  scraps,
  routing: routerReducer,
});

export default rootReducer;
<|endoftext|>


<commit_before>define(function (require) {
  var d3 = require("d3");

  return function split() {
    var splitBy = function (d) { return d; };
    var element = "div";
    var elementClass = function () { return "horizontal"; };
    var predicate = false;

    function layout(selection) {
      selection.each(function (data) {
        var elem = d3.select(this).data([data]);

        var elems = elem.selectAll("splits")
          .data(splitBy)
          .enter().append(element)
          .attr("class",  elementClass);

        if (predicate) {
          elems.call(split);
        }
      });
    }

    layout.splitBy = function (_) {
      if (!arguments.length) { return splitBy; }
      splitBy = _;
      return layout;
    };

    layout.element = function (_) {
      if (!arguments.length) { return element; }
      element = _;
      return layout;
    };

    layout.elementClass = function (_) {
      if (!arguments.length) { return elementClass; }
      elementClass = _;
      return layout;
    };

    layout.predicate = function (_) {
      if (!arguments.length) { return predicate; }
      predicate = _;
      return layout;
    };

    return layout;
  };
});<commit_msg>removing split.js from layouts<commit_after><|endoftext|>


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

// for license information please see license.txt

frappe.provide("frappe.form.formatters");

frappe.form.formatters = {
	_right: function(value, options) {
		if(options && options.inline) {
			return value;
		} else {
			return "
" + value + "
";
		}
	},
	Data: function(value) {
		return value==null ? "" : value;
	},
	Select: function(value) {
		return __(frappe.form.formatters["Data"](value));
	},
	Float: function(value, docfield, options, doc) {
		// don't allow 0 precision for Floats, hence or'ing with null
		var precision = docfield.precision || cint(frappe.boot.sysdefaults.float_precision) || null;
		if (docfield.options && docfield.options.trim()) {
			// options points to a currency field, but expects precision of float!
			docfield.precision = precision;
			return frappe.form.formatters.Currency(value, docfield, options, doc);

		} else {
			// show 1.000000 as 1
			if (!(options || {}).always_show_decimals && !is_null(value)) {
				var temp = cstr(value).split(".");
				if (temp[1]==undefined || cint(temp[1])===0) {
					precision = 0;
				}
			}

			return frappe.form.formatters._right(
				((value==null || value==="")
					? ""
					: format_number(value, null, precision)), options);
		}
	},
	Int: function(value, docfield, options) {
		return frappe.form.formatters._right(value==null ? "" : cint(value), options)
	},
	Percent: function(value, docfield, options) {
		return frappe.form.formatters._right(flt(value, 2) + "%", options)
	},
	Currency: function(value, docfield, options, doc) {
		var currency = frappe.meta.get_field_currency(docfield, doc);
		return frappe.form.formatters._right((value==null || value==="")
			? "" : format_currency(value, currency, docfield.precision || null), options);
	},
	Check: function(value) {
		if(value) {
			return '';
		} else {
			return '';
		}
	},
	Link: function(value, docfield, options) {
		var doctype = docfield._options || docfield.options;
		if(value && value.match(/^['"].*['"]$/)) {
			return value.replace(/^.(.*).$/, "$1");
		}
		if(options && options.for_print) {
			return value;
		}
		if(!value) {
			return "";
		}
		if(docfield && docfield.link_onclick) {
			return repl('%(value)s',
				{onclick: docfield.link_onclick.replace(/"/g, '"'), value:value});
		} else if(docfield && doctype) {
			return repl('%(label)s', {
				doctype: encodeURIComponent(doctype),
				name: encodeURIComponent(value),
				label: __(options && options.label || value)
			});
		} else {
			return value;
		}
	},
	Date: function(value) {
		if (value) {
			value = dateutil.str_to_user(value);
			// handle invalid date
			if (value==="Invalid date") {
				value = null;
			}
		}

		return value || "";
	},
	Datetime: function(value) {
		return value ? dateutil.str_to_user(dateutil.convert_to_user_tz(value)) : "";
	},
	Text: function(value) {
		if(value) {
			var tags = ["<p", "<div", "<br", "<table"];
			var match = false;

			for(var i=0; i<tags.length; i++) {
				if(value.match(tags[i])) {
					match = true;
					break;
				}
			}

			if(!match) {
				value = replace_newlines(value);
			}
		}

		return frappe.form.formatters.Data(value);
	},
	LikedBy: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= '';
		});
		return html;
	},
	Tag: function(value) {
		var html = "";
		$.each((value || "").split(","), function(i, v) {
			if(v) html+= ''+v +'';
		});
		return html;
	},
	Comment: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v.comment+'';
		});
		return html;
	},
	Assign: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v+'';
		});
		return html;
	},
	SmallText: function(value) {
		return frappe.form.formatters.Text(value);
	},
	TextEditor: function(value) {
		return frappe.form.formatters.Text(value);
	},
	Code: function(value) {
		return "
" + (value==null ? "" : $("
").text(value).html()) + "
"
	},
	WorkflowState: function(value) {
		workflow_state = frappe.get_doc("Workflow State", value);
		if(workflow_state) {
			return repl("\
				 %(value)s", {
					value: value,
					style: workflow_state.style.toLowerCase(),
					icon: workflow_state.icon
				});
		} else {
			return "" + value + "";
		}
	},
	Email: function(value) {
		return $("

").text(value).html();
	}
}

frappe.form.get_formatter = function(fieldtype) {
	if(!fieldtype)
		fieldtype = "Data";
	return frappe.form.formatters[fieldtype.replace(/ /g, "")] || frappe.form.formatters.Data;
}

frappe.format = function(value, df, options, doc) {
	if(!df) df = {"fieldtype":"Data"};
	var fieldtype = df.fieldtype || "Data";

	// format Dynamic Link as a Link
	if(fieldtype==="Dynamic Link") {
		fieldtype = "Link";
		df._options = doc ? doc[df.options] : null;
	}

	formatter = df.formatter || frappe.form.get_formatter(fieldtype);

	var formatted = formatter(value, df, options, doc);

	if (typeof formatted == "string")
		formatted = frappe.dom.remove_script_and_style(formatted);

	return formatted;
}

frappe.get_format_helper = function(doc) {
	var helper = {
		get_formatted: function(fieldname) {
			var df = frappe.meta.get_docfield(doc.doctype, fieldname);
			if(!df) { console.log("fieldname not found: " + fieldname); };
			return frappe.format(doc[fieldname], df, {inline:1}, doc);
		}
	};
	$.extend(helper, doc);
	return helper;
}
<commit_msg>[fix] show unchecked checkboxes using icon-ban-circle instead of empty box<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

frappe.provide("frappe.form.formatters");

frappe.form.formatters = {
	_right: function(value, options) {
		if(options && options.inline) {
			return value;
		} else {
			return "
" + value + "
";
		}
	},
	Data: function(value) {
		return value==null ? "" : value;
	},
	Select: function(value) {
		return __(frappe.form.formatters["Data"](value));
	},
	Float: function(value, docfield, options, doc) {
		// don't allow 0 precision for Floats, hence or'ing with null
		var precision = docfield.precision || cint(frappe.boot.sysdefaults.float_precision) || null;
		if (docfield.options && docfield.options.trim()) {
			// options points to a currency field, but expects precision of float!
			docfield.precision = precision;
			return frappe.form.formatters.Currency(value, docfield, options, doc);

		} else {
			// show 1.000000 as 1
			if (!(options || {}).always_show_decimals && !is_null(value)) {
				var temp = cstr(value).split(".");
				if (temp[1]==undefined || cint(temp[1])===0) {
					precision = 0;
				}
			}

			return frappe.form.formatters._right(
				((value==null || value==="")
					? ""
					: format_number(value, null, precision)), options);
		}
	},
	Int: function(value, docfield, options) {
		return frappe.form.formatters._right(value==null ? "" : cint(value), options)
	},
	Percent: function(value, docfield, options) {
		return frappe.form.formatters._right(flt(value, 2) + "%", options)
	},
	Currency: function(value, docfield, options, doc) {
		var currency = frappe.meta.get_field_currency(docfield, doc);
		return frappe.form.formatters._right((value==null || value==="")
			? "" : format_currency(value, currency, docfield.precision || null), options);
	},
	Check: function(value) {
		if(value) {
			return '';
		} else {
			return '';
		}
	},
	Link: function(value, docfield, options) {
		var doctype = docfield._options || docfield.options;
		if(value && value.match(/^['"].*['"]$/)) {
			return value.replace(/^.(.*).$/, "$1");
		}
		if(options && options.for_print) {
			return value;
		}
		if(!value) {
			return "";
		}
		if(docfield && docfield.link_onclick) {
			return repl('%(value)s',
				{onclick: docfield.link_onclick.replace(/"/g, '"'), value:value});
		} else if(docfield && doctype) {
			return repl('%(label)s', {
				doctype: encodeURIComponent(doctype),
				name: encodeURIComponent(value),
				label: __(options && options.label || value)
			});
		} else {
			return value;
		}
	},
	Date: function(value) {
		if (value) {
			value = dateutil.str_to_user(value);
			// handle invalid date
			if (value==="Invalid date") {
				value = null;
			}
		}

		return value || "";
	},
	Datetime: function(value) {
		return value ? dateutil.str_to_user(dateutil.convert_to_user_tz(value)) : "";
	},
	Text: function(value) {
		if(value) {
			var tags = ["<p", "<div", "<br", "<table"];
			var match = false;

			for(var i=0; i<tags.length; i++) {
				if(value.match(tags[i])) {
					match = true;
					break;
				}
			}

			if(!match) {
				value = replace_newlines(value);
			}
		}

		return frappe.form.formatters.Data(value);
	},
	LikedBy: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= '';
		});
		return html;
	},
	Tag: function(value) {
		var html = "";
		$.each((value || "").split(","), function(i, v) {
			if(v) html+= ''+v +'';
		});
		return html;
	},
	Comment: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v.comment+'';
		});
		return html;
	},
	Assign: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v+'';
		});
		return html;
	},
	SmallText: function(value) {
		return frappe.form.formatters.Text(value);
	},
	TextEditor: function(value) {
		return frappe.form.formatters.Text(value);
	},
	Code: function(value) {
		return "
" + (value==null ? "" : $("
").text(value).html()) + "
"
	},
	WorkflowState: function(value) {
		workflow_state = frappe.get_doc("Workflow State", value);
		if(workflow_state) {
			return repl("\
				 %(value)s", {
					value: value,
					style: workflow_state.style.toLowerCase(),
					icon: workflow_state.icon
				});
		} else {
			return "" + value + "";
		}
	},
	Email: function(value) {
		return $("

").text(value).html();
	}
}

frappe.form.get_formatter = function(fieldtype) {
	if(!fieldtype)
		fieldtype = "Data";
	return frappe.form.formatters[fieldtype.replace(/ /g, "")] || frappe.form.formatters.Data;
}

frappe.format = function(value, df, options, doc) {
	if(!df) df = {"fieldtype":"Data"};
	var fieldtype = df.fieldtype || "Data";

	// format Dynamic Link as a Link
	if(fieldtype==="Dynamic Link") {
		fieldtype = "Link";
		df._options = doc ? doc[df.options] : null;
	}

	formatter = df.formatter || frappe.form.get_formatter(fieldtype);

	var formatted = formatter(value, df, options, doc);

	if (typeof formatted == "string")
		formatted = frappe.dom.remove_script_and_style(formatted);

	return formatted;
}

frappe.get_format_helper = function(doc) {
	var helper = {
		get_formatted: function(fieldname) {
			var df = frappe.meta.get_docfield(doc.doctype, fieldname);
			if(!df) { console.log("fieldname not found: " + fieldname); };
			return frappe.format(doc[fieldname], df, {inline:1}, doc);
		}
	};
	$.extend(helper, doc);
	return helper;
}
<|endoftext|>


<commit_before>
import './js-yaml';

export function parseTxt() {
  var info = localStorage.getItem(document.domain);
  var cacheDuration;
  var amount;
  var unit;
  var version;
  var diff;
  var newArray = [];
  var ms;
  var currentPrefix;

  var shouldRenew = false;
  if (info != null) {
    var tried = info;
    try {
      tried = JSON.parse(info);
    } catch (e) {

    }
    if (tried.tipsyTried) {
      diff = Date.now() - Number(tried.tipsyTried);
      if (diff > 2 * 3600000 ) {
        shouldRenew = true;
      } else {
        newArray[0] = {};
        return newArray;
      }

    }
    version = info.split("\n")[1];

    if (version == "0.0.1") {
      cacheDuration = info.split("\n")[2];
      cacheDuration = cacheDuration.split(" ");

      amount = cacheDuration[0];
      unit = cacheDuration[1];

      diff = Date.now() - Number(info.split("\n")[0]);

      if (unit == 'h') {
        ms = 3600000;
      } else if (unit == 'd') {
        ms = 86400000;
      } else if (unit == 'w') {
        ms = 604800000;
      }

      if (diff > ms * Number(amount)) {
        shouldRenew = true;
      }

    } else  {
      var j = JSON.parse(info);
      var pervTime = Number(j.prevTime);

      if (info['cache-duration']) {
        amount = info['cache-duration'].amount;
        unit = info['cache-duration'].unit;

        diff = Date.now() - Number(prevTime);

        if (unit == 'hour' || unit == "hours") {
          ms = 3600000;
        } else if (unit == 'days' || unit == "days") {
          ms = 86400000;
        } else if (unit == 'week' || unit == 'weeks') {
          ms = 604800000;
        }

        if (diff > ms * Number(amount)) {
          shouldRenew = true;
        }
      }
    }
  }

  if (info == null || shouldRenew) {
    var req = new XMLHttpRequest();
    try {
      req.open('GET', "/tipsy.txt", false);
    } catch (e) {

    }
    try {
      req.send(null);
    } catch(e) {
      localStorage.setItem(document.domain, JSON.stringify({'tipsyTried': Date.now()}));
    }
    if (req.status == 200) {
      version = req.responseText.split("\n")[0];

      if (version == "0.0.1") {

        info = Date.now().toString() + "\n" + req.responseText;
        localStorage.setItem(document.domain, info);
      } else {
        info = req.responseText;

        try {
          info = jsyaml.load(info);
        } catch (e) {}
        info.prevTime = Date.now().toString();
        localStorage.setItem(document.domain, JSON.stringify(info));
      }
    } else {
      localStorage.setItem(document.domain, JSON.stringify({'tipsyTried': Date.now()}));
    }
  } else {
    info = localStorage.getItem(document.domain);
  }

  if (info != null) {

    var str = info;
    if (typeof info != "string") {
      str = JSON.stringify(info);
    }

    version = str.split("\n")[1];

    if (version == "0.0.1") {

      var splitted = info.split("\n");

      var tipsyInfo = splitted.slice(3,splitted.length);
      for (var i =  0; i < tipsyInfo.length; i++) {
        if (tipsyInfo[i].length > 1) {
          var entry = tipsyInfo[i].split(" ");
          var urlPrefix = entry[0];
          var paymentInfos = entry[1];
          var author = entry[2];

          currentPrefix = document.documentURI.substring(document.documentURI.indexOf(document.domain) + document.domain.length + 1, document.documentURI.length);

          if (currentPrefix === " " || currentPrefix === "") {
            currentPrefix = "*";
          }
          if ((currentPrefix == urlPrefix) || (urlPrefix ==="*")) {
            if (!newArray[0]) {
              newArray[0] = {};
            }

            var splittedProcessors = paymentInfos.split("|");
            for (var k = 0; k < splittedProcessors.length; k++) {
              var splitEntry = splittedProcessors[k].split("=");
              switch(splitEntry[0]){
                case "paypal":
                  newArray[0].paypal = splitEntry[1];
                  break;
                case "dwolla":
                  newArray[0].dwolla = splitEntry[1];
              }
            }

            if (author && author.length > 1) {
              newArray[0].name = author;
            }
          }
        }
      }

    return newArray;
    } else {

      if (typeof info == "string") {
        info = JSON.parse(info);
      }

      currentPrefix = document.documentURI.substring(document.documentURI.indexOf(document.domain) + document.domain.length + 1, document.documentURI.length);

      var paymentMethods = info['payment-methods'];
      for (var urlPref in paymentMethods ) {
        if (currentPrefix === " " || currentPrefix === "") {
          currentPrefix = "_";
        }

        if ((currentPrefix == urlPref) || (urlPref === "_")) {
          if (!newArray[0]) {
            newArray[0] = {};
          }
          if (paymentMethods[urlPref]) {
            newArray[0].dwolla = paymentMethods[urlPref].dwolla;
          }
          if (paymentMethods[urlPref]) {
            newArray[0].paypal = paymentMethods[urlPref].paypal;
          }
          if (info.author) {
            newArray[0].name = info.author;
          }
        }
      }
      return newArray;
    }
  }
}
<commit_msg>Fix the err msg in https://github.com/haystack/tipsy/issues/87<commit_after>
import './js-yaml';

export function parseTxt() {
  var info = localStorage.getItem(document.domain);
  var cacheDuration;
  var amount;
  var unit;
  var version;
  var diff;
  var newArray = [];
  var ms;
  var currentPrefix;

  var shouldRenew = false;
  if (info != null) {
    var tried = info;
    try {
      tried = JSON.parse(info);
    } catch (e) {

    }
    if (tried.tipsyTried) {
      diff = Date.now() - Number(tried.tipsyTried);
      if (diff > 2 * 3600000 ) {
        shouldRenew = true;
      } else {
        newArray[0] = {};
        return newArray;
      }

    }
    version = info.split("\n")[1];

    if (version == "0.0.1") {
      cacheDuration = info.split("\n")[2];
      cacheDuration = cacheDuration.split(" ");

      amount = cacheDuration[0];
      unit = cacheDuration[1];

      diff = Date.now() - Number(info.split("\n")[0]);

      if (unit == 'h') {
        ms = 3600000;
      } else if (unit == 'd') {
        ms = 86400000;
      } else if (unit == 'w') {
        ms = 604800000;
      }

      if (diff > ms * Number(amount)) {
        shouldRenew = true;
      }

    } else  {
      var j = JSON.parse(info);
      var pervTime = Number(j.prevTime);

      if (info['cache-duration']) {
        amount = info['cache-duration'].amount;
        unit = info['cache-duration'].unit;

        diff = Date.now() - Number(prevTime);

        if (unit == 'hour' || unit == "hours") {
          ms = 3600000;
        } else if (unit == 'days' || unit == "days") {
          ms = 86400000;
        } else if (unit == 'week' || unit == 'weeks') {
          ms = 604800000;
        }

        if (diff > ms * Number(amount)) {
          shouldRenew = true;
        }
      }
    }
  }

  if (info == null || shouldRenew) {
    var req = new XMLHttpRequest();
    try {
      req.open('GET', "/tipsy.txt", false);
    } catch (e) {

    }
    try {
      req.send(null);
    } catch(e) {
      localStorage.setItem(document.domain, JSON.stringify({'tipsyTried': Date.now()}));
    }
    if (req.status == 200) {
      version = req.responseText.split("\n")[0];

      if (version == "0.0.1") {

        info = Date.now().toString() + "\n" + req.responseText;
        localStorage.setItem(document.domain, info);
      } else {
        info = req.responseText;

        try {
          info = jsyaml.load(info);
        } catch (e) {}
        var serialInfo = JSON.parse(JSON.stringify(info)); // copy object or non-object without jquery
        serialInfo.prevTime = Date.now().toString();
        localStorage.setItem(document.domain, JSON.stringify(serialInfo));
      }
    } else {
      localStorage.setItem(document.domain, JSON.stringify({'tipsyTried': Date.now()}));
    }
  } else {
    info = localStorage.getItem(document.domain);
  }

  if (info != null) {

    var str = info;
    if (typeof info != "string") {
      str = JSON.stringify(info);
    }

    version = str.split("\n")[1];

    if (version == "0.0.1") {

      var splitted = info.split("\n");

      var tipsyInfo = splitted.slice(3,splitted.length);
      for (var i =  0; i < tipsyInfo.length; i++) {
        if (tipsyInfo[i].length > 1) {
          var entry = tipsyInfo[i].split(" ");
          var urlPrefix = entry[0];
          var paymentInfos = entry[1];
          var author = entry[2];

          currentPrefix = document.documentURI.substring(document.documentURI.indexOf(document.domain) + document.domain.length + 1, document.documentURI.length);

          if (currentPrefix === " " || currentPrefix === "") {
            currentPrefix = "*";
          }
          if ((currentPrefix == urlPrefix) || (urlPrefix ==="*")) {
            if (!newArray[0]) {
              newArray[0] = {};
            }

            var splittedProcessors = paymentInfos.split("|");
            for (var k = 0; k < splittedProcessors.length; k++) {
              var splitEntry = splittedProcessors[k].split("=");
              switch(splitEntry[0]){
                case "paypal":
                  newArray[0].paypal = splitEntry[1];
                  break;
                case "dwolla":
                  newArray[0].dwolla = splitEntry[1];
              }
            }

            if (author && author.length > 1) {
              newArray[0].name = author;
            }
          }
        }
      }

    return newArray;
    } else {

      if (typeof info == "string") {
        info = JSON.parse(info);
      }

      currentPrefix = document.documentURI.substring(document.documentURI.indexOf(document.domain) + document.domain.length + 1, document.documentURI.length);

      var paymentMethods = info['payment-methods'];
      for (var urlPref in paymentMethods ) {
        if (currentPrefix === " " || currentPrefix === "") {
          currentPrefix = "_";
        }

        if ((currentPrefix == urlPref) || (urlPref === "_")) {
          if (!newArray[0]) {
            newArray[0] = {};
          }
          if (paymentMethods[urlPref]) {
            newArray[0].dwolla = paymentMethods[urlPref].dwolla;
          }
          if (paymentMethods[urlPref]) {
            newArray[0].paypal = paymentMethods[urlPref].paypal;
          }
          if (info.author) {
            newArray[0].name = info.author;
          }
        }
      }
      return newArray;
    }
  }
}
<|endoftext|>


<commit_before>/*global window, nodeca, jQuery, Handlebars, Backbone, $, _*/

"use strict";

function start_download(id, url) {
  if ($('iframe#' + id).length) {
    // duplicate
    return;
  }

  $('').attr({id: id, src: url}).css('display', 'none')
    .appendTo(window.document.body);
}

module.exports = Backbone.View.extend({
  // Use existing DOM element instead of generating a new one.
  el: '#result',

  // Deleagate some event handlers for some child elements.
  events: {
    'click #result-download': 'onDownload'
  },

  /**
    *  new ui.wizard.result.pane()
    *
    *  View constructor.
    */
  initialize: function () {
    this.$glyphs = this.$('#result-font');

    this.model.glyphs.on('add', this.addGlyph, this);
  },

  /**
    *  ui.wizard.result.pane#addGlyph(glyph) -> Void
    *
    *  Creates corresponding view for given glyph.
    *
    *  ##### See Also:
    *
    *  - [[ui.wizard.result.glyph]]
    */
  addGlyph: function (glyph) {
    var view = new nodeca.client.fontomas.ui.wizard.result.glyph({model: glyph});
    this.$glyphs.append(view.el);
  },

  /**
    *  ui.wizard.result.pane#onDownload(event) -> Void
    *
    *  Download button click handler
    */
  onDownload: function (event) {
    event.preventDefault();
    nodeca.server.fontomas.font.generate(this.model.getFontConfig(), function (err, msg) {
      var font_id = msg.data.id;

      if (err) {
        // TODO: notification about error
        nodeca.logger.error(err);
        return;
      }

      function poll_status() {
        nodeca.server.fontomas.font.status({id: font_id}, function (err, msg) {
          if (err) {
            // TODO: notification about error
            nodeca.logger.error(err);
            return;
          }

          if ('error' === msg.data.status) {
            // TODO: notification about error
            nodeca.logger.error(msg.data.error || "Unexpected error.");
            return;
          }

          if ('finished' === msg.data.status) {
            // TODO: normal notification about success
            nodeca.logger.info("Font successfully generated. " +
                               "Your download link: " + msg.data.url);
            start_download(font_id, msg.data.url);
            return;
          }

          if ('enqueued' === msg.data.status) {
            // TODO: notification about queue
            if (-1 === msg.data.position) {
              nodeca.logger.info("Your request is in progress nd will be available soon.");
            } else {
              nodeca.logger.info("Your request is in queue. " +
                                "Your turn number is " + msg.data.position);
            }

            // try in next 5 seconds
            setTimeout(poll_status, 5000);
            return;
          }

          // Unexpected behavior
          nodeca.logger.error("Unexpected behavior");
        });
      }

      poll_status();
    });
  }
});
<commit_msg>Fix download link<commit_after>/*global window, nodeca, jQuery, Handlebars, Backbone, $, _*/

"use strict";

function start_download(id, url) {
  $('iframe#' + id).remove();
  $('').attr({id: id, src: url}).css('display', 'none')
    .appendTo(window.document.body);
}

module.exports = Backbone.View.extend({
  // Use existing DOM element instead of generating a new one.
  el: '#result',

  // Deleagate some event handlers for some child elements.
  events: {
    'click #result-download': 'onDownload'
  },

  /**
    *  new ui.wizard.result.pane()
    *
    *  View constructor.
    */
  initialize: function () {
    this.$glyphs = this.$('#result-font');

    this.model.glyphs.on('add', this.addGlyph, this);
  },

  /**
    *  ui.wizard.result.pane#addGlyph(glyph) -> Void
    *
    *  Creates corresponding view for given glyph.
    *
    *  ##### See Also:
    *
    *  - [[ui.wizard.result.glyph]]
    */
  addGlyph: function (glyph) {
    var view = new nodeca.client.fontomas.ui.wizard.result.glyph({model: glyph});
    this.$glyphs.append(view.el);
  },

  /**
    *  ui.wizard.result.pane#onDownload(event) -> Void
    *
    *  Download button click handler
    */
  onDownload: function (event) {
    event.preventDefault();
    nodeca.server.fontomas.font.generate(this.model.getFontConfig(), function (err, msg) {
      var font_id = msg.data.id;

      if (err) {
        // TODO: notification about error
        nodeca.logger.error(err);
        return;
      }

      function poll_status() {
        nodeca.server.fontomas.font.status({id: font_id}, function (err, msg) {
          if (err) {
            // TODO: notification about error
            nodeca.logger.error(err);
            return;
          }

          if ('error' === msg.data.status) {
            // TODO: notification about error
            nodeca.logger.error(msg.data.error || "Unexpected error.");
            return;
          }

          if ('finished' === msg.data.status) {
            // TODO: normal notification about success
            nodeca.logger.info("Font successfully generated. " +
                               "Your download link: " + msg.data.url);
            start_download(font_id, msg.data.url);
            return;
          }

          if ('enqueued' === msg.data.status) {
            // TODO: notification about queue
            if (-1 === msg.data.position) {
              nodeca.logger.info("Your request is in progress nd will be available soon.");
            } else {
              nodeca.logger.info("Your request is in queue. " +
                                "Your turn number is " + msg.data.position);
            }

            // try in next 5 seconds
            setTimeout(poll_status, 5000);
            return;
          }

          // Unexpected behavior
          nodeca.logger.error("Unexpected behavior");
        });
      }

      poll_status();
    });
  }
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs');
var mv = require('mv');
var zlib = require('zlib');
var path = require('path');

// Use whichever version of the local request helper is available
// This might be the JavaScript or CoffeeScript version depending
// on whether this module is being installed explictly or
// `npm install` is being run at the root of the repository.
var request = null;
try {
  request = require('../lib/request');
} catch (error) {
  require('coffee-script').register();
  request = require('../src/request');
}

var tar = require('tar');
var temp = require('temp');

temp.track();

var downloadFileToLocation = function(url, filename, callback) {
  var stream = fs.createWriteStream(filename);
  stream.on('end', callback);
  stream.on('error', callback);
  request.createReadStream({url: url}, function(requestStream) {
    requestStream.pipe(stream);
  });
};

var downloadTarballAndExtract = function(url, location, callback) {
  var tempPath = temp.mkdirSync('apm-node-');
  var stream = tar.Extract({
    path: tempPath
  });
  stream.on('end', callback.bind(this, tempPath));
  stream.on('error', callback);
  request.createReadStream({url: url}, function(requestStream) {
    requestStream.pipe(zlib.createGunzip()).pipe(stream);
  });
};

var copyNodeBinToLocation = function(callback, version, targetFilename, fromDirectory) {
  var arch = process.arch === 'ia32' ? 'x86' : process.arch;
  var subDir = "node-" + version + "-" + process.platform + "-" + arch;
  var fromPath = path.join(fromDirectory, subDir, 'bin', 'node');
  return mv(fromPath, targetFilename, function(err) {
    if (err) {
      callback(err);
      return;
    }
    fs.chmod(targetFilename, "755", callback);
  });
};

var downloadNode = function(version, done) {
  var arch, downloadURL, filename;
  if (process.platform === 'win32') {
    if (process.env.JANKY_SHA1)
      arch = ''; // Always download 32-bit node on Atom Windows CI builds
    else
      arch = process.arch === 'x64' ? 'x64/' : '';
    downloadURL = "http://nodejs.org/dist/" + version + "/" + arch + "node.exe";
    filename = path.join('bin', "node.exe");
  } else {
    arch = process.arch === 'ia32' ? 'x86' : process.arch;
    downloadURL = "http://nodejs.org/dist/" + version + "/node-" + version + "-" + process.platform + "-" + arch + ".tar.gz";
    filename = path.join('bin', "node");
  }
  if (fs.existsSync(filename)) {
    done();
    return;
  }
  if (process.platform === 'win32') {
    return downloadFileToLocation(downloadURL, filename, done);
  } else {
    var next = copyNodeBinToLocation.bind(this, done, version, filename);
    return downloadTarballAndExtract(downloadURL, filename, next);
  }
};

downloadNode('v0.10.30', function(error) {
  if (error != null) {
    console.error('Failed to download node', error);
    return process.exit(1);
  } else {
    return process.exit(0);
  }
});
<commit_msg>Download node when installed version is different<commit_after>#!/usr/bin/env node
var fs = require('fs');
var mv = require('mv');
var zlib = require('zlib');
var path = require('path');

// Use whichever version of the local request helper is available
// This might be the JavaScript or CoffeeScript version depending
// on whether this module is being installed explictly or
// `npm install` is being run at the root of the repository.
var request = null;
try {
  request = require('../lib/request');
} catch (error) {
  require('coffee-script').register();
  request = require('../src/request');
}

var tar = require('tar');
var temp = require('temp');

temp.track();

var downloadFileToLocation = function(url, filename, callback) {
  var stream = fs.createWriteStream(filename);
  stream.on('end', callback);
  stream.on('error', callback);
  request.createReadStream({url: url}, function(requestStream) {
    requestStream.pipe(stream);
  });
};

var downloadTarballAndExtract = function(url, location, callback) {
  var tempPath = temp.mkdirSync('apm-node-');
  var stream = tar.Extract({
    path: tempPath
  });
  stream.on('end', callback.bind(this, tempPath));
  stream.on('error', callback);
  request.createReadStream({url: url}, function(requestStream) {
    requestStream.pipe(zlib.createGunzip()).pipe(stream);
  });
};

var copyNodeBinToLocation = function(callback, version, targetFilename, fromDirectory) {
  var arch = process.arch === 'ia32' ? 'x86' : process.arch;
  var subDir = "node-" + version + "-" + process.platform + "-" + arch;
  var fromPath = path.join(fromDirectory, subDir, 'bin', 'node');
  return mv(fromPath, targetFilename, function(err) {
    if (err) {
      callback(err);
      return;
    }
    fs.chmod(targetFilename, "755", callback);
  });
};

var getInstallNodeVersion = function(filename, callback) {
  require('child_process').exec(filename + ' -v', function(error, stdout) {
    var version = null;
    if (stdout != null) {
      version = stdout.toString().trim();
    }
    callback(error, version);
  });
}

var downloadNode = function(version, done) {
  var arch, downloadURL, filename;
  if (process.platform === 'win32') {
    if (process.env.JANKY_SHA1)
      arch = ''; // Always download 32-bit node on Atom Windows CI builds
    else
      arch = process.arch === 'x64' ? 'x64/' : '';
    downloadURL = "http://nodejs.org/dist/" + version + "/" + arch + "node.exe";
    filename = path.join('bin', "node.exe");
  } else {
    arch = process.arch === 'ia32' ? 'x86' : process.arch;
    downloadURL = "http://nodejs.org/dist/" + version + "/node-" + version + "-" + process.platform + "-" + arch + ".tar.gz";
    filename = path.join('bin', "node");
  }

  var downloadFile = function() {
    if (process.platform === 'win32') {
      downloadFileToLocation(downloadURL, filename, done);
    } else {
      var next = copyNodeBinToLocation.bind(this, done, version, filename);
      downloadTarballAndExtract(downloadURL, filename, next);
    }
  };

  if (fs.existsSync(filename)) {
    getInstallNodeVersion(filename, function(error, installedVersion) {
      if(error != null) {
        done(error);
      } else if (installedVersion !== version) {
        downloadFile();
      } else {
        done();
      }
    });
  } else {
    downloadFile();
  }
};

downloadNode('v0.10.30', function(error) {
  if (error != null) {
    console.error('Failed to download node', error);
    return process.exit(1);
  } else {
    return process.exit(0);
  }
});
<|endoftext|>


<commit_before>/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.controller.settings.Courses', {
    extend: 'Ext.app.Controller',

    // controller config
    views: [
        'settings.courses.Manager',
        'settings.courses.Form'
    ],

    stores: [
        'courses.Courses'
    ],

    models: [
        'course.Course'
    ],

    routes: {
        'settings/courses': 'showManager'
    },

    refs: {
        settingsNavPanel: {
            ref: 'settingsNavPanel',
            selector: 'settings-navpanel'
        },
        manager: {
            selector: 'courses-manager',
            autoCreate: true,

            xtype: 'courses-manager'
        },
        coursesFormWindow: {
            selector: 'courses-form-window',
            autoCreate: true,

            xtype: 'courses-form-window'
        }
    },

	control: {
        'courses-manager': {
            show: 'onManagerShow',
            edit: 'onCellEditorEdit',
            browsecoursesclick: 'onBrowseCoursesClick',
            deletecourseclick: 'onDeleteCourseClick'
        },
        'courses-manager button[action=create-course]': {
            click: 'onCreateCourseClick'
        },
        'courses-form-window button[action="save"]': {
            click: 'onSaveCourseClick'
        },
        'courses-form-window form': {
            fieldvaliditychange: 'setFormValidity',
            fielderrorchange: 'setFormValidity'
        }
    },

    // route handlers
    showManager: function() {
        var me = this,
            navPanel = me.getSettingsNavPanel();

        Ext.suspendLayouts();

        Ext.util.History.suspendState();
        navPanel.setActiveLink('settings/courses');
        navPanel.expand(false);
        Ext.util.History.resumeState(false); // false to discard any changes to state

        me.application.getController('Viewport').loadCard(me.getManager());

        Ext.resumeLayouts(true);
    },

    // event handlers
    onManagerShow: function(managerPanel) {
        var store = Ext.getStore('courses.Courses');

        if (!store.isLoaded()) {
            managerPanel.setLoading('Loading courses…');
            store.load({
                callback: function() {
                    managerPanel.setLoading(false);
                }
            });
        }

        Ext.util.History.pushState('settings/courses', 'Courses — Settings');
    },

    onCreateCourseClick: function() {
        var me = this,
            win = me.getCoursesFormWindow(),
            form = win.down('form'),
            titleField = form.down('textfield[name="Title"]'),
            saveButton = win.down('button[action="save"]');

        form.suspendEvents();
        form.reset();
        form.resumeEvents();

        saveButton.disable();

        win.show(null,function() {
            titleField.focus();
        });
    },

    onSaveCourseClick: function() {
        var me = this,
            manager = me.getManager();
            win = me.getCoursesFormWindow(),
            form = win.down('form'),
            course = me.getCourseCourseModel().create(form.getValues());

        if (course.isValid()) {
            course.set('ID', null);

            course.save({
                success: function(rec) {
                    win.close();
                    me.getCoursesCoursesStore().add(course);
                    manager.getView().focusRow(rec);
                }
            });
        }
    },

    onDeleteCourseClick: function(grid,rec) {
        Ext.Msg.confirm('Deleting Course', 'Are you sure you want to delete this course?', function(btn) {
            if (btn == 'yes') {
                rec.erase();
            }
        });
    },

    onCellEditorEdit: function(editor, e) {
        var rec = e.record;

        if (rec.isValid()) {
            rec.save();
        }
    },

    onBrowseCoursesClick: function(grid,rec) {
        Ext.util.History.pushState(['course-sections', 'search', 'course:' + rec.get('Code')]);
    },

    setFormValidity: function(form) {
        var saveButton = form.up('window').down('button[action="save"]');

        if (form.isValid()) {
            saveButton.enable();
        } else {
            saveButton.disable();
        }
    }
});
<commit_msg>Improve ref syntax<commit_after>/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.controller.settings.Courses', {
    extend: 'Ext.app.Controller',

    // controller config
    views: [
        'settings.courses.Manager',
        'settings.courses.Form'
    ],

    stores: [
        'courses.Courses'
    ],

    models: [
        'course.Course'
    ],

    routes: {
        'settings/courses': 'showManager'
    },

    refs: {
        settingsNavPanel: 'settings-navpanel',
        manager: {
            selector: 'courses-manager',
            autoCreate: true,

            xtype: 'courses-manager'
        },
        coursesFormWindow: {
            selector: 'courses-form-window',
            autoCreate: true,

            xtype: 'courses-form-window'
        }
    },

	control: {
        'courses-manager': {
            show: 'onManagerShow',
            edit: 'onCellEditorEdit',
            browsecoursesclick: 'onBrowseCoursesClick',
            deletecourseclick: 'onDeleteCourseClick'
        },
        'courses-manager button[action=create-course]': {
            click: 'onCreateCourseClick'
        },
        'courses-form-window button[action="save"]': {
            click: 'onSaveCourseClick'
        },
        'courses-form-window form': {
            fieldvaliditychange: 'setFormValidity',
            fielderrorchange: 'setFormValidity'
        }
    },

    // route handlers
    showManager: function() {
        var me = this,
            navPanel = me.getSettingsNavPanel();

        Ext.suspendLayouts();

        Ext.util.History.suspendState();
        navPanel.setActiveLink('settings/courses');
        navPanel.expand(false);
        Ext.util.History.resumeState(false); // false to discard any changes to state

        me.application.getController('Viewport').loadCard(me.getManager());

        Ext.resumeLayouts(true);
    },

    // event handlers
    onManagerShow: function(managerPanel) {
        var store = Ext.getStore('courses.Courses');

        if (!store.isLoaded()) {
            managerPanel.setLoading('Loading courses…');
            store.load({
                callback: function() {
                    managerPanel.setLoading(false);
                }
            });
        }

        Ext.util.History.pushState('settings/courses', 'Courses — Settings');
    },

    onCreateCourseClick: function() {
        var me = this,
            win = me.getCoursesFormWindow(),
            form = win.down('form'),
            titleField = form.down('textfield[name="Title"]'),
            saveButton = win.down('button[action="save"]');

        form.suspendEvents();
        form.reset();
        form.resumeEvents();

        saveButton.disable();

        win.show(null,function() {
            titleField.focus();
        });
    },

    onSaveCourseClick: function() {
        var me = this,
            manager = me.getManager();
            win = me.getCoursesFormWindow(),
            form = win.down('form'),
            course = me.getCourseCourseModel().create(form.getValues());

        if (course.isValid()) {
            course.set('ID', null);

            course.save({
                success: function(rec) {
                    win.close();
                    me.getCoursesCoursesStore().add(course);
                    manager.getView().focusRow(rec);
                }
            });
        }
    },

    onDeleteCourseClick: function(grid,rec) {
        Ext.Msg.confirm('Deleting Course', 'Are you sure you want to delete this course?', function(btn) {
            if (btn == 'yes') {
                rec.erase();
            }
        });
    },

    onCellEditorEdit: function(editor, e) {
        var rec = e.record;

        if (rec.isValid()) {
            rec.save();
        }
    },

    onBrowseCoursesClick: function(grid,rec) {
        Ext.util.History.pushState(['course-sections', 'search', 'course:' + rec.get('Code')]);
    },

    setFormValidity: function(form) {
        var saveButton = form.up('window').down('button[action="save"]');

        if (form.isValid()) {
            saveButton.enable();
        } else {
            saveButton.disable();
        }
    }
});
<|endoftext|>


<commit_before>/*!
 * CSS Template Layout
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */
(function () {
    var lastEvent, buffer, parser, compiler;
    var that = {
        constants:{
            DISPLAY:"display",
            POSITION:"position"
        },
        OperationNotSupportedException: Error,

        setTemplate:function (cssFile) {
            wef.log.info("loading template...");

            function readFile(url) {
                //TODO: FIXME
                function ajaxReadFile() {
                    var request = new XMLHttpRequest();
                    request.open("get", url, false);
                    request.send("");
                    wef.log.info("request status: ", request.statusText);
                    return request.responseText;
                }

                try {
                    return ajaxReadFile(url);
                } catch (e) {
                    wef.log.error(e);
                    throw new that.OperationNotSupportedException(e);
                }
            }

            wef.fn.cssParser.parse(readFile(cssFile));
            wef.log.info("template loaded OK");
        },

        insertTemplate:function (templateSource) {
            wef.log.info("adding template...");
            wef.fn.cssParser.parse(templateSource);
            wef.log.info("template added OK");
        },

        //only for testing purposes
        getLastEvent:function () {
            return lastEvent;
        },

        getBuffer:function () {
            return buffer;
        }
    };

    function defaultCompiler() {
        var that = {
            compile: compile,
            UnexpectedValueException: Error
        };

        function template(preProcessTemplate) {
            function gridSlot(slotText) {
                wef.log.info("creating new slot...");

                var that = {
                    slotText: slotText
                };

                wef.log.info("slot: ", that);
                return that;
            }

            function gridRow(rowText) {
                wef.log.info("creating new row...");

                var that = {
                    rowText: rowText,
                    slots: []
                };

                (function init() {
                    that.slots = Array.prototype.map.call(rowText, function(slot) {
                        wef.log.warn(rowText, "->", slot);
                        return gridSlot(slot.charAt(0));
                    });
                })();

                wef.log.info("row: ", that);
                return that;
            }

            function grid(display) {
                wef.log.info("creating new grid...");

                //var slots = {};
                var that = {
                    rows: []
                    //getTemplate
                    //setTemplate
                };

                (function init() {

                    if (display.grid != null) {
                        that.rows = display.grid.map(function(row) {
                            wef.log.warn("row >>>", row);
                            return gridRow(row);
                        });
                    }
                })();

                function hasSlot(slotIdentifier) {
                    wef.log.debug("hasSlot ? ", slotIdentifier);
                    return that.rows.some(function(row) {
                        var regExp = new RegExp(slotIdentifier);
                        return regExp.exec(row.rowText);
                    })
                }
                wef.log.info("grid: ", that);
                return that;
            }

            var that = {
                parentTemplate: null,
                selectorText: preProcessTemplate.selectorText,
                selector: null,
                display: preProcessTemplate.display,
                position: preProcessTemplate.position,
                grid: null,
                isRoot: isRoot,
                insert:insert
            };

            (function init() {
                wef.log.debug("creating template...");
                that.grid = grid(preProcessTemplate.display);
            })();

            function isRoot() {
                return that.position.position == null;
            }

            function insert(aTemplate) {

            }

            wef.log.info("new template:  ", that);
            return that;
        }

        var rootTemplate = function() {
            var that = {
                insert: insert,
                rows: []
            };

            function insert(preProcessTemplate) {
                wef.log.warn("inserting ", preProcessTemplate.selectorText);
                var aTemplate = template(preProcessTemplate);

                if (aTemplate.isRoot()) {
                    wef.log.debug("inserting at root", aTemplate.selectorText);
                    that.rows.push(aTemplate);
                    return true;
                } else {
                    wef.log.debug("searching parent: ", aTemplate.selectorText);
                    //insert in children
                    return that.rows.some(function(element, index, array) {
                        return element.insert(aTemplate);
                    });
                }
            }

            return that;
        }();

        (function init() {
            wef.log.info("new compiler created");
        })();

        function parseDisplay(displayValue) {
            /**
             * Name:    ‘display’
             * New value:    <display-type>? && [ [ <string> [ / <row-height> ]? ]+ ] <col-width>*
             * Percentages:    N/A
             * Computed value:    specified value
             *
             * The <display-type> is one of the following keywords. An omitted keyword is equivalent to ‘block’.
             * <display-type> = inline | block | list-item | inline-block | table | inline-table
             * | table-row-group | table-header-group | table-footer-group | table-row
             * | table-column-group | table-column | table-cell | table-caption | none
             *
             * Each <string> consist of one or more at signs (“@”), letters (or digits, see <letter> below),
             * periods (“.”) and spaces
             *
             * Each <row-height> sets the height of the preceding row. The default is ‘auto’.
             * The values can be as follows:
             * <length> An explicit height for that row. Negative values make the template illegal. If the length is
             * expressed in ‘gr’ units, these refer to the inherited grid, not the grid defined by the template itself.
             * auto The row's height is determined by its contents.
             * * (asterisk) All rows with an asterisk will be of equal height.
             *
             * Each <col-width> can be one of the following:
             * <length> An explicit width for that column. Negative values make the template illegal.
             * * (asterisk.) All columns with a ‘*’ have the same width. See the algorithm below.
             * max-content, min-content, minmax(p,q), fit-content
             */
            wef.log.info("compiling display...");
            wef.log.debug("display source: ", displayValue);
            var displayMetadata = {
                displayType: null,
                grid: null
            };
            var displayTypeRegExp = /^\s*(inline|block|list-item|inline-block|table|inline-table|table-row-group|table-header-group|table-footer-group|table-row|table-column-group|table-column|table-cell|table-caption|none)?/ig;
            var stringRegExp = /\s*"([a-zA-Z0-9.@ ])+"/ig;
            if (displayValue != undefined) {
                //TODO: check invalid values
                displayMetadata.displayType = displayValue.match(displayTypeRegExp);
                displayMetadata.grid = displayValue.match(stringRegExp).map(function(element) {
                    return element.replace(/"/g, "").replace(/\s*/, "");
                });
            }
            wef.log.info("display result: ", displayMetadata);
            return displayMetadata;
        }

        function parsePosition(positionValue) {
            /**
             * Name:    position
             * New value:    <letter> | same
             * Percentages:    N/A
             * Computed value:    ‘<letter>’ or ‘static’; see text
             *
             * <letter> must be a single letter or digit, with category Lu, Ll, Lt or Nd in Unicode [UNICODE]),
             * or a “@” symbol
             */
            wef.log.info("compiling position...");
            wef.log.debug("position source: ", positionValue);
            var positionMetadata = {
                position: null
            };
            var matched;
            var positionRegExp = /^\s*([a-zA-Z0-9]+|same)\s*/i;
            if (positionValue != undefined) {
                matched = positionValue.match(positionRegExp);
                if (matched == null) {
                    wef.log.error("Error: unexpected value at ", positionValue);
                    throw new that.UnexpectedValueException("Error: unexpected value at ", positionValue);
                }
                positionMetadata.position = matched[1];
            }
            wef.log.info("position result: ", positionMetadata);
            return positionMetadata;
        }

        function parseProperties(rule) {
            var preProcessTemplate = {};
            wef.log.info("compiling properties...");
            wef.log.debug("properties source: ", rule);

            preProcessTemplate.selectorText = rule.selectorText;

            //wef.log.debug("* ", templateLayout.constants.DISPLAY, rule.declaration[templateLayout.constants.DISPLAY]);
            preProcessTemplate.display = parseDisplay(rule.declaration[templateLayout.constants.DISPLAY]);

            //wef.log.debug("* ", templateLayout.constants.POSITION, rule.declaration[templateLayout.constants.POSITION]);
            preProcessTemplate.position = parsePosition(rule.declaration[templateLayout.constants.POSITION]);

            wef.log.info("properties result: ", preProcessTemplate);
            return preProcessTemplate;
        }

        function compile(buffer) {
            wef.log.info("compiling...");
            wef.log.debug("source: ", buffer);

            for (var selectorText in buffer) {
                wef.log.debug("next element: ", selectorText);
                var preProcessTemplate = parseProperties(buffer[selectorText]);
                wef.log.debug("result: ", preProcessTemplate);

                rootTemplate.insert(preProcessTemplate);
            }
            wef.log.debug("compiling ... OK");
        }

        return that;
    }

    (function init() {
        wef.log.info("creating templateLayout...");
        lastEvent = null;
        buffer = {};
        parser = wef.fn.cssParser;

        document.addEventListener(parser.events.PARSER_START, function (e) {
            wef.log.info("templateLayout listens: start parsing");
            lastEvent = e;
            buffer = {};
        }, false);

        document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
            wef.log.info("templateLayout listens: property found");
            lastEvent = e;
            if (isSupportedProperty(e.data)) {
                store(e.data);
            }
        }, false);

        document.addEventListener(parser.events.PARSER_DONE, function (e) {
            wef.log.info("templateLayout listens: parsing done");
            lastEvent = e;
            transform();
        }, false);

        wef.log.info("templateLayout OK");
    })();

    function transform() {
        compiler = defaultCompiler();
        wef.log.debug("transforming template ...");
        compiler.compile(buffer);
        wef.log.debug("template transformed OK");
    }

    function store(rule) {
        if (!buffer[rule.selectorText]) {
            buffer[rule.selectorText] = {selectorText:rule.selectorText, declaration:{}};
        }
        buffer[rule.selectorText].declaration[rule.declaration.property] = rule.declaration.valueText;
        wef.log.info("property stored: ", rule.declaration.property);
    }

    function isSupportedProperty(rule) {
        for (var iterator in that.constants) {
            if (that.constants[iterator] == rule.declaration.property) {
                wef.log.info("supported property found: ", rule.declaration.property);
                return true;
            }
        }
        return false;
    }

    window.templateLayout = that;
})();<commit_msg>Add grid.setTemplate<commit_after>/*!
 * CSS Template Layout
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */
(function () {
    var lastEvent, buffer, parser, compiler;
    var that = {
        constants:{
            DISPLAY:"display",
            POSITION:"position"
        },
        OperationNotSupportedException: Error,

        setTemplate:function (cssFile) {
            wef.log.info("loading template...");

            function readFile(url) {
                //TODO: FIXME
                function ajaxReadFile() {
                    var request = new XMLHttpRequest();
                    request.open("get", url, false);
                    request.send("");
                    wef.log.info("request status: ", request.statusText);
                    return request.responseText;
                }

                try {
                    return ajaxReadFile(url);
                } catch (e) {
                    wef.log.error(e);
                    throw new that.OperationNotSupportedException(e);
                }
            }

            wef.fn.cssParser.parse(readFile(cssFile));
            wef.log.info("template loaded OK");
        },

        insertTemplate:function (templateSource) {
            wef.log.info("adding template...");
            wef.fn.cssParser.parse(templateSource);
            wef.log.info("template added OK");
        },

        //only for testing purposes
        getLastEvent:function () {
            return lastEvent;
        },

        getBuffer:function () {
            return buffer;
        }
    };

    function defaultCompiler() {
        var that = {
            compile: compile,
            UnexpectedValueException: Error
        };

        function template(preProcessTemplate) {
            function gridSlot(slotText) {
                wef.log.info("creating new slot...");

                var that = {
                    slotText: slotText
                };

                wef.log.info("slot: ", that);
                return that;
            }

            function gridRow(rowText) {
                wef.log.info("creating new row...");

                var that = {
                    rowText: rowText,
                    slots: []
                };

                (function init() {
                    that.slots = Array.prototype.map.call(rowText, function(slot) {
                        wef.log.warn(rowText, "->", slot);
                        return gridSlot(slot.charAt(0));
                    });
                })();

                wef.log.info("row: ", that);
                return that;
            }

            function grid(display) {
                wef.log.info("creating new grid...");

                var that = {
                    rows: [],
                    //getTemplate
                    setTemplate: setTemplate
                };
                var slots = {};

                (function init() {

                    if (display.grid != null) {
                        that.rows = display.grid.map(function(row) {
                            wef.log.warn("row >>>", row);
                            return gridRow(row);
                        });
                    }
                })();

                function hasSlot(slotIdentifier) {
                    wef.log.debug("hasSlot ? ", slotIdentifier);
                    return that.rows.some(function(row) {
                        var regExp = new RegExp(slotIdentifier);
                        return regExp.exec(row.rowText);
                    })
                }

                function setTemplate(aTemplate) {
                    if(hasSlot(aTemplate.position.position)) {
                        wef.log.debug("insert here");
                        var tmp = slots[aTemplate.position.position] || new Array();
                        tmp.push(aTemplate);
                        slots[aTemplate.position.position] = tmp;
                        wef.log.debug("at ", slots[aTemplate.position.position]);
                        return true;
                    }

                    //forEach non leaf template in slots
                    for(var slot in slots) {
                        if(slots[slot].some(function (currentTemplate){
                            return !currentTemplate.isLeaf() && currentTemplate.insert(currentTemplate);
                        })) {
                            return true;
                        }
                    }

                    wef.log.debug("parent template not found");
                    return false;
                }

                wef.log.info("grid: ", that);
                return that;
            }

            var that = {
                parentTemplate: null,
                selectorText: preProcessTemplate.selectorText,
                selector: null,
                display: preProcessTemplate.display,
                position: preProcessTemplate.position,
                grid: null,
                isRoot: isRoot,
                insert:insert
            };

            (function init() {
                wef.log.debug("creating template...");
                that.grid = grid(preProcessTemplate.display);
            })();

            function isRoot() {
                return that.position.position == null;
            }

            function insert(aTemplate) {

            }

            wef.log.info("new template:  ", that);
            return that;
        }

        var rootTemplate = function() {
            var that = {
                insert: insert,
                rows: []
            };

            function insert(preProcessTemplate) {
                wef.log.warn("inserting ", preProcessTemplate.selectorText);
                var aTemplate = template(preProcessTemplate);

                if (aTemplate.isRoot()) {
                    wef.log.debug("inserting at root", aTemplate.selectorText);
                    that.rows.push(aTemplate);
                    return true;
                } else {
                    wef.log.debug("searching parent: ", aTemplate.selectorText);
                    //insert in children
                    return that.rows.some(function(element, index, array) {
                        return element.insert(aTemplate);
                    });
                }
            }

            return that;
        }();

        (function init() {
            wef.log.info("new compiler created");
        })();

        function parseDisplay(displayValue) {
            /**
             * Name:    ‘display’
             * New value:    <display-type>? && [ [ <string> [ / <row-height> ]? ]+ ] <col-width>*
             * Percentages:    N/A
             * Computed value:    specified value
             *
             * The <display-type> is one of the following keywords. An omitted keyword is equivalent to ‘block’.
             * <display-type> = inline | block | list-item | inline-block | table | inline-table
             * | table-row-group | table-header-group | table-footer-group | table-row
             * | table-column-group | table-column | table-cell | table-caption | none
             *
             * Each <string> consist of one or more at signs (“@”), letters (or digits, see <letter> below),
             * periods (“.”) and spaces
             *
             * Each <row-height> sets the height of the preceding row. The default is ‘auto’.
             * The values can be as follows:
             * <length> An explicit height for that row. Negative values make the template illegal. If the length is
             * expressed in ‘gr’ units, these refer to the inherited grid, not the grid defined by the template itself.
             * auto The row's height is determined by its contents.
             * * (asterisk) All rows with an asterisk will be of equal height.
             *
             * Each <col-width> can be one of the following:
             * <length> An explicit width for that column. Negative values make the template illegal.
             * * (asterisk.) All columns with a ‘*’ have the same width. See the algorithm below.
             * max-content, min-content, minmax(p,q), fit-content
             */
            wef.log.info("compiling display...");
            wef.log.debug("display source: ", displayValue);
            var displayMetadata = {
                displayType: null,
                grid: null
            };
            var displayTypeRegExp = /^\s*(inline|block|list-item|inline-block|table|inline-table|table-row-group|table-header-group|table-footer-group|table-row|table-column-group|table-column|table-cell|table-caption|none)?/ig;
            var stringRegExp = /\s*"([a-zA-Z0-9.@ ])+"/ig;
            if (displayValue != undefined) {
                //TODO: check invalid values
                displayMetadata.displayType = displayValue.match(displayTypeRegExp);
                displayMetadata.grid = displayValue.match(stringRegExp).map(function(element) {
                    return element.replace(/"/g, "").replace(/\s*/, "");
                });
            }
            wef.log.info("display result: ", displayMetadata);
            return displayMetadata;
        }

        function parsePosition(positionValue) {
            /**
             * Name:    position
             * New value:    <letter> | same
             * Percentages:    N/A
             * Computed value:    ‘<letter>’ or ‘static’; see text
             *
             * <letter> must be a single letter or digit, with category Lu, Ll, Lt or Nd in Unicode [UNICODE]),
             * or a “@” symbol
             */
            wef.log.info("compiling position...");
            wef.log.debug("position source: ", positionValue);
            var positionMetadata = {
                position: null
            };
            var matched;
            var positionRegExp = /^\s*([a-zA-Z0-9]+|same)\s*/i;
            if (positionValue != undefined) {
                matched = positionValue.match(positionRegExp);
                if (matched == null) {
                    wef.log.error("Error: unexpected value at ", positionValue);
                    throw new that.UnexpectedValueException("Error: unexpected value at ", positionValue);
                }
                positionMetadata.position = matched[1];
            }
            wef.log.info("position result: ", positionMetadata);
            return positionMetadata;
        }

        function parseProperties(rule) {
            var preProcessTemplate = {};
            wef.log.info("compiling properties...");
            wef.log.debug("properties source: ", rule);

            preProcessTemplate.selectorText = rule.selectorText;

            //wef.log.debug("* ", templateLayout.constants.DISPLAY, rule.declaration[templateLayout.constants.DISPLAY]);
            preProcessTemplate.display = parseDisplay(rule.declaration[templateLayout.constants.DISPLAY]);

            //wef.log.debug("* ", templateLayout.constants.POSITION, rule.declaration[templateLayout.constants.POSITION]);
            preProcessTemplate.position = parsePosition(rule.declaration[templateLayout.constants.POSITION]);

            wef.log.info("properties result: ", preProcessTemplate);
            return preProcessTemplate;
        }

        function compile(buffer) {
            wef.log.info("compiling...");
            wef.log.debug("source: ", buffer);

            for (var selectorText in buffer) {
                wef.log.debug("next element: ", selectorText);
                var preProcessTemplate = parseProperties(buffer[selectorText]);
                wef.log.debug("result: ", preProcessTemplate);

                rootTemplate.insert(preProcessTemplate);
            }
            wef.log.debug("compiling ... OK");
        }

        return that;
    }

    (function init() {
        wef.log.info("creating templateLayout...");
        lastEvent = null;
        buffer = {};
        parser = wef.fn.cssParser;

        document.addEventListener(parser.events.PARSER_START, function (e) {
            wef.log.info("templateLayout listens: start parsing");
            lastEvent = e;
            buffer = {};
        }, false);

        document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
            wef.log.info("templateLayout listens: property found");
            lastEvent = e;
            if (isSupportedProperty(e.data)) {
                store(e.data);
            }
        }, false);

        document.addEventListener(parser.events.PARSER_DONE, function (e) {
            wef.log.info("templateLayout listens: parsing done");
            lastEvent = e;
            transform();
        }, false);

        wef.log.info("templateLayout OK");
    })();

    function transform() {
        compiler = defaultCompiler();
        wef.log.debug("transforming template ...");
        compiler.compile(buffer);
        wef.log.debug("template transformed OK");
    }

    function store(rule) {
        if (!buffer[rule.selectorText]) {
            buffer[rule.selectorText] = {selectorText:rule.selectorText, declaration:{}};
        }
        buffer[rule.selectorText].declaration[rule.declaration.property] = rule.declaration.valueText;
        wef.log.info("property stored: ", rule.declaration.property);
    }

    function isSupportedProperty(rule) {
        for (var iterator in that.constants) {
            if (that.constants[iterator] == rule.declaration.property) {
                wef.log.info("supported property found: ", rule.declaration.property);
                return true;
            }
        }
        return false;
    }

    window.templateLayout = that;
})();<|endoftext|>


<commit_before>import "./common";

// Import third party libraries
import "../../third/bootstrap-notify/js/bootstrap-notify";
import "../../third/bootstrap-typeahead/typeahead";
import "../../third/bootstrap-tooltip/tooltip";
import "../../third/bootstrap-tooltip/tooltip.css";
import "jquery-caret-plugin/dist/jquery.caret";
import "../../third/jquery-idle/jquery.idle";
import "spectrum-colorpicker";
import "jquery-validation";
import "flatpickr";
import "flatpickr/dist/plugins/confirmDate/confirmDate";

// Import app JS
import "../i18n";
import "../feature_flags";
import "../loading";
import "../schema";
import "../vdom";
import "../search_util";
import "../keydown_util";
import "../lightbox_canvas";
import "../rtl";
import "../rendered_markdown";
import "../lazy_set";
import "../fold_dict";
import "../scroll_util";
import "../components";
import "../feedback_widget";
import "../localstorage";
import "../drafts";
import "../input_pill";
import "../user_pill";
import "../stream_pill";
import "../compose_pm_pill";
import "../channel";
import "../setup";
import "../unread_ui";
import "../unread_ops";
import "../muting";
import "../muting_ui";
import "../message_viewport";
import "../rows";
import "../people";
import "../user_groups";
import "../unread";
import "../topic_list_data";
import "../topic_list";
import "../pm_list_dom";
import "../pm_list";
import "../pm_conversations";
import "../recent_senders";
import "../stream_sort";
import "../topic_generator";
import "../top_left_corner";
import "../stream_list";
import "../topic_zoom";
import "../filter";
import "../poll_widget";
import "../todo_widget";
import "../zform";
import "../widgetize";
import "../submessage";
import "../fetch_status";
import "../message_list_data";
import "../message_list_view";
import "../message_list";
import "../message_live_update";
import "../narrow_state";
import "../narrow";
import "../reload_state";
import "../reload";
import "../compose_fade";
import "../markdown";
import "../local_message";
import "../echo";
import "../sent_messages";
import "../compose_state";
import "../compose_actions";
import "../transmit";
import "../zcommand";
import "../compose";
import "../upload";
import "../color_data";
import "../stream_color";
import "../stream_data";
import "../stream_topic_history";
import "../stream_muting";
import "../stream_events";
import "../stream_create";
import "../stream_edit";
import "../subs";
import "../message_edit";
import "../message_edit_history";
import "../condense";
import "../resize";
import "../list_widget";
import "../floating_recipient_bar";
import "../lightbox";
import "../ui_report";
import "../message_scroll";
import "../info_overlay";
import "../ui";
import "../night_mode";
import "../ui_util";
import "../click_handlers";
import "../settings_panel_menu";
import "../settings_toggle";
import "../scroll_bar";
import "../gear_menu";
import "../copy_and_paste";
import "../stream_popover";
import "../popovers";
import "../overlays";
import "../typeahead_helper";
import "../search_suggestion";
import "../search";
import "../composebox_typeahead";
import "../pill_typeahead";
import "../navigate";
import "../list_util";
import "../hotkey";
import "../favicon";
import "../notifications";
import "../hash_util";
import "../hashchange";
import "../invite";
import "../message_flags";
import "../starred_messages";
import "../alert_words";
import "../alert_words_ui";
import "../attachments_ui";
import "../message_store";
import "../message_util";
import "../message_events";
import "../message_fetch";
import "../server_events";
import "../server_events_dispatch";
import "../zulip";
import "../presence";
import "../user_search";
import "../user_status";
import "../user_status_ui";
import "../buddy_data";
import "../padded_widget";
import "../buddy_list";
import "../list_cursor";
import "../activity";
import "../user_events";
import "../colorspace";
import "../timerender";
import "../tutorial";
import "../hotspots";
import "../templates";
import "../upload_widget";
import "../avatar";
import "../realm_icon";
import "../realm_logo";
import "../reminder";
import "../confirm_dialog";
import "../dropdown_list_widget";
import "../settings_account";
import "../settings_display";
import "../settings_notifications";
import "../settings_bots";
import "../settings_muting";
import "../settings_sections";
import "../settings_emoji";
import "../settings_exports";
import "../settings_org";
import "../settings_users";
import "../settings_streams";
import "../settings_linkifiers";
import "../settings_invites";
import "../settings_user_groups";
import "../settings_profile_fields";
import "../settings";
import "../admin";
import "../message_view_header";
import "../bot_data";
import "../reactions";
import "../typing";
import "../typing_data";
import "../typing_events";
import "../ui_init";
import "../emoji_picker";
import "../compose_ui";
import "../panels";
import "../recent_topics";
import "../settings_ui";
import "../search_pill";
import "../search_pill_widget";
import "../stream_ui_updates";
import "../spoilers";
import "../desktop_integration";

// Import styles

import "../../third/bootstrap-notify/css/bootstrap-notify.css";
import "spectrum-colorpicker/spectrum.css";
import "katex/dist/katex.css";
import "flatpickr/dist/flatpickr.css";
import "flatpickr/dist/plugins/confirmDate/confirmDate.css";
import "../../styles/components.css";
import "../../styles/app_components.css";
import "../../styles/rendered_markdown.css";
import "../../styles/zulip.css";
import "../../styles/alerts.css";
import "../../styles/settings.css";
import "../../styles/image_upload_widget.css";
import "../../styles/subscriptions.css";
import "../../styles/drafts.css";
import "../../styles/input_pill.css";
import "../../styles/informational_overlays.css";
import "../../styles/compose.css";
import "../../styles/message_edit_history.css";
import "../../styles/reactions.css";
import "../../styles/user_circles.css";
import "../../styles/left_sidebar.css";
import "../../styles/right_sidebar.css";
import "../../styles/lightbox.css";
import "../../styles/popovers.css";
import "../../styles/recent_topics.css";
import "../../styles/typing_notifications.css";
import "../../styles/hotspots.css";
import "../../styles/night_mode.css";
import "../../styles/user_status.css";
import "../../styles/widgets.css";

// This should be last.
import "../ready";
<commit_msg>bundles: Remove imports with no top-level effect.<commit_after>import "./common";

// Import third party libraries
import "../../third/bootstrap-notify/js/bootstrap-notify";
import "../../third/bootstrap-typeahead/typeahead";
import "../../third/bootstrap-tooltip/tooltip";
import "../../third/bootstrap-tooltip/tooltip.css";
import "jquery-caret-plugin/dist/jquery.caret";
import "../../third/jquery-idle/jquery.idle";
import "spectrum-colorpicker";
import "jquery-validation";
import "flatpickr";
import "flatpickr/dist/plugins/confirmDate/confirmDate";

// Import app JS
import "../i18n";
import "../feature_flags";
import "../loading";
import "../schema";
import "../vdom";
import "../search_util";
import "../keydown_util";
import "../lightbox_canvas";
import "../rtl";
import "../rendered_markdown";
import "../fold_dict";
import "../scroll_util";
import "../components";
import "../feedback_widget";
import "../localstorage";
import "../drafts";
import "../input_pill";
import "../user_pill";
import "../stream_pill";
import "../compose_pm_pill";
import "../channel";
import "../setup";
import "../unread_ui";
import "../unread_ops";
import "../muting";
import "../muting_ui";
import "../message_viewport";
import "../rows";
import "../user_groups";
import "../unread";
import "../topic_list_data";
import "../topic_list";
import "../pm_list_dom";
import "../pm_list";
import "../recent_senders";
import "../stream_sort";
import "../topic_generator";
import "../top_left_corner";
import "../stream_list";
import "../topic_zoom";
import "../filter";
import "../poll_widget";
import "../todo_widget";
import "../zform";
import "../widgetize";
import "../submessage";
import "../fetch_status";
import "../message_list_data";
import "../message_list_view";
import "../message_list";
import "../message_live_update";
import "../narrow_state";
import "../narrow";
import "../reload_state";
import "../reload";
import "../compose_fade";
import "../markdown";
import "../local_message";
import "../echo";
import "../sent_messages";
import "../compose_state";
import "../compose_actions";
import "../transmit";
import "../zcommand";
import "../compose";
import "../upload";
import "../color_data";
import "../stream_color";
import "../stream_data";
import "../stream_topic_history";
import "../stream_muting";
import "../stream_events";
import "../stream_create";
import "../stream_edit";
import "../subs";
import "../message_edit";
import "../message_edit_history";
import "../condense";
import "../resize";
import "../list_widget";
import "../floating_recipient_bar";
import "../lightbox";
import "../ui_report";
import "../message_scroll";
import "../info_overlay";
import "../ui";
import "../night_mode";
import "../ui_util";
import "../click_handlers";
import "../settings_panel_menu";
import "../settings_toggle";
import "../scroll_bar";
import "../gear_menu";
import "../copy_and_paste";
import "../stream_popover";
import "../popovers";
import "../overlays";
import "../typeahead_helper";
import "../search_suggestion";
import "../search";
import "../composebox_typeahead";
import "../pill_typeahead";
import "../navigate";
import "../list_util";
import "../hotkey";
import "../notifications";
import "../hash_util";
import "../hashchange";
import "../invite";
import "../message_flags";
import "../starred_messages";
import "../alert_words";
import "../alert_words_ui";
import "../attachments_ui";
import "../message_store";
import "../message_util";
import "../message_events";
import "../message_fetch";
import "../server_events";
import "../server_events_dispatch";
import "../zulip";
import "../presence";
import "../user_search";
import "../user_status";
import "../user_status_ui";
import "../buddy_data";
import "../padded_widget";
import "../buddy_list";
import "../list_cursor";
import "../activity";
import "../user_events";
import "../colorspace";
import "../timerender";
import "../tutorial";
import "../hotspots";
import "../templates";
import "../upload_widget";
import "../avatar";
import "../realm_icon";
import "../realm_logo";
import "../reminder";
import "../confirm_dialog";
import "../dropdown_list_widget";
import "../settings_account";
import "../settings_display";
import "../settings_notifications";
import "../settings_bots";
import "../settings_muting";
import "../settings_sections";
import "../settings_emoji";
import "../settings_exports";
import "../settings_org";
import "../settings_users";
import "../settings_streams";
import "../settings_linkifiers";
import "../settings_invites";
import "../settings_user_groups";
import "../settings_profile_fields";
import "../settings";
import "../admin";
import "../message_view_header";
import "../bot_data";
import "../reactions";
import "../typing";
import "../typing_data";
import "../typing_events";
import "../ui_init";
import "../emoji_picker";
import "../compose_ui";
import "../panels";
import "../recent_topics";
import "../settings_ui";
import "../search_pill";
import "../search_pill_widget";
import "../stream_ui_updates";
import "../spoilers";
import "../desktop_integration";

// Import styles

import "../../third/bootstrap-notify/css/bootstrap-notify.css";
import "spectrum-colorpicker/spectrum.css";
import "katex/dist/katex.css";
import "flatpickr/dist/flatpickr.css";
import "flatpickr/dist/plugins/confirmDate/confirmDate.css";
import "../../styles/components.css";
import "../../styles/app_components.css";
import "../../styles/rendered_markdown.css";
import "../../styles/zulip.css";
import "../../styles/alerts.css";
import "../../styles/settings.css";
import "../../styles/image_upload_widget.css";
import "../../styles/subscriptions.css";
import "../../styles/drafts.css";
import "../../styles/input_pill.css";
import "../../styles/informational_overlays.css";
import "../../styles/compose.css";
import "../../styles/message_edit_history.css";
import "../../styles/reactions.css";
import "../../styles/user_circles.css";
import "../../styles/left_sidebar.css";
import "../../styles/right_sidebar.css";
import "../../styles/lightbox.css";
import "../../styles/popovers.css";
import "../../styles/recent_topics.css";
import "../../styles/typing_notifications.css";
import "../../styles/hotspots.css";
import "../../styles/night_mode.css";
import "../../styles/user_status.css";
import "../../styles/widgets.css";

// This should be last.
import "../ready";
<|endoftext|>