frappe.ready(function () {
frappe.file_reading = false;
frappe.form_dirty = false;
$.extend(frappe, web_form_settings);
moment.defaultFormat = frappe.moment_date_format;
$('[data-toggle="tooltip"]').tooltip();
var $form = $("form[data-web-form='" + frappe.web_form_name + "']");
$form.on("change", "[type='file']", function () {
var $input = $(this);
if ($input.attr("type") === "file") {
var input = $input.get(0);
var reader = new FileReader();
if (input.files.length) {
var file = input.files[0];
frappe.file_reading = true;
reader.onload = function (e) {
input.filedata = {
"__file_attachment": 1,
"filename": file.name,
"dataurl": reader.result
};
if (input.filedata.dataurl.length > frappe.max_attachment_size * 1024 * 1024) {
frappe.msgprint(__('Max file size allowed is {0}MB', [frappe.max_attachment_size]));
input.filedata = null;
$(input).val('');
$(input).attr('data-value', '');
}
frappe.file_reading = false;
};
reader.readAsDataURL(file);
}
}
});
var set_mandatory_class = function set_mandatory_class(input) {
if ($(input).attr('data-reqd')) {
$(input).parent().toggleClass('has-error', !!!$(input).val());
}
};
$('.form-group input, .form-group textarea, .form-group select').on('change', function () {
set_mandatory_class(this);
}).on('keypress', function () {
set_mandatory_class(this);
var maxlength = parseInt($(this).attr('maxlength'));
if (maxlength && (($(this).val() || '') + '').length > maxlength - 1) {
$(this).val($(this).val().substr(0, maxlength - 1));
}
}).each(function () {
set_mandatory_class(this);
});
$form.on('change', function () {
frappe.form_dirty = true;
});
$form.on('submit', function () {
return false;
});
$('.btn-payment').on('click', function () {
save(true);
return false;
});
$form.on("click", ".change-attach", function () {
var input_wrapper = $(this).parent().addClass("hide").parent().find(".attach-input-wrap").removeClass("hide");
input_wrapper.find('input').val('').attr('data-value', '');
frappe.form_dirty = true;
return false;
});
$('.btn-change-section, .slide-progress .fa-fw').on('click', function () {
var idx = $(this).attr('data-idx');
if (!frappe.form_dirty || frappe.is_read_only) {
show_slide(idx);
} else {
if (save() !== false) {
show_slide(idx);
}
}
return false;
});
var show_slide = function show_slide(idx) {
$('.web-form-page').addClass('hidden');
$('.slide-progress .fa-circle').removeClass('fa-circle').addClass('fa-circle-o');
$('.slide-progress .fa-fw[data-idx="' + idx + '"]').removeClass('fa-circle-o').addClass('fa-circle');
$('.web-form-page[data-idx="' + idx + '"]').removeClass('hidden').find(':input:first').focus();
};
$('.btn-add-row').on('click', function () {
var fieldname = $(this).attr('data-fieldname');
var grid = $('.web-form-grid[data-fieldname="' + fieldname + '"]');
var new_row = grid.find('.web-form-grid-row.hidden').clone().appendTo(grid.find('tbody')).attr('data-name', '').removeClass('hidden');
new_row.find('input').each(function () {
$(this).val($(this).attr('data-default') || "").removeClass('hasDatepicker').attr('id', '');
});
setup_date_picker(new_row);
return false;
});
$('.web-form-grid').on('click', '.btn-remove', function () {
$(this).parents('.web-form-grid-row:first').addClass('hidden').remove();
frappe.form_dirty = true;
return false;
});
var get_data = function get_data() {
frappe.mandatory_missing_in_last_doc = [];
var doc = get_data_for_doctype($form, frappe.web_form_doctype);
doc.doctype = frappe.web_form_doctype;
if (frappe.doc_name) {
doc.name = frappe.doc_name;
}
frappe.mandatory_missing = frappe.mandatory_missing_in_last_doc;
$('.web-form-grid').each(function () {
var fieldname = $(this).attr('data-fieldname');
var doctype = $(this).attr('data-doctype');
doc[fieldname] = [];
$(this).find('[data-child-row=1]').each(function () {
if (!$(this).hasClass('hidden')) {
frappe.mandatory_missing_in_last_doc = [];
var d = get_data_for_doctype($(this), doctype);
var name = $(this).attr('data-name');
if (name) {
d.name = name;
}
var has_value = false;
for (var key in d) {
if (typeof d[key] === 'string') {
d[key] = d[key].trim();
}
if (d[key] !== null && d[key] !== undefined && d[key] !== '') {
has_value = true;
break;
}
}
if (has_value) {
doc[fieldname].push(d);
frappe.mandatory_missing = frappe.mandatory_missing.concat(frappe.mandatory_missing_in_last_doc);
}
}
});
});
return doc;
};
var get_data_for_doctype = function get_data_for_doctype(parent, doctype) {
var out = {};
parent.find("[name][data-doctype='" + doctype + "']").each(function () {
var $input = $(this);
var input_type = $input.attr("data-fieldtype");
var no_attachment = false;
if (input_type === "Attach") {
if ($input.get(0).filedata) {
var val = $input.get(0).filedata;
} else {
var val = $input.attr('data-value');
if (!val) {
val = { '__no_attachment': 1 };
no_attachment = true;
}
}
} else if (input_type === 'Text Editor') {
var val = $input.parent().find('.note-editable').html();
} else if (input_type === "Check") {
var val = $input.prop("checked") ? 1 : 0;
} else if (input_type === "Date") {
if ($input.val()) {
var val = moment($input.val(), moment.defaultFormat).format('YYYY-MM-DD');
} else {
var val = null;
}
} else {
var val = $input.val();
}
if (typeof val === 'string') {
val = val.trim();
}
if ($input.attr("data-reqd") && (val === undefined || val === null || val === '' || no_attachment)) {
frappe.mandatory_missing_in_last_doc.push([$input.attr("data-label"), $input.parents('.web-form-page:first').attr('data-label')]);
}
out[$input.attr("name")] = val;
});
return out;
};
function save(for_payment) {
if (window.saving) return false;
window.saving = true;
frappe.form_dirty = false;
if (frappe.file_reading) {
window.saving = false;
frappe.msgprint(__("Uploading files please wait for a few seconds."));
return false;
}
var data = get_data();
if ((!frappe.allow_incomplete || for_payment) && frappe.mandatory_missing.length) {
window.saving = false;
show_mandatory_missing();
return false;
}
frappe.call({
type: "POST",
method: "frappe.website.doctype.web_form.web_form.accept",
args: {
data: data,
web_form: frappe.web_form_name,
for_payment: for_payment
},
freeze: true,
btn: $form.find("[type='submit']"),
callback: function callback(data) {
if (!data.exc) {
frappe.doc_name = data.message;
$form.addClass("hide");
$(".comments, .introduction, .page-head").addClass("hide");
scroll(0, 0);
set_message(frappe.success_link, true);
if (for_payment && data.message) {
window.location.href = data.message;
}
} else {
frappe.msgprint(__('There were errors. Please report this.'));
}
},
always: function always() {
window.saving = false;
}
});
return true;
}
function show_mandatory_missing() {
var text = [],
last_section = null;
frappe.mandatory_missing.forEach(function (d) {
if (last_section != d[1]) {
text.push('');
text.push(d[1].bold());
last_section = d[1];
}
text.push(d[0]);
});
frappe.msgprint(__('The following mandatory fields must be filled:
') + text.join('
'));
}
function set_message(msg, permanent) {
$(".form-message").html(msg).removeClass("hide");
if (!permanent) {
setTimeout(function () {
$(".form-message").addClass('hide');
}, 5000);
}
}
$(".btn-form-submit").on("click", function () {
save();
return false;
});
$(".close").on("click", function () {
var name = $(this).attr("data-name");
if (name) {
frappe.call({
type: "POST",
method: "frappe.website.doctype.web_form.web_form.delete",
args: {
"web_form": frappe.web_form_name,
"name": name
},
callback: function callback(r) {
if (!r.exc) {
location.reload();
}
}
});
}
});
var setup_date_picker = function setup_date_picker(ele) {
var $dates = ele.find("[data-fieldtype='Date']");
var $date_times = ele.find("[data-fieldtype='Datetime']");
if ($dates.length) {
$dates.datepicker({
language: "en",
autoClose: true,
dateFormat: frappe.datepicker_format
});
$dates.each(function () {
var val = $(this).attr('value');
if (val) {
$(this).val(moment(val, 'YYYY-MM-DD').format()).trigger('change');
}
});
}
if ($date_times.length) {
$date_times.datepicker({
language: "en",
autoClose: true,
dateFormat: frappe.datepicker_format,
timepicker: true,
timeFormat: "hh:ii:ss"
});
}
};
setup_date_picker($form);
var summernotes = {};
var setup_text_editor = function setup_text_editor() {
var editors = $('[data-fieldtype="Text Editor"]');
editors.each(function () {
if ($(this).attr('disabled')) return;
summernotes[$(this).attr('data-fieldname')] = $(this).summernote({
minHeight: 400,
toolbar: [['magic', ['style']], ['style', ['bold', 'italic', 'underline', 'clear']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['media', ['link', 'picture']], ['misc', ['fullscreen', 'codeview']]],
icons: frappe.summer_note_icons
});
});
};
setup_text_editor();
});
frappe.summer_note_icons = {
'align': 'fa fa-align',
'alignCenter': 'fa fa-align-center',
'alignJustify': 'fa fa-align-justify',
'alignLeft': 'fa fa-align-left',
'alignRight': 'fa fa-align-right',
'indent': 'fa fa-indent',
'outdent': 'fa fa-outdent',
'arrowsAlt': 'fa fa-arrows-alt',
'bold': 'fa fa-bold',
'caret': 'caret',
'circle': 'fa fa-circle',
'close': 'fa fa-close',
'code': 'fa fa-code',
'eraser': 'fa fa-eraser',
'font': 'fa fa-font',
'frame': 'fa fa-frame',
'italic': 'fa fa-italic',
'link': 'fa fa-link',
'unlink': 'fa fa-chain-broken',
'magic': 'fa fa-magic',
'menuCheck': 'fa fa-check',
'minus': 'fa fa-minus',
'orderedlist': 'fa fa-list-ol',
'pencil': 'fa fa-pencil',
'picture': 'fa fa-image',
'question': 'fa fa-question',
'redo': 'fa fa-redo',
'square': 'fa fa-square',
'strikethrough': 'fa fa-strikethrough',
'subscript': 'fa fa-subscript',
'superscript': 'fa fa-superscript',
'table': 'fa fa-table',
'textHeight': 'fa fa-text-height',
'trash': 'fa fa-trash',
'underline': 'fa fa-underline',
'undo': 'fa fa-undo',
'unorderedlist': 'fa fa-list-ul',
'video': 'fa fa-video-camera'
};/**
* Super simple wysiwyg editor v0.8.2
* http://summernote.org/
*
* summernote.js
* Copyright 2013-2016 Alan Hong. and other contributors
* summernote may be freely distributed under the MIT license./
*
* Date: 2016-08-07T05:11Z
*/
(function (factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function ($) {
/**
* @class core.func
*
* func utils (for high-order func's arg)
*
* @singleton
* @alternateClassName func
*/
var func = (function () {
var eq = function (itemA) {
return function (itemB) {
return itemA === itemB;
};
};
var eq2 = function (itemA, itemB) {
return itemA === itemB;
};
var peq2 = function (propName) {
return function (itemA, itemB) {
return itemA[propName] === itemB[propName];
};
};
var ok = function () {
return true;
};
var fail = function () {
return false;
};
var not = function (f) {
return function () {
return !f.apply(f, arguments);
};
};
var and = function (fA, fB) {
return function (item) {
return fA(item) && fB(item);
};
};
var self = function (a) {
return a;
};
var invoke = function (obj, method) {
return function () {
return obj[method].apply(obj, arguments);
};
};
var idCounter = 0;
/**
* generate a globally-unique id
*
* @param {String} [prefix]
*/
var uniqueId = function (prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
/**
* returns bnd (bounds) from rect
*
* - IE Compatibility Issue: http://goo.gl/sRLOAo
* - Scroll Issue: http://goo.gl/sNjUc
*
* @param {Rect} rect
* @return {Object} bounds
* @return {Number} bounds.top
* @return {Number} bounds.left
* @return {Number} bounds.width
* @return {Number} bounds.height
*/
var rect2bnd = function (rect) {
var $document = $(document);
return {
top: rect.top + $document.scrollTop(),
left: rect.left + $document.scrollLeft(),
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
};
/**
* returns a copy of the object where the keys have become the values and the values the keys.
* @param {Object} obj
* @return {Object}
*/
var invertObject = function (obj) {
var inverted = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
inverted[obj[key]] = key;
}
}
return inverted;
};
/**
* @param {String} namespace
* @param {String} [prefix]
* @return {String}
*/
var namespaceToCamel = function (namespace, prefix) {
prefix = prefix || '';
return prefix + namespace.split('.').map(function (name) {
return name.substring(0, 1).toUpperCase() + name.substring(1);
}).join('');
};
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing.
* @param {Function} func
* @param {Number} wait
* @param {Boolean} immediate
* @return {Function}
*/
var debounce = function (func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
};
return {
eq: eq,
eq2: eq2,
peq2: peq2,
ok: ok,
fail: fail,
self: self,
not: not,
and: and,
invoke: invoke,
uniqueId: uniqueId,
rect2bnd: rect2bnd,
invertObject: invertObject,
namespaceToCamel: namespaceToCamel,
debounce: debounce
};
})();
/**
* @class core.list
*
* list utils
*
* @singleton
* @alternateClassName list
*/
var list = (function () {
/**
* returns the first item of an array.
*
* @param {Array} array
*/
var head = function (array) {
return array[0];
};
/**
* returns the last item of an array.
*
* @param {Array} array
*/
var last = function (array) {
return array[array.length - 1];
};
/**
* returns everything but the last entry of the array.
*
* @param {Array} array
*/
var initial = function (array) {
return array.slice(0, array.length - 1);
};
/**
* returns the rest of the items in an array.
*
* @param {Array} array
*/
var tail = function (array) {
return array.slice(1);
};
/**
* returns item of array
*/
var find = function (array, pred) {
for (var idx = 0, len = array.length; idx < len; idx ++) {
var item = array[idx];
if (pred(item)) {
return item;
}
}
};
/**
* returns true if all of the values in the array pass the predicate truth test.
*/
var all = function (array, pred) {
for (var idx = 0, len = array.length; idx < len; idx ++) {
if (!pred(array[idx])) {
return false;
}
}
return true;
};
/**
* returns index of item
*/
var indexOf = function (array, item) {
return $.inArray(item, array);
};
/**
* returns true if the value is present in the list.
*/
var contains = function (array, item) {
return indexOf(array, item) !== -1;
};
/**
* get sum from a list
*
* @param {Array} array - array
* @param {Function} fn - iterator
*/
var sum = function (array, fn) {
fn = fn || func.self;
return array.reduce(function (memo, v) {
return memo + fn(v);
}, 0);
};
/**
* returns a copy of the collection with array type.
* @param {Collection} collection - collection eg) node.childNodes, ...
*/
var from = function (collection) {
var result = [], idx = -1, length = collection.length;
while (++idx < length) {
result[idx] = collection[idx];
}
return result;
};
/**
* returns whether list is empty or not
*/
var isEmpty = function (array) {
return !array || !array.length;
};
/**
* cluster elements by predicate function.
*
* @param {Array} array - array
* @param {Function} fn - predicate function for cluster rule
* @param {Array[]}
*/
var clusterBy = function (array, fn) {
if (!array.length) { return []; }
var aTail = tail(array);
return aTail.reduce(function (memo, v) {
var aLast = last(memo);
if (fn(last(aLast), v)) {
aLast[aLast.length] = v;
} else {
memo[memo.length] = [v];
}
return memo;
}, [[head(array)]]);
};
/**
* returns a copy of the array with all false values removed
*
* @param {Array} array - array
* @param {Function} fn - predicate function for cluster rule
*/
var compact = function (array) {
var aResult = [];
for (var idx = 0, len = array.length; idx < len; idx ++) {
if (array[idx]) { aResult.push(array[idx]); }
}
return aResult;
};
/**
* produces a duplicate-free version of the array
*
* @param {Array} array
*/
var unique = function (array) {
var results = [];
for (var idx = 0, len = array.length; idx < len; idx ++) {
if (!contains(results, array[idx])) {
results.push(array[idx]);
}
}
return results;
};
/**
* returns next item.
* @param {Array} array
*/
var next = function (array, item) {
var idx = indexOf(array, item);
if (idx === -1) { return null; }
return array[idx + 1];
};
/**
* returns prev item.
* @param {Array} array
*/
var prev = function (array, item) {
var idx = indexOf(array, item);
if (idx === -1) { return null; }
return array[idx - 1];
};
return { head: head, last: last, initial: initial, tail: tail,
prev: prev, next: next, find: find, contains: contains,
all: all, sum: sum, from: from, isEmpty: isEmpty,
clusterBy: clusterBy, compact: compact, unique: unique };
})();
var isSupportAmd = typeof define === 'function' && define.amd;
/**
* returns whether font is installed or not.
*
* @param {String} fontName
* @return {Boolean}
*/
var isFontInstalled = function (fontName) {
var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS';
var $tester = $('
] var ancestors = listAncestor(point.node, func.eq(root)); if (!ancestors.length) { return null; } else if (ancestors.length === 1) { return splitNode(point, options); } return ancestors.reduce(function (node, parent) { if (node === point.node) { node = splitNode(point, options); } return splitNode({ node: parent, offset: node ? dom.position(node) : nodeLength(parent) }, options); }); }; /** * split point * * @param {Point} point * @param {Boolean} isInline * @return {Object} */ var splitPoint = function (point, isInline) { // find splitRoot, container // - inline: splitRoot is a child of paragraph // - block: splitRoot is a child of bodyContainer var pred = isInline ? isPara : isBodyContainer; var ancestors = listAncestor(point.node, pred); var topAncestor = list.last(ancestors) || point.node; var splitRoot, container; if (pred(topAncestor)) { splitRoot = ancestors[ancestors.length - 2]; container = topAncestor; } else { splitRoot = topAncestor; container = splitRoot.parentNode; } // if splitRoot is exists, split with splitTree var pivot = splitRoot && splitTree(splitRoot, point, { isSkipPaddingBlankHTML: isInline, isNotSplitEdgePoint: isInline }); // if container is point.node, find pivot with point.offset if (!pivot && container === point.node) { pivot = point.node.childNodes[point.offset]; } return { rightNode: pivot, container: container }; }; var create = function (nodeName) { return document.createElement(nodeName); }; var createText = function (text) { return document.createTextNode(text); }; /** * @method remove * * remove node, (isRemoveChild: remove child or not) * * @param {Node} node * @param {Boolean} isRemoveChild */ var remove = function (node, isRemoveChild) { if (!node || !node.parentNode) { return; } if (node.removeNode) { return node.removeNode(isRemoveChild); } var parent = node.parentNode; if (!isRemoveChild) { var nodes = []; var i, len; for (i = 0, len = node.childNodes.length; i < len; i++) { nodes.push(node.childNodes[i]); } for (i = 0, len = nodes.length; i < len; i++) { parent.insertBefore(nodes[i], node); } } parent.removeChild(node); }; /** * @method removeWhile * * @param {Node} node * @param {Function} pred */ var removeWhile = function (node, pred) { while (node) { if (isEditable(node) || !pred(node)) { break; } var parent = node.parentNode; remove(node); node = parent; } }; /** * @method replace * * replace node with provided nodeName * * @param {Node} node * @param {String} nodeName * @return {Node} - new node */ var replace = function (node, nodeName) { if (node.nodeName.toUpperCase() === nodeName.toUpperCase()) { return node; } var newNode = create(nodeName); if (node.style.cssText) { newNode.style.cssText = node.style.cssText; } appendChildNodes(newNode, list.from(node.childNodes)); insertAfter(newNode, node); remove(node); return newNode; }; var isTextarea = makePredByNodeName('TEXTAREA'); /** * @param {jQuery} $node * @param {Boolean} [stripLinebreaks] - default: false */ var value = function ($node, stripLinebreaks) { var val = isTextarea($node[0]) ? $node.val() : $node.html(); if (stripLinebreaks) { return val.replace(/[\n\r]/g, ''); } return val; }; /** * @method html * * get the HTML contents of node * * @param {jQuery} $node * @param {Boolean} [isNewlineOnBlock] */ var html = function ($node, isNewlineOnBlock) { var markup = value($node); if (isNewlineOnBlock) { var regexTag = /<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g; markup = markup.replace(regexTag, function (match, endSlash, name) { name = name.toUpperCase(); var isEndOfInlineContainer = /^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(name) && !!endSlash; var isBlockNode = /^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(name); return match + ((isEndOfInlineContainer || isBlockNode) ? '\n' : ''); }); markup = $.trim(markup); } return markup; }; var posFromPlaceholder = function (placeholder) { var $placeholder = $(placeholder); var pos = $placeholder.offset(); var height = $placeholder.outerHeight(true); // include margin return { left: pos.left, top: pos.top + height }; }; var attachEvents = function ($node, events) { Object.keys(events).forEach(function (key) { $node.on(key, events[key]); }); }; var detachEvents = function ($node, events) { Object.keys(events).forEach(function (key) { $node.off(key, events[key]); }); }; return { /** @property {String} NBSP_CHAR */ NBSP_CHAR: NBSP_CHAR, /** @property {String} ZERO_WIDTH_NBSP_CHAR */ ZERO_WIDTH_NBSP_CHAR: ZERO_WIDTH_NBSP_CHAR, /** @property {String} blank */ blank: blankHTML, /** @property {String} emptyPara */ emptyPara: '
' + blankHTML + '
', makePredByNodeName: makePredByNodeName, isEditable: isEditable, isControlSizing: isControlSizing, isText: isText, isElement: isElement, isVoid: isVoid, isPara: isPara, isPurePara: isPurePara, isHeading: isHeading, isInline: isInline, isBlock: func.not(isInline), isBodyInline: isBodyInline, isBody: isBody, isParaInline: isParaInline, isPre: isPre, isList: isList, isTable: isTable, isData: isData, isCell: isCell, isBlockquote: isBlockquote, isBodyContainer: isBodyContainer, isAnchor: isAnchor, isDiv: makePredByNodeName('DIV'), isLi: isLi, isBR: makePredByNodeName('BR'), isSpan: makePredByNodeName('SPAN'), isB: makePredByNodeName('B'), isU: makePredByNodeName('U'), isS: makePredByNodeName('S'), isI: makePredByNodeName('I'), isImg: makePredByNodeName('IMG'), isTextarea: isTextarea, isEmpty: isEmpty, isEmptyAnchor: func.and(isAnchor, isEmpty), isClosestSibling: isClosestSibling, withClosestSiblings: withClosestSiblings, nodeLength: nodeLength, isLeftEdgePoint: isLeftEdgePoint, isRightEdgePoint: isRightEdgePoint, isEdgePoint: isEdgePoint, isLeftEdgeOf: isLeftEdgeOf, isRightEdgeOf: isRightEdgeOf, isLeftEdgePointOf: isLeftEdgePointOf, isRightEdgePointOf: isRightEdgePointOf, prevPoint: prevPoint, nextPoint: nextPoint, isSamePoint: isSamePoint, isVisiblePoint: isVisiblePoint, prevPointUntil: prevPointUntil, nextPointUntil: nextPointUntil, isCharPoint: isCharPoint, walkPoint: walkPoint, ancestor: ancestor, singleChildAncestor: singleChildAncestor, listAncestor: listAncestor, lastAncestor: lastAncestor, listNext: listNext, listPrev: listPrev, listDescendant: listDescendant, commonAncestor: commonAncestor, wrap: wrap, insertAfter: insertAfter, appendChildNodes: appendChildNodes, position: position, hasChildren: hasChildren, makeOffsetPath: makeOffsetPath, fromOffsetPath: fromOffsetPath, splitTree: splitTree, splitPoint: splitPoint, create: create, createText: createText, remove: remove, removeWhile: removeWhile, replace: replace, html: html, value: value, posFromPlaceholder: posFromPlaceholder, attachEvents: attachEvents, detachEvents: detachEvents }; })(); /** * @param {jQuery} $note * @param {Object} options * @return {Context} */ var Context = function ($note, options) { var self = this; var ui = $.summernote.ui; this.memos = {}; this.modules = {}; this.layoutInfo = {}; this.options = options; /** * create layout and initialize modules and other resources */ this.initialize = function () { this.layoutInfo = ui.createLayout($note, options); this._initialize(); $note.hide(); return this; }; /** * destroy modules and other resources and remove layout */ this.destroy = function () { this._destroy(); $note.removeData('summernote'); ui.removeLayout($note, this.layoutInfo); }; /** * destory modules and other resources and initialize it again */ this.reset = function () { var disabled = self.isDisabled(); this.code(dom.emptyPara); this._destroy(); this._initialize(); if (disabled) { self.disable(); } }; this._initialize = function () { // add optional buttons var buttons = $.extend({}, this.options.buttons); Object.keys(buttons).forEach(function (key) { self.memo('button.' + key, buttons[key]); }); var modules = $.extend({}, this.options.modules, $.summernote.plugins || {}); // add and initialize modules Object.keys(modules).forEach(function (key) { self.module(key, modules[key], true); }); Object.keys(this.modules).forEach(function (key) { self.initializeModule(key); }); }; this._destroy = function () { // destroy modules with reversed order Object.keys(this.modules).reverse().forEach(function (key) { self.removeModule(key); }); Object.keys(this.memos).forEach(function (key) { self.removeMemo(key); }); }; this.code = function (html) { var isActivated = this.invoke('codeview.isActivated'); if (html === undefined) { this.invoke('codeview.sync'); return isActivated ? this.layoutInfo.codable.val() : this.layoutInfo.editable.html(); } else { if (isActivated) { this.layoutInfo.codable.val(html); } else { this.layoutInfo.editable.html(html); } $note.val(html); this.triggerEvent('change', html); } }; this.isDisabled = function () { return this.layoutInfo.editable.attr('contenteditable') === 'false'; }; this.enable = function () { this.layoutInfo.editable.attr('contenteditable', true); this.invoke('toolbar.activate', true); }; this.disable = function () { // close codeview if codeview is opend if (this.invoke('codeview.isActivated')) { this.invoke('codeview.deactivate'); } this.layoutInfo.editable.attr('contenteditable', false); this.invoke('toolbar.deactivate', true); }; this.triggerEvent = function () { var namespace = list.head(arguments); var args = list.tail(list.from(arguments)); var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')]; if (callback) { callback.apply($note[0], args); } $note.trigger('summernote.' + namespace, args); }; this.initializeModule = function (key) { var module = this.modules[key]; module.shouldInitialize = module.shouldInitialize || func.ok; if (!module.shouldInitialize()) { return; } // initialize module if (module.initialize) { module.initialize(); } // attach events if (module.events) { dom.attachEvents($note, module.events); } }; this.module = function (key, ModuleClass, withoutIntialize) { if (arguments.length === 1) { return this.modules[key]; } this.modules[key] = new ModuleClass(this); if (!withoutIntialize) { this.initializeModule(key); } }; this.removeModule = function (key) { var module = this.modules[key]; if (module.shouldInitialize()) { if (module.events) { dom.detachEvents($note, module.events); } if (module.destroy) { module.destroy(); } } delete this.modules[key]; }; this.memo = function (key, obj) { if (arguments.length === 1) { return this.memos[key]; } this.memos[key] = obj; }; this.removeMemo = function (key) { if (this.memos[key] && this.memos[key].destroy) { this.memos[key].destroy(); } delete this.memos[key]; }; this.createInvokeHandler = function (namespace, value) { return function (event) { event.preventDefault(); self.invoke(namespace, value || $(event.target).closest('[data-value]').data('value')); }; }; this.invoke = function () { var namespace = list.head(arguments); var args = list.tail(list.from(arguments)); var splits = namespace.split('.'); var hasSeparator = splits.length > 1; var moduleName = hasSeparator && list.head(splits); var methodName = hasSeparator ? list.last(splits) : list.head(splits); var module = this.modules[moduleName || 'editor']; if (!moduleName && this[methodName]) { return this[methodName].apply(this, args); } else if (module && module[methodName] && module.shouldInitialize()) { return module[methodName].apply(module, args); } }; return this.initialize(); }; $.fn.extend({ /** * Summernote API * * @param {Object|String} * @return {this} */ summernote: function () { var type = $.type(list.head(arguments)); var isExternalAPICalled = type === 'string'; var hasInitOptions = type === 'object'; var options = hasInitOptions ? list.head(arguments) : {}; options = $.extend({}, $.summernote.options, options); options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]); options.icons = $.extend(true, {}, $.summernote.options.icons, options.icons); this.each(function (idx, note) { var $note = $(note); if (!$note.data('summernote')) { var context = new Context($note, options); $note.data('summernote', context); $note.data('summernote').triggerEvent('init', context.layoutInfo); } }); var $note = this.first(); if ($note.length) { var context = $note.data('summernote'); if (isExternalAPICalled) { return context.invoke.apply(context, list.from(arguments)); } else if (options.focus) { context.invoke('editor.focus'); } } return this; } }); var Renderer = function (markup, children, options, callback) { this.render = function ($parent) { var $node = $(markup); if (options && options.contents) { $node.html(options.contents); } if (options && options.className) { $node.addClass(options.className); } if (options && options.data) { $.each(options.data, function (k, v) { $node.attr('data-' + k, v); }); } if (options && options.click) { $node.on('click', options.click); } if (children) { var $container = $node.find('.note-children-container'); children.forEach(function (child) { child.render($container.length ? $container : $node); }); } if (callback) { callback($node, options); } if (options && options.callback) { options.callback($node); } if ($parent) { $parent.append($node); } return $node; }; }; var renderer = { create: function (markup, callback) { return function () { var children = $.isArray(arguments[0]) ? arguments[0] : []; var options = typeof arguments[1] === 'object' ? arguments[1] : arguments[0]; if (options && options.children) { children = options.children; } return new Renderer(markup, children, options, callback); }; } }; var editor = renderer.create(''); var toolbar = renderer.create(''); var editingArea = renderer.create(''); var codable = renderer.create(''); var editable = renderer.create(''); var statusbar = renderer.create([ '' ].join('')); var airEditor = renderer.create(''); var airEditable = renderer.create(''); var buttonGroup = renderer.create('